From 90bb7ac4c9810fc676f2ee1b64c3a23f60611faa Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Thu, 26 Nov 2026 17:05:51 +0000 Subject: [PATCH 1/8] Update vendored DuckDB sources to a28f463cffd --- CMakeLists.txt | 1 + .../aggregate/distributive/arg_min_max.cpp | 12 + .../extension/parquet/column_reader.cpp | 19 +- .../extension/parquet/column_writer.cpp | 15 +- .../parquet/include/column_reader.hpp | 2 + .../parquet/include/parquet_decimal_utils.hpp | 6 +- .../writer/parquet_write_operators.hpp | 67 ++-- .../include/writer/parquet_write_stats.hpp | 78 +++++ .../writer/templated_column_writer.hpp | 5 +- .../extension/parquet/parquet_crypto.cpp | 13 +- .../extension/parquet/parquet_extension.cpp | 5 +- .../extension/parquet/parquet_reader.cpp | 12 +- .../extension/parquet/parquet_statistics.cpp | 17 +- .../extension/parquet/parquet_writer.cpp | 18 +- .../parquet/reader/decimal_column_reader.cpp | 38 +-- ...nerated_extension_loader_package_build.cpp | 8 +- src/duckdb/src/common/enum_util.cpp | 7 +- .../src/common/row_operations/row_matcher.cpp | 13 +- .../types/column/column_data_collection.cpp | 148 ++++++--- .../column/column_data_collection_segment.cpp | 55 +++- .../common/types/variant/variant_writer.cpp | 138 +++++++++ .../comparison_operators.cpp | 4 +- .../vector_operations/string_comparison.cpp | 97 ++++++ .../execute_comparison.cpp | 5 +- src/duckdb/src/execution/join_hashtable.cpp | 275 ++++++++++++----- .../csv_scanner/encode/csv_encoder.cpp | 22 +- .../operator/persistent/physical_insert.cpp | 4 +- .../operator/schema/physical_create_index.cpp | 4 +- src/duckdb/src/function/builtin_encodings.cpp | 55 +++- .../scalar/variant/variant_path_function.cpp | 161 +++------- .../function/scalar/variant/variant_value.cpp | 25 +- src/duckdb/src/function/table/read_duckdb.cpp | 158 +++++++++- .../function/table/version/pragma_version.cpp | 6 +- .../function/window/window_value_function.cpp | 2 + .../common/multi_file/multi_file_function.hpp | 4 +- .../common/operator/comparison_operators.hpp | 32 ++ .../column/column_data_collection_segment.hpp | 19 +- .../duckdb/common/types/selection_vector.hpp | 5 + .../duckdb/common/types/string_type.hpp | 56 +++- .../duckdb/common/types/variant_writer.hpp | 286 ++++++++++++++++++ .../duckdb/common/unordered_multimap.hpp | 15 + .../duckdb/common/vector/vector_writer.hpp | 8 + .../vector_operations/string_comparison.hpp | 93 ++++++ .../duckdb/execution/join_hashtable.hpp | 11 + .../csv_scanner/encode/csv_encoder.hpp | 7 +- .../function/scalar/variant_path_function.hpp | 40 +-- .../duckdb/function/window_function.hpp | 4 + .../duckdb/main/capi_v2/extension_api_v2.hpp | 3 + .../src/include/duckdb/main/client_data.hpp | 2 + .../join_order/join_relation_set.hpp | 19 +- .../join_order/query_graph_manager.hpp | 6 +- .../rule/comparison_simplification.hpp | 9 + .../optimizer/topn_window_elimination.hpp | 2 + .../expression/bound_aggregate_expression.hpp | 2 + .../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 | 5 + src/duckdb/src/include/duckdb_v2.h | 25 ++ src/duckdb/src/main/capi/v2/capi_v2_value.cpp | 24 ++ src/duckdb/src/main/client_verify.cpp | 24 +- .../apply_functional_dependencies.cpp | 6 + .../optimizer/common_subplan_optimizer.cpp | 10 +- .../src/optimizer/expression_rewriter.cpp | 5 +- .../join_order/cardinality_estimator.cpp | 61 +++- .../join_order/join_relation_set.cpp | 49 ++- .../join_order/query_graph_manager.cpp | 74 +++-- .../rule/comparison_simplification.cpp | 26 ++ .../src/optimizer/topn_window_elimination.cpp | 51 ++-- .../src/parser/parsed_expression_iterator.cpp | 29 +- .../planner/sql_export/sql_export_window.cpp | 12 +- src/duckdb/src/planner/table_filter_state.cpp | 43 ++- src/duckdb/src/storage/data_table.cpp | 8 +- src/duckdb/src/storage/local_storage.cpp | 147 +++++---- src/duckdb/ub_src_common_types_variant.cpp | 2 + 75 files changed, 2134 insertions(+), 632 deletions(-) create mode 100644 src/duckdb/src/common/types/variant/variant_writer.cpp create mode 100644 src/duckdb/src/common/vector_operations/string_comparison.cpp create mode 100644 src/duckdb/src/include/duckdb/common/types/variant_writer.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 diff --git a/CMakeLists.txt b/CMakeLists.txt index e6b2b45a4..9d3747f0e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -180,6 +180,7 @@ 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 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/parquet/column_reader.cpp b/src/duckdb/extension/parquet/column_reader.cpp index bdb3e8390..758d95687 100644 --- a/src/duckdb/extension/parquet/column_reader.cpp +++ b/src/duckdb/extension/parquet/column_reader.cpp @@ -289,6 +289,9 @@ bool ColumnReader::TrySkipPagesWithOffsetIndex(idx_t skipped_so_far, idx_t &to_s // no page index, or still inside a page return false; } + // this path does not maintain page_ordinal, which is safe only while + // the page index is never used for encrypted files + D_ASSERT(!reader.parquet_options.encryption_config); auto &trans = reinterpret_cast(*protocol->getTransport()); auto &locations = offset_index->page_locations; while (trans.GetLocation() < NumericCast(locations[0].offset)) { @@ -497,7 +500,7 @@ bool ColumnReader::PageIsFilteredOut(PageHeader &page_hdr, optional_ptr(*protocol->getTransport()); - trans.Skip(page_hdr.compressed_page_size); + trans.Skip(GetOnDiskPageSize(page_hdr)); page_rows_available = is_v1 ? v1_header.num_values : v2_header.num_values; } @@ -575,7 +578,7 @@ void ColumnReader::PrepareRead(optional_ptr filter, optional_ idx_t page_num_values = NumericCast(is_v1 ? page_hdr.data_page_header.num_values : page_hdr.data_page_header_v2.num_values); if (rows_to_skip >= page_num_values) { - trans.Skip(page_hdr.compressed_page_size); + trans.Skip(GetOnDiskPageSize(page_hdr)); page_is_filtered_out = true; page_rows_available = page_num_values; return; @@ -713,6 +716,15 @@ uint32_t ColumnReader::GetPageBodySize(const PageHeader &page_hdr) const { return page_body_size; } +uint32_t ColumnReader::GetOnDiskPageSize(const PageHeader &page_hdr) const { + if (!reader.parquet_options.encryption_config) { + return NumericCast(page_hdr.compressed_page_size); + } + // an encrypted page body is stored as a single crypto module: length + nonce + ciphertext + tag + const uint32_t framing = ParquetCrypto::LENGTH_BYTES + ParquetCrypto::NONCE_BYTES + ParquetCrypto::TAG_BYTES; + return GetPageBodySize(page_hdr) + framing; +} + void ColumnReader::AllocateBlock(idx_t payload_size) { const auto allocation_size = payload_size + 1; if (!block) { @@ -1371,9 +1383,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 3df01125f..8225de5da 100644 --- a/src/duckdb/extension/parquet/include/column_reader.hpp +++ b/src/duckdb/extension/parquet/include/column_reader.hpp @@ -422,6 +422,8 @@ class ColumnReader { void PreparePageV2(PageHeader &page_hdr); //! The size of the page body in the file, without the encryption framing that Arrow includes uint32_t GetPageBodySize(const PageHeader &page_hdr) const; + //! The number of bytes the page body occupies in the file, including any encryption framing + uint32_t GetOnDiskPageSize(const PageHeader &page_hdr) const; void DecompressInternal(CompressionCodec::type codec, const_data_ptr_t src, idx_t src_size, data_ptr_t dst, idx_t dst_size); const ColumnChunk *chunk = nullptr; 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/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_crypto.cpp b/src/duckdb/extension/parquet/parquet_crypto.cpp index 922e671ad..ed92302c8 100644 --- a/src/duckdb/extension/parquet/parquet_crypto.cpp +++ b/src/duckdb/extension/parquet/parquet_crypto.cpp @@ -514,6 +514,15 @@ int8_t ParquetCrypto::GetModule(const ColumnChunk &chunk, PageType::type page_ty } } +static int16_t CheckedPageOrdinal(uint16_t page_ordinal) { + if (page_ordinal > NumericCast(NumericLimits::Maximum())) { + throw InvalidInputException("An encrypted column chunk has more than %d data pages, exceeding the maximum " + "page ordinal supported by Parquet modular encryption", + NumericLimits::Maximum() + 1); + } + return NumericCast(page_ordinal); +} + int16_t ParquetCrypto::GetFinalPageOrdinal(const ColumnChunk &chunk, uint8_t module, uint16_t page_ordinal) { switch (module) { case DATA_PAGE_HEADER: @@ -524,9 +533,9 @@ int16_t ParquetCrypto::GetFinalPageOrdinal(const ColumnChunk &chunk, uint8_t mod } else if (chunk.meta_data.__isset.bloom_filter_offset) { page_ordinal -= 1; } - return NumericCast(page_ordinal); + return CheckedPageOrdinal(page_ordinal); case DATA_PAGE: - return NumericCast(page_ordinal); + return CheckedPageOrdinal(page_ordinal); default: // All modules except DataPage(Header) are -1 (absent) return -1; diff --git a/src/duckdb/extension/parquet/parquet_extension.cpp b/src/duckdb/extension/parquet/parquet_extension.cpp index 6f3e0e5e5..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; }); diff --git a/src/duckdb/extension/parquet/parquet_reader.cpp b/src/duckdb/extension/parquet/parquet_reader.cpp index 5b6899df1..b1accb7f0 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: @@ -1997,7 +1989,7 @@ void ParquetReader::PrepareRowGroupBuffer(ClientContext &context, ParquetReaderS auto &column_reader = state.GetColumnReader(col_idx); // keep track of column and row group ordinal if data is encrypted - if (metadata->crypto_metadata && metadata->crypto_metadata->encryption_algorithm.__isset.AES_GCM_CTR_V1) { + if (metadata->crypto_metadata && metadata->crypto_metadata->encryption_algorithm.__isset.AES_GCM_V1) { column_reader.InitializeCryptoMetadata(metadata->crypto_metadata->encryption_algorithm, GetGroup(state).ordinal); } 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 57429e40b..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", @@ -1273,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); 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/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 904ed328e..07e0650e6 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-alpha57804"; + descriptor->api_version = "v2.1.0-alpha57892"; 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-alpha57804"; + descriptor->api_version = "v2.1.0-alpha57892"; 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-alpha57804"; + descriptor->api_version = "v2.1.0-alpha57892"; 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-alpha57804"; + descriptor->api_version = "v2.1.0-alpha57892"; 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 87072888a..442a0f269 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -1418,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() { 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/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/variant/variant_writer.cpp b/src/duckdb/src/common/types/variant/variant_writer.cpp new file mode 100644 index 000000000..f2922fba7 --- /dev/null +++ b/src/duckdb/src/common/types/variant/variant_writer.cpp @@ -0,0 +1,138 @@ +#include "duckdb/common/types/variant_writer.hpp" + +namespace duckdb { + +namespace { + +//! Copies the list entries of the rows to 'target', moved to start at 'offset' +void CopyListEntries(list_entry_t *target, const vector &entries, idx_t offset) { + const auto count = entries.size(); + const auto source = entries.data(); + if (offset == 0) { + memcpy(target, source, count * sizeof(list_entry_t)); + return; + } + for (idx_t i = 0; i < count; i++) { + target[i] = list_entry_t(source[i].offset + offset, source[i].length); + } +} + +} // namespace + +VectorWriter::VectorWriter(Vector &vector, idx_t count, idx_t offset) + : variant(vector), start_idx(offset), count(offset + count), current_idx(offset) { +} + +VectorWriter::VectorWriter(VectorWriter &&other) noexcept + : variant(other.variant), state(std::move(other.state)), start_idx(other.start_idx), count(other.count), + current_idx(other.current_idx) { + other.count = other.current_idx; +} + +VectorWriter::~VectorWriter() { // NOLINT(bugprone-exception-escape): only the allocations can throw + D_ASSERT(Exception::UncaughtException() || current_idx == count); + if (state && !Exception::UncaughtException()) { + Finalize(); + } +} + +void VectorWriter::InitializeState() { + state = make_uniq(); + const auto row_count = count - current_idx; + state->keys.reserve(row_count); + state->children.reserve(row_count); + state->values.reserve(row_count); + state->blobs.reserve(row_count); +} + +StringHeap &VectorWriter::InitializeBlobHeap() { + state->blob_heap = StringVector::GetStringHeap(VariantVector::GetData(variant)); + return *state->blob_heap; +} + +void VectorWriter::ThrowRowTooLarge() { + throw InvalidInputException( + "Cannot convert value to VARIANT: encoded row size exceeds the maximum supported %u bytes", + NumericLimits::Maximum()); +} + +void VectorWriter::EmitContainer(const VariantNode &node, VariantBuilder &builder) { + EmitIterator(node, builder); +} + +void VectorWriter::Finalize() { + auto &writer_state = *state; + auto &builder = writer_state.builder; + const auto row_count = writer_state.blobs.size(); + D_ASSERT(row_count == current_idx - start_idx); + if (row_count == 0) { + return; + } + + auto &keys = VariantVector::GetKeys(variant); + auto &keys_entry = ListVector::GetChildMutable(keys); + auto &children = VariantVector::GetChildren(variant); + auto &values = VariantVector::GetValues(variant); + + const auto keys_offset = ListVector::GetListSize(keys); + const auto children_offset = ListVector::GetListSize(children); + const auto values_offset = ListVector::GetListSize(values); + const auto total_keys = builder.key_slots.size(); + const auto total_children = builder.child_value_ids.size(); + const auto total_values = builder.type_ids.size(); + + //! BuildVariant leaves the keys as a dictionary, the new keys are written flat after the existing ones + if (keys_entry.GetVectorType() != VectorType::FLAT_VECTOR) { + keys_entry.Flatten(); + } + ListVector::Reserve(keys, keys_offset + total_keys); + ListVector::SetListSize(keys, keys_offset + total_keys); + ListVector::Reserve(children, children_offset + total_children); + ListVector::SetListSize(children, children_offset + total_children); + ListVector::Reserve(values, values_offset + total_values); + ListVector::SetListSize(values, values_offset + total_values); + + //! rows + VariantVectorData variant_data(variant); + CopyListEntries(variant_data.keys_data + start_idx, writer_state.keys, keys_offset); + CopyListEntries(variant_data.children_data + start_idx, writer_state.children, children_offset); + CopyListEntries(variant_data.values_data + start_idx, writer_state.values, values_offset); + memcpy(variant_data.blob_data + start_idx, writer_state.blobs.data(), row_count * sizeof(string_t)); + for (auto row : writer_state.null_rows) { + FlatVector::SetNull(variant, start_idx + row, true); + } + + //! values + if (total_values) { + memcpy(variant_data.type_ids_data + values_offset, builder.type_ids.data(), total_values * sizeof(uint8_t)); + memcpy(variant_data.byte_offset_data + values_offset, builder.byte_offsets.data(), + total_values * sizeof(uint32_t)); + } + + //! children + const auto child_value_ids = builder.child_value_ids.data(); + const auto child_key_ids = builder.child_key_ids.data(); + for (idx_t i = 0; i < total_children; i++) { + const auto child_idx = children_offset + i; + variant_data.values_index_data[child_idx] = child_value_ids[i]; + if (child_key_ids[i] == VARIANT_INVALID_KEY) { + variant_data.keys_index_validity.SetInvalid(child_idx); + } else { + variant_data.keys_index_data[child_idx] = child_key_ids[i]; + } + } + + //! keys: copy each distinct key into the keys vector once, then point every key slot at its copy + vector dictionary_keys(writer_state.dictionary.size()); + const auto dictionary_data = dictionary_keys.data(); + for (auto &entry : writer_state.dictionary) { + dictionary_data[entry.second] = StringVector::AddStringOrBlob(keys_entry, entry.first); + } + const auto key_slots = builder.key_slots.data(); + auto keys_entry_data = FlatVector::GetDataMutable(keys_entry); + for (idx_t i = 0; i < total_keys; i++) { + keys_entry_data[keys_offset + i] = dictionary_data[key_slots[i]]; + } +} + +} // namespace duckdb 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/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/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/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/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/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/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/scalar/variant/variant_path_function.cpp b/src/duckdb/src/function/scalar/variant/variant_path_function.cpp index ceb73139c..b513fdb3a 100644 --- a/src/duckdb/src/function/scalar/variant/variant_path_function.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_path_function.cpp @@ -1,71 +1,8 @@ #include "duckdb/function/scalar/variant_path_function.hpp" -#include "duckdb/common/types/variant/variant_builder.hpp" -#include "duckdb/common/vector/list_vector.hpp" +#include "duckdb/common/numeric_utils.hpp" namespace duckdb { -namespace { - -//! Emits a primitive directly, only containers need the traversal of EmitIterator -void EmitSelectedNode(const VariantNode &node, VariantBuilder &builder) { - if (!node.IsNull() && !node.IsMissing()) { - const auto type = node.GetTypeId(); - if (type != LogicalTypeId::STRUCT && type != LogicalTypeId::LIST) { - builder.EmitPrimitiveNode(node); - return; - } - } - EmitIterator(node, builder); -} - -//! Emits the value selected for each row, or a NULL if it is missing or not kept -template -struct SelectedVariantSource { - bool Emit(idx_t row, VariantBuilder &builder) const { - const auto node = select_fn(row); - if (!node || !keep(*node)) { - return true; - } - EmitSelectedNode(*node, builder); - return false; - } - - const SELECT_FUNCTION &select_fn; - variant_node_filter_t keep; -}; - -template -void BuildSelectedVariants(idx_t count, Vector &result, variant_node_filter_t keep, const SELECT_FUNCTION &select_fn) { - SelectedVariantSource source {select_fn, keep}; - result.Initialize(VectorDataInitialization::UNINITIALIZED, count); - BuildVariant(source, count, result); -} - -} // namespace - -void VariantPathFunction::ExecuteVariant(DataChunk &input, const ExpressionState &state, Vector &result, - variant_node_filter_t keep) { - D_ASSERT(input.ColumnCount() == 1 || input.ColumnCount() == 2); - const auto count = input.size(); - const auto &variant_vec = input.data[0]; - - if (input.ColumnCount() == 1) { - ExecuteVariantUnary(variant_vec, {}, result, count, keep); - return; - } - D_ASSERT(input.data[1].GetVectorType() == VectorType::CONSTANT_VECTOR); - - auto &func_expr = state.expr.Cast(); - auto &info = func_expr.BindInfo()->Cast(); - const auto path_type_id = input.data[1].GetType().id(); - if (path_type_id == LogicalTypeId::LIST) { - ExecuteVariantMany(variant_vec, info.paths, result, count, keep); - return; - } - D_ASSERT(path_type_id == LogicalTypeId::VARCHAR || path_type_id == LogicalTypeId::BIGINT); - ExecuteVariantUnary(variant_vec, info.paths[0], result, count, keep); -} - optional VariantPathFunction::ResolveIndex(const VariantNode &node, int64_t index) { if (node.IsNull() || node.IsMissing() || node.GetTypeId() != LogicalTypeId::LIST) { return {}; @@ -86,80 +23,50 @@ optional VariantPathFunction::ResolveIndex(const VariantNode &node, return elements[length - 1 - from_end]; } -void VariantPathFunction::ExecuteVariantUnary(const Vector &input, const vector &path, - Vector &result, idx_t count, variant_node_filter_t keep) { - const VectorIterator variants(input); - BuildSelectedVariants(count, result, keep, [&](idx_t row) -> optional { - if (!variants.RowIsValid(row)) { - return {}; +vector> VariantPathFunction::GetSingleKeys(const vector> &paths) { + vector> keys(paths.size()); + for (idx_t path_idx = 0; path_idx < paths.size(); path_idx++) { + const auto &path = paths[path_idx]; + if (path.size() == 1 && path[0].lookup_mode == VariantChildLookupMode::BY_KEY) { + keys[path_idx] = string_t(path[0].key.c_str(), NumericCast(path[0].key.size())); } - return ResolvePath(variants[row], path); - }); + } + return keys; } -void VariantPathFunction::ExecuteVariantMany(const Vector &input, const vector> &paths, - Vector &result, idx_t count, variant_node_filter_t keep) { - const VectorIterator variants(input); +void VariantPathFunction::ResolvePaths(const VariantNode &root, const vector> &paths, + const vector> &keys, + vector> &selected) { + //! Copied into locals so the matching loop keeps them in registers const auto path_count = paths.size(); + const auto key_data = keys.data(); + const auto selected_data = selected.data(); - //! The key of each single key path, these are resolved in one pass over the children of the object - vector> keys(path_count); - idx_t key_count = 0; + idx_t pending = 0; for (idx_t path_idx = 0; path_idx < path_count; path_idx++) { - const auto &path = paths[path_idx]; - if (path.size() == 1 && path[0].lookup_mode == VariantChildLookupMode::BY_KEY) { - keys[path_idx] = string_t(path[0].key.c_str(), NumericCast(path[0].key.size())); - key_count++; + if (key_data[path_idx]) { + selected_data[path_idx].reset(); + pending++; + } else { + selected_data[path_idx] = ResolvePath(root, paths[path_idx]); } } - - result.Initialize(VectorDataInitialization::UNINITIALIZED, count); - //! The elements of a row hold its value at each of the paths in order - vector> selected; - selected.reserve(count * path_count); - { - auto list_writer = FlatVector::Writer(result, count); - for (idx_t row = 0; row < count; row++) { - if (!variants.RowIsValid(row)) { - list_writer.WriteNull(); - continue; - } - const auto offset = selected.size(); - list_writer.WriteValue(list_entry_t(offset, path_count)); - selected.resize(offset + path_count); - const auto root = variants[row]; - for (idx_t path_idx = 0; path_idx < path_count; path_idx++) { - if (!keys[path_idx]) { - selected[offset + path_idx] = ResolvePath(root, paths[path_idx]); - } - } - if (key_count == 0 || root.IsNull() || root.IsMissing() || root.GetTypeId() != LogicalTypeId::STRUCT) { - continue; - } - auto pending = key_count; - for (const auto &entry : root.GetObjectChildren()) { - for (idx_t path_idx = 0; path_idx < path_count; path_idx++) { - auto &value = selected[offset + path_idx]; - const auto &key = keys[path_idx]; - if (key && !value && *key == entry.key) { - value = entry.value; - pending--; - } - } - if (pending == 0) { - break; - } + if (pending == 0 || root.IsNull() || root.IsMissing() || root.GetTypeId() != LogicalTypeId::STRUCT) { + return; + } + for (const auto &entry : root.GetObjectChildren()) { + for (idx_t path_idx = 0; path_idx < path_count; path_idx++) { + auto &value = selected_data[path_idx]; + const auto &key = key_data[path_idx]; + if (key && !value && *key == entry.key) { + value = entry.value; + pending--; } } + if (pending == 0) { + break; + } } - const auto element_count = selected.size(); - if (element_count == 0) { - return; - } - Vector elements(LogicalType::VARIANT(), element_count); - BuildSelectedVariants(element_count, elements, keep, - [&](idx_t element_idx) -> const optional & { return selected[element_idx]; }); - ListVector::Append(result, elements, element_count); } ScalarFunctionSet VariantPathFunction::CreateFunctionSet(const Identifier &name, const scalar_function_t &function, diff --git a/src/duckdb/src/function/scalar/variant/variant_value.cpp b/src/duckdb/src/function/scalar/variant/variant_value.cpp index 1505d1b29..37b785bc0 100644 --- a/src/duckdb/src/function/scalar/variant/variant_value.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_value.cpp @@ -7,12 +7,9 @@ namespace duckdb { namespace { -//! Whether the selected value is returned, OBJECT, ARRAY and VARIANT_NULL values are not -bool IsScalarValue(const VariantNode &node) { - if (node.IsNull() || node.IsMissing()) { - return false; - } - switch (node.GetTypeId()) { +//! Whether a value of this type is returned, OBJECT, ARRAY and VARIANT_NULL values are not +bool IsScalarType(LogicalTypeId type) { + switch (type) { case LogicalTypeId::SQLNULL: case LogicalTypeId::STRUCT: case LogicalTypeId::LIST: @@ -22,8 +19,22 @@ bool IsScalarValue(const VariantNode &node) { } } +//! Writes the selected value, or a NULL if it is missing or not a scalar +void WriteValueResult(const optional &node, VectorWriter &value_writer) { + if (!node || node->IsNull() || node->IsMissing()) { + value_writer.WriteNull(); + return; + } + const auto type = node->GetTypeId(); + if (!IsScalarType(type)) { + value_writer.WriteNull(); + return; + } + value_writer.WriteValue(*node, type); +} + void VariantValueFunction(DataChunk &input, ExpressionState &state, Vector &result) { - VariantPathFunction::ExecuteVariant(input, state, result, IsScalarValue); + VariantPathFunction::Execute(input, state, result, WriteValueResult); } } // namespace 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/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index 1e2a42de6..dc898f311 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-alpha57804" +#define DUCKDB_PATCH_VERSION "0-alpha57892" #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-alpha57804" +#define DUCKDB_VERSION "v2.1.0-alpha57892" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "ad9c3430fc" +#define DUCKDB_SOURCE_ID "a28f463cff" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" 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/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/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/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_writer.hpp b/src/duckdb/src/include/duckdb/common/types/variant_writer.hpp new file mode 100644 index 000000000..2fad0fb66 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/types/variant_writer.hpp @@ -0,0 +1,286 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/types/variant_writer.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/vector/vector_writer.hpp" +#include "duckdb/common/types/variant/variant_builder.hpp" +#include "duckdb/common/unique_ptr.hpp" + +namespace duckdb { + +//! The rows collected by a VectorWriter +struct VariantWriterState { + VariantWriterState() : keys_arena(Allocator::DefaultAllocator()), builder(dictionary, keys_arena) { + } + + //! owns the keys of the dictionary, they are copied into the keys vector when the rows are written + ArenaAllocator keys_arena; + OrderedOwningStringMap dictionary; + VariantBuilder builder; + //! per row: its keys, children and values in the builder, and its encoded value (owned by the data vector) + vector keys; + vector children; + vector values; + vector blobs; + //! the rows written as SQL NULL, relative to the first row of the writer + vector null_rows; + //! the heap of the data vector, looked up when the first blob that is not inlined is written + optional_ptr blob_heap; +}; + +//! Specialization of VectorWriter for VectorVariantType. +//! The rows are collected in a single VariantBuilder and written to the vector when the writer is destroyed. The +//! keys, children and values of the rows are appended to the ones already in the vector. +template <> +struct VectorWriter { + DUCKDB_API VectorWriter(Vector &vector, idx_t count, idx_t offset); + DUCKDB_API VectorWriter(VectorWriter &&other) noexcept; + DUCKDB_API ~VectorWriter(); + + //! Write a SQL NULL + void WriteNull() { + D_ASSERT(current_idx < count); + auto &writer_state = GetState(); + auto &builder = writer_state.builder; + writer_state.null_rows.push_back(current_idx - start_idx); + writer_state.keys.emplace_back(builder.key_slots.size(), 0); + writer_state.children.emplace_back(builder.child_value_ids.size(), 0); + writer_state.values.emplace_back(builder.type_ids.size(), 0); + writer_state.blobs.emplace_back(0U); + current_idx++; + } + + //! Write a copy of the value 'node' points at. A NULL or missing node is written as a VARIANT null value. + void WriteValue(const VariantNode &node) { + if (node.IsNull() || node.IsMissing()) { + D_ASSERT(current_idx < count); + auto &builder = GetState().builder; + builder.BeginRow(); + builder.EmitNull(); + FinishRow(); + return; + } + WriteNode(node, VariantNodeStorageAccess::GetStorageType(node)); + } + + //! Write a copy of the value 'node' points at, for a node that is not NULL or missing and whose type is 'type'. + //! Saves looking up the type again when the caller already has it. + void WriteValue(const VariantNode &node, LogicalTypeId type) { + D_ASSERT(!node.IsNull() && !node.IsMissing() && node.GetTypeId() == type); + WriteNode(node, VariantTypeFromLogicalTypeId(type, type == LogicalTypeId::BOOLEAN && node.GetBool())); + } + + void Truncate() noexcept { + count = current_idx; + } + +private: + friend struct VectorWriter>; + friend class DynamicListWriter; + + //! Allow 'n' more rows to be written, used by the LIST(VARIANT) writer to write all elements through one writer + void Extend(idx_t n) { + count += n; + } + + VariantWriterState &GetState() { + if (!state) { + InitializeState(); + } + return *state; + } + + void WriteNode(const VariantNode &node, VariantLogicalType type_id) { + D_ASSERT(current_idx < count); + auto &builder = GetState().builder; + builder.BeginRow(); + if (type_id == VariantLogicalType::OBJECT || type_id == VariantLogicalType::ARRAY) { + EmitContainer(node, builder); + } else { + builder.EmitPrimitiveNode(node, type_id); + } + FinishRow(); + } + + //! Records the row the builder just emitted + void FinishRow() { + auto &writer_state = *state; + auto &builder = writer_state.builder; + const auto blob_size = builder.blob.size(); + if (blob_size > NumericLimits::Maximum()) { + ThrowRowTooLarge(); + } + writer_state.keys.emplace_back(builder.row_keys, builder.key_slots.size() - builder.row_keys); + writer_state.children.emplace_back(builder.row_children, builder.child_value_ids.size() - builder.row_children); + writer_state.values.emplace_back(builder.row_values, builder.type_ids.size() - builder.row_values); + string_t blob(builder.blob.data(), static_cast(blob_size)); + if (!blob.IsInlined()) { + auto &heap = writer_state.blob_heap ? *writer_state.blob_heap : InitializeBlobHeap(); + blob = heap.AddBlob(blob); + } + writer_state.blobs.push_back(blob); + current_idx++; + } + + DUCKDB_API void InitializeState(); + DUCKDB_API StringHeap &InitializeBlobHeap(); + DUCKDB_API static void ThrowRowTooLarge(); + DUCKDB_API static void EmitContainer(const VariantNode &node, VariantBuilder &builder); + void Finalize(); + +private: + Vector &variant; + unique_ptr state; + idx_t start_idx; + idx_t count; + idx_t current_idx; +}; + +//! Specialization of VectorWriter for VectorListType. +//! The elements of all lists are written through a single VARIANT writer, so they share one VariantBuilder instead +//! of creating one per list. +template <> +struct VectorWriter> { +public: + //! Range returned by WriteList(n), yields the shared element writer once for each of the n elements + struct WriteRange { + class RangeIterator { + public: + RangeIterator(VectorWriter &writer, idx_t pos) : writer(writer), pos(pos) { + } + VectorWriter &operator*() { + return writer; + } + RangeIterator &operator++() { // NOLINT: match stl API + ++pos; + return *this; + } + bool operator!=(const RangeIterator &other) const { + return pos != other.pos; + } + + private: + VectorWriter &writer; + idx_t pos; + }; + + WriteRange(VectorWriter &child_writer, idx_t n) : child_writer(child_writer), length(n) { + } + + RangeIterator begin() { // NOLINT: match stl API + return RangeIterator(child_writer, 0); + } + RangeIterator end() { // NOLINT: match stl API + return RangeIterator(child_writer, length); + } + + VectorWriter &child_writer; + idx_t length; + }; + +public: + VectorWriter(Vector &vector, idx_t count, idx_t offset) + : list_data(FlatVector::GetDataMutable(vector)), validity(FlatVector::ValidityMutable(vector)), + list_vec(vector), count(offset + count), current_idx(offset), child_offset(VectorWriterGetListSize(vector)), + child_writer(VectorWriterGetListChild(vector), 0, child_offset) { + } + VectorWriter(VectorWriter &&other) noexcept + : list_data(other.list_data), validity(other.validity), list_vec(other.list_vec), count(other.count), + current_idx(other.current_idx), child_offset(other.child_offset), + child_writer(std::move(other.child_writer)) { + other.count = other.current_idx; + } + ~VectorWriter() { + D_ASSERT(Exception::UncaughtException() || current_idx == count); + } + + void WriteNull() { + D_ASSERT(current_idx < count); + validity.SetInvalid(current_idx); + current_idx++; + } + + void Truncate() noexcept { + count = current_idx; + } + + //! Reserve n elements, record the list entry for this row, and return a WriteRange over the element writer. + //! All n elements must be written before the next list is opened. + WriteRange WriteList(idx_t n) { + D_ASSERT(current_idx < count); + // the elements of the previous list must all have been written + D_ASSERT(child_writer.current_idx == child_offset); + VectorWriterReserveList(list_vec, child_offset + n); + VectorWriterSetListSize(list_vec, child_offset + n); + list_data[current_idx] = {child_offset, n}; + current_idx++; + child_offset += n; + child_writer.Extend(n); + return WriteRange(child_writer, n); + } + + //! Open a list whose final length is unknown. Each WriteElement() call on the returned writer allows one more + //! element to be written; the list entry is recorded when it goes out of scope. + DynamicListWriter WriteDynamicList(); + +private: + friend class DynamicListWriter; + + list_entry_t *list_data; + ValidityMask &validity; + Vector &list_vec; + idx_t count; + idx_t current_idx; + idx_t child_offset; + //! Writes the elements of all lists, its rows start at the list size of the vector when this writer was created + VectorWriter child_writer; +}; + +//! Writer for a single LIST(VARIANT) list whose final length is unknown. Every element is written through the shared +//! element writer of the parent, so there is nothing to rebuild when the list grows. +template <> +class DynamicListWriter { +public: + DynamicListWriter(VectorWriter> &parent, idx_t row_idx) + : parent(parent), row_idx(row_idx), length(0) { + } + DynamicListWriter(const DynamicListWriter &) = delete; + DynamicListWriter(DynamicListWriter &&) = delete; + ~DynamicListWriter() { // NOLINT(bugprone-exception-escape): WriteElement reserved the capacity of the list + D_ASSERT(Exception::UncaughtException() || parent.child_writer.current_idx == parent.child_offset + length); + parent.list_data[row_idx] = {parent.child_offset, length}; + parent.child_offset += length; + VectorWriterSetListSize(parent.list_vec, parent.child_offset); + } + + //! Returns the element writer, which must be used to write exactly one value before WriteElement() is called again + VectorWriter &WriteElement() { + // the previous element must have been written + D_ASSERT(parent.child_writer.current_idx == parent.child_offset + length); + length++; + VectorWriterReserveList(parent.list_vec, parent.child_offset + length); + parent.child_writer.Extend(1); + return parent.child_writer; + } + +private: + VectorWriter> &parent; + idx_t row_idx; + idx_t length; +}; + +inline DynamicListWriter VectorWriter>::WriteDynamicList() { + D_ASSERT(current_idx < count); + D_ASSERT(child_writer.current_idx == child_offset); + const auto row_idx = current_idx; + current_idx++; + return DynamicListWriter(*this, row_idx); +} + +} // namespace duckdb 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/vector_writer.hpp b/src/duckdb/src/include/duckdb/common/vector/vector_writer.hpp index 1681a9aa7..0e01f4599 100644 --- a/src/duckdb/src/include/duckdb/common/vector/vector_writer.hpp +++ b/src/duckdb/src/include/duckdb/common/vector/vector_writer.hpp @@ -422,6 +422,14 @@ inline DynamicListWriter VectorWriter>::WriteDynamicList() return DynamicListWriter(*this, row_idx, old_offset); } +//! The VARIANT specializations are defined in duckdb/common/types/variant_writer.hpp +template <> +struct VectorWriter; +template <> +struct VectorWriter>; +template <> +class DynamicListWriter; + //! Specialization of VectorWriter for list_entry_t. Writes per-row list entries //! to a list vector without a templated child type. Supports the primitive-style //! WriteValue(list_entry_t) / WriteNull() API for callers that compute list 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/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/function/scalar/variant_path_function.hpp b/src/duckdb/src/include/duckdb/function/scalar/variant_path_function.hpp index af8e1dc33..f70f44987 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 @@ -10,14 +10,12 @@ #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/types/variant_iterator.hpp" +#include "duckdb/common/types/variant_writer.hpp" #include "duckdb/function/scalar/variant_utils.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" namespace duckdb { -//! Whether a VARIANT value selected by a path is returned -typedef bool (*variant_node_filter_t)(const VariantNode &node); - struct VariantPathFunction { //! Provides unified construction of path based processing functions. static ScalarFunctionSet CreateFunctionSet(const Identifier &name, const scalar_function_t &function, @@ -25,7 +23,7 @@ struct VariantPathFunction { init_local_state_t init_state = nullptr); //! Executes scalar VARIANT functions that accept an optional constant path argument. - //! The function may be called as f(VARIANT), f(VARIANT, VARCHAR) or f(VARIANT, VARCHAR[]). + //! The function may be called as f(VARIANT), f(VARIANT, VARCHAR), f(VARIANT, VARCHAR[]) or f(VARIANT, BIGINT). //! The callback `write_fn` writes the result for one row. template static void Execute(DataChunk &input, const ExpressionState &state, Vector &result, @@ -52,23 +50,14 @@ struct VariantPathFunction { D_ASSERT(n_columns == 2); const auto &path_type_id = input.data[1].GetType().id(); - if (path_type_id == LogicalTypeId::VARCHAR) { - ExecuteUnary(variant_vec, info.paths[0], result, count, write_fn); - return; - } if (path_type_id == LogicalTypeId::LIST) { ExecuteMany(variant_vec, info.paths, result, count, write_fn); return; } + D_ASSERT(path_type_id == LogicalTypeId::VARCHAR || path_type_id == LogicalTypeId::BIGINT); + ExecuteUnary(variant_vec, info.paths[0], result, count, write_fn); } - //! Executes scalar VARIANT functions that return the VARIANT value selected by an optional constant path argument. - //! The function may be called as f(VARIANT), f(VARIANT, VARCHAR), f(VARIANT, VARCHAR[]) or f(VARIANT, BIGINT), and - //! returns VARIANT, or VARIANT[] for a list of paths. Missing values, and values for which `keep` returns false, - //! are written as NULL. - static void ExecuteVariant(DataChunk &input, const ExpressionState &state, Vector &result, - variant_node_filter_t keep); - private: //! Executes a single path and writes RESULT_TYPE per input row. template @@ -94,33 +83,34 @@ struct VariantPathFunction { static void ExecuteMany(const Vector &input, const vector> &paths, Vector &result, const idx_t count, const WRITE_FUNCTION &write_fn) { const VectorIterator variants(input); + const auto keys = GetSingleKeys(paths); result.Initialize(VectorDataInitialization::UNINITIALIZED, count); auto result_writer = FlatVector::Writer>(result, count); + //! The value of the current row at each of the paths + vector> selected(paths.size()); for (idx_t row_idx = 0; row_idx < count; row_idx++) { if (!variants.RowIsValid(row_idx)) { result_writer.WriteNull(); continue; } - auto row_writer = result_writer.WriteList(paths.size()); - const auto variant = variants[row_idx]; + ResolvePaths(variants[row_idx], paths, keys, selected); idx_t path_idx = 0; - for (auto &path_writer : row_writer) { - write_fn(ResolvePath(variant, paths[path_idx]), path_writer); + for (auto &path_writer : result_writer.WriteList(paths.size())) { + write_fn(selected[path_idx], path_writer); path_idx++; } } } - //! Executes a single path and writes the selected VARIANT value per input row. - static void ExecuteVariantUnary(const Vector &input, const vector &path, Vector &result, - idx_t count, variant_node_filter_t keep); - //! Executes a list of paths and writes LIST of the selected values per input row. - static void ExecuteVariantMany(const Vector &input, const vector> &paths, - Vector &result, idx_t count, variant_node_filter_t keep); + //! Returns the key of each path that is a single key lookup, and an empty optional for the other paths + static vector> GetSingleKeys(const vector> &paths); + //! Resolves every path for 'root' into 'selected', the single key paths in one pass over the children of the object + static void ResolvePaths(const VariantNode &root, const vector> &paths, + const vector> &keys, vector> &selected); //! Returns the element at a 0-based index of an ARRAY, negative indexes count from the end. Returns nullopt if the //! node is not an ARRAY or the index is out of range. 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/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/main/client_data.hpp b/src/duckdb/src/include/duckdb/main/client_data.hpp index 44ac82e0d..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 { @@ -47,6 +48,7 @@ struct ClientData { //! 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. 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/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/rule/comparison_simplification.hpp b/src/duckdb/src/include/duckdb/optimizer/rule/comparison_simplification.hpp index 6ef740137..f4108cd64 100644 --- a/src/duckdb/src/include/duckdb/optimizer/rule/comparison_simplification.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/rule/comparison_simplification.hpp @@ -21,6 +21,15 @@ class ComparisonSimplificationRule : public Rule { bool is_root) override; }; +//! Rewrites a BETWEEN on a constant NULL input into a constant NULL (i.e. [NULL BETWEEN x AND y] => [NULL]) +class BetweenNullSimplificationRule : public Rule { +public: + explicit BetweenNullSimplificationRule(ExpressionRewriter &rewriter); + + unique_ptr Apply(LogicalOperator &op, vector> &bindings, bool &changes_made, + bool is_root) override; +}; + //! Rewrites top-level filter equality between row constructors into scalar equalities. class RowComparisonSimplificationRule : public Rule { public: 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/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/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 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/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/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/common_subplan_optimizer.cpp b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp index 13c9fefcc..a2435e925 100644 --- a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp +++ b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp @@ -1074,9 +1074,6 @@ class CommonSubplanFinder { min_cte_idx = cte_index; } - // Resolve types to be used for creating the materialized CTE and refs - op->ResolveOperatorTypes(); - const auto &primary_subplan = subplan_info.subplans[0]; vector> old_bindings(subplan_info.subplans.size()); @@ -1085,6 +1082,8 @@ class CommonSubplanFinder { column_binding_set_t required_canonical_binding_set; for (idx_t subplan_idx = 0; subplan_idx < subplan_info.subplans.size(); subplan_idx++) { auto &subplan = subplan_info.subplans[subplan_idx]; + // Earlier extractions can introduce new CTE readers within this subplan. + subplan.op.get()->ResolveOperatorTypes(); old_bindings[subplan_idx] = subplan.op.get()->GetColumnBindings(); old_types[subplan_idx] = subplan.op.get()->types; for (auto &cb : subplan.canonical_bindings) { @@ -1144,7 +1143,7 @@ class CommonSubplanFinder { // Create CTE refs and figure out column binding replacements vector> cte_refs; - ColumnBindingReplacer replacer; + BindingReplacementGraph replacements; for (idx_t subplan_idx = 0; subplan_idx < subplan_info.subplans.size(); subplan_idx++) { const auto &subplan = subplan_info.subplans[subplan_idx]; const auto cte_ref_index = optimizer.binder.GenerateTableIndex(); @@ -1172,7 +1171,7 @@ class CommonSubplanFinder { D_ASSERT(old_bindings[subplan_idx].size() == new_bindings.size()); D_ASSERT(subplan.canonical_bindings.size() == new_bindings.size()); for (idx_t i = 0; i < old_bindings[subplan_idx].size(); i++) { - replacer.replacement_bindings.emplace_back(old_bindings[subplan_idx][i], new_bindings[i]); + replacements.Add(old_bindings[subplan_idx][i], new_bindings[i]); #ifdef D_ASSERT_IS_ENABLED const auto inserted = generated_binding_map.emplace(new_bindings[i], subplan.canonical_bindings[i]); D_ASSERT(inserted.second); @@ -1205,6 +1204,7 @@ class CommonSubplanFinder { lowest_common_ancestor = std::move(cte); // Replace bindings of subplans with those of the CTE refs + ColumnBindingReplacer replacer(replacements); replacer.stop_operator = lowest_common_ancestor.get(); replacer.VisitOperator(*op); // Replace from the root until CTE replacer.VisitOperator(*lowest_common_ancestor->children[1]); // Replace in CTE child diff --git a/src/duckdb/src/optimizer/expression_rewriter.cpp b/src/duckdb/src/optimizer/expression_rewriter.cpp index 5db2e6e7e..f6813a98b 100644 --- a/src/duckdb/src/optimizer/expression_rewriter.cpp +++ b/src/duckdb/src/optimizer/expression_rewriter.cpp @@ -34,6 +34,7 @@ vector> ExpressionRewriter::CreateDefaultRules(ExpressionRewrit 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)); @@ -76,11 +77,11 @@ const vector> &ExpressionRewriter::GetRules() { return rules; } auto &client_data = ClientData::Get(context); - if (!client_data.default_expression_rewriter) { + 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; } diff --git a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp index 52cafc77b..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 = @@ -998,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/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/query_graph_manager.cpp b/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp index 8c93e73d3..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)) { @@ -822,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; @@ -838,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 || @@ -981,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()) { @@ -1005,12 +1040,9 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorfilter) { if (info.from_residual_predicate) { continue; @@ -1221,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) || @@ -1228,11 +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; - if (op.type != JoinOrderOperatorType::CROSS_PRODUCT && !JoinOrderConflictDetector::MustApplyAsOperator(op)) { - continue; - } + for (auto &constraint : candidate_constraints) { + auto &op = constraint.get(); if (JoinOrderConflictDetector::IsCompletedBy(op, left) || JoinOrderConflictDetector::IsCompletedBy(op, right) || !JoinOrderConflictDetector::IsCompletedBy(op, combined)) { continue; @@ -1241,7 +1273,7 @@ bool QueryGraphManager::IsJoinOrderCandidate(optional_ptr sel if (!JoinOrderConflictDetector::IsApplicable(op, left, right)) { return false; } - } else if (selected_operator != &op) { + } else if (selected_operator.get() != &op) { return false; } } diff --git a/src/duckdb/src/optimizer/rule/comparison_simplification.cpp b/src/duckdb/src/optimizer/rule/comparison_simplification.cpp index ee85e04f0..128d65330 100644 --- a/src/duckdb/src/optimizer/rule/comparison_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/comparison_simplification.cpp @@ -6,6 +6,7 @@ #include "duckdb/execution/expression_executor.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/optimizer/expression_rewriter.hpp" +#include "duckdb/planner/expression/bound_between_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/planner/expression/bound_operator_expression.hpp" @@ -203,6 +204,31 @@ ComparisonSimplificationRule::ComparisonSimplificationRule(ExpressionRewriter &r root = std::move(op); } +BetweenNullSimplificationRule::BetweenNullSimplificationRule(ExpressionRewriter &rewriter) : Rule(rewriter) { + auto between = make_uniq(); + between->expr_type = make_uniq(ExpressionType::COMPARE_BETWEEN); + between->matchers.push_back(make_uniq()); + between->matchers.push_back(make_uniq()); + between->matchers.push_back(make_uniq()); + between->policy = SetMatcher::Policy::ORDERED; + root = std::move(between); +} + +unique_ptr BetweenNullSimplificationRule::Apply(LogicalOperator &op, + vector> &bindings, bool &changes_made, + bool is_root) { + auto &between = bindings[0].get().Cast(); + if (!BoundBetweenExpression::HasValidBindData(between)) { + return nullptr; + } + Value input_value; + if (!ExpressionExecutor::TryEvaluateScalar(GetContext(), bindings[1].get(), input_value) || !input_value.IsNull()) { + return nullptr; + } + // both bound comparisons are NULL whatever the bounds are, so they need not be evaluated + return make_uniq(Value(LogicalType::BOOLEAN)); +} + RowComparisonSimplificationRule::RowComparisonSimplificationRule(ExpressionRewriter &rewriter) : Rule(rewriter) { auto comparison = make_uniq(); comparison->expr_type = make_uniq(ExpressionType::COMPARE_EQUAL); diff --git a/src/duckdb/src/optimizer/topn_window_elimination.cpp b/src/duckdb/src/optimizer/topn_window_elimination.cpp index 44d036df2..db0ced397 100644 --- a/src/duckdb/src/optimizer/topn_window_elimination.cpp +++ b/src/duckdb/src/optimizer/topn_window_elimination.cpp @@ -3,7 +3,6 @@ #include "duckdb/common/assert.hpp" #include "duckdb/common/enums/expression_type.hpp" #include "duckdb/common/helper.hpp" -#include "duckdb/common/smaller_binary.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/common/unique_ptr.hpp" #include "duckdb/function/builtin_function_lookup.hpp" @@ -194,26 +193,6 @@ LHSColumnInfo GetLHSColumnInfo(const unique_ptr &op, idx_t colu return result; } -//! Whether the top-n aggregate keeps the sign of a zero in a single FLOAT or DOUBLE payload column: types that -//! arg_min/arg_max do not store natively are stored as sort keys, which store 0.0 and -0.0 alike. -static bool PayloadKeepsZeroSign(const LogicalType &type, const bool n_aggregate) { - if (type.id() != LogicalTypeId::FLOAT && type.id() != LogicalTypeId::DOUBLE) { - return true; - } - if (n_aggregate) { -#if DUCKDB_SMALLER_BINARY(arg_min_max_n_types) - return false; -#else - return true; -#endif - } -#if DUCKDB_SMALLER_BINARY(arg_min_max_types) - return false; -#else - return type.id() == LogicalTypeId::DOUBLE; -#endif -} - //! Late materialization recreates a payload by re-scanning the base table column and re-applying a single default //! (strict) cast at the topmost projection. That only reproduces the original value when the projection expression //! is a plain column reference, optionally wrapped in a single non-try cast. A value-transforming expression @@ -330,8 +309,7 @@ unique_ptr TopNWindowElimination::OptimizeInternal(unique_ptrGetReturnType(), params.limit > 1)) { + if (!AggregateKeepsZeroSign(window, aggregate_payload, params)) { return op; } any_late_materialization |= used_late_materialization; @@ -383,6 +361,33 @@ TopNWindowElimination::CreateAggregateExpression(vector> 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/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/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/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/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/ub_src_common_types_variant.cpp b/src/duckdb/ub_src_common_types_variant.cpp index dc76281e1..85f31a35e 100644 --- a/src/duckdb/ub_src_common_types_variant.cpp +++ b/src/duckdb/ub_src_common_types_variant.cpp @@ -12,3 +12,5 @@ #include "src/common/types/variant/variant_value_convert.cpp" +#include "src/common/types/variant/variant_writer.cpp" + From db2baf46669d5972c70b85e680e628e0f5ff1a93 Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Fri, 27 Nov 2026 16:33:38 +0000 Subject: [PATCH 2/8] Update vendored DuckDB sources to 704d4d288ac --- CMakeLists.txt | 2 +- .../aggregate/algebraic/avg.cpp | 96 +- .../aggregate/distributive/arg_min_max.cpp | 63 +- .../aggregate/distributive/sum.cpp | 84 +- .../core_functions/aggregate/sum_helpers.hpp | 43 +- .../scalar/list/list_aggregates.cpp | 13 + .../core_functions/scalar/list/list_sort.cpp | 30 + src/duckdb/extension/icu/datetime/chinese.cpp | 11 +- .../extension/parquet/column_reader.cpp | 2 +- .../parquet/include/parquet_crypto.hpp | 2 +- .../parquet/include/parquet_reader.hpp | 7 +- .../parquet/include/parquet_statistics.hpp | 5 +- .../extension/parquet/parquet_crypto.cpp | 14 +- .../extension/parquet/parquet_metadata.cpp | 6 +- .../extension/parquet/parquet_reader.cpp | 309 +- .../extension/parquet/parquet_statistics.cpp | 49 +- ...nerated_extension_loader_package_build.cpp | 8 +- src/duckdb/src/catalog/catalog.cpp | 3 + .../catalog_entry/duck_table_entry.cpp | 13 +- src/duckdb/src/catalog/catalog_set.cpp | 5 + .../src/catalog/default/default_views.cpp | 6 +- src/duckdb/src/catalog/dependency_manager.cpp | 5 +- src/duckdb/src/common/adbc/adbc.cpp | 4 +- src/duckdb/src/common/base_file_system.cpp | 1021 ++ .../src/common/compressed_file_system.cpp | 2 +- src/duckdb/src/common/enum_util.cpp | 11 +- .../src/common/enums/statement_type.cpp | 13 +- src/duckdb/src/common/file_system.cpp | 1079 +- src/duckdb/src/common/local_file_system.cpp | 98 +- src/duckdb/src/common/memory_mapped_file.cpp | 9 +- src/duckdb/src/common/opener_file_system.cpp | 75 - .../src/common/operator/cast_operators.cpp | 4 +- src/duckdb/src/common/process_util.cpp | 1 - .../common/serializer/async_file_writer.cpp | 2 +- .../serializer/buffered_file_reader.cpp | 5 +- .../src/common/types/bignum_decimal.cpp | 10 +- src/duckdb/src/common/types/cast_helpers.cpp | 3 +- src/duckdb/src/common/types/date.cpp | 3 +- src/duckdb/src/common/types/hugeint.cpp | 35 +- src/duckdb/src/common/types/uhugeint.cpp | 46 +- .../variant/parquet_variant_iterator.cpp | 9 +- src/duckdb/src/common/virtual_file_system.cpp | 41 +- .../execution/aggregate_state_spilling.cpp | 42 +- src/duckdb/src/execution/index/art/art.cpp | 27 +- .../src/execution/index/art/art_builder.cpp | 30 +- src/duckdb/src/execution/index/art/node.cpp | 14 +- .../src/execution/index/bound_index.cpp | 4 +- .../aggregate/physical_streaming_window.cpp | 2 +- .../operator/aggregate/physical_window.cpp | 40 +- .../csv_scanner/encode/csv_encoder.cpp | 46 +- .../operator/helper/physical_limit.cpp | 12 +- .../helper/physical_streaming_limit.cpp | 15 +- .../operator/join/join_filter_pushdown.cpp | 3 +- .../persistent/physical_batch_insert.cpp | 4 + .../persistent/physical_copy_to_file.cpp | 2 +- .../operator/persistent/physical_insert.cpp | 7 +- .../operator/schema/physical_create_index.cpp | 6 +- .../execution/operator/set/physical_union.cpp | 16 +- .../physical_plan/plan_aggregate.cpp | 2 +- .../execution/physical_plan/plan_any_join.cpp | 4 +- .../physical_plan/plan_asof_join.cpp | 4 +- .../physical_plan/plan_comparison_join.cpp | 4 +- .../physical_plan/plan_copy_to_file.cpp | 2 +- .../execution/physical_plan/plan_create.cpp | 2 +- .../physical_plan/plan_create_index.cpp | 30 +- .../physical_plan/plan_create_table.cpp | 2 +- .../physical_plan/plan_cross_product.cpp | 4 +- .../src/execution/physical_plan/plan_cte.cpp | 21 +- .../execution/physical_plan/plan_distinct.cpp | 2 +- .../execution/physical_plan/plan_explain.cpp | 2 +- .../execution/physical_plan/plan_export.cpp | 2 +- .../physical_plan/plan_expression_get.cpp | 2 +- .../execution/physical_plan/plan_filter.cpp | 2 +- .../src/execution/physical_plan/plan_get.cpp | 2 +- .../execution/physical_plan/plan_insert.cpp | 2 +- .../execution/physical_plan/plan_limit.cpp | 2 +- .../physical_plan/plan_merge_into.cpp | 2 +- .../execution/physical_plan/plan_order.cpp | 2 +- .../execution/physical_plan/plan_pivot.cpp | 2 +- .../physical_plan/plan_positional_join.cpp | 4 +- .../physical_plan/plan_projection.cpp | 2 +- .../physical_plan/plan_recursive_cte.cpp | 6 +- .../execution/physical_plan/plan_sample.cpp | 2 +- .../physical_plan/plan_secure_view.cpp | 2 +- .../src/execution/physical_plan/plan_set.cpp | 2 +- .../physical_plan/plan_set_operation.cpp | 6 +- .../physical_plan/plan_top_key_filter.cpp | 2 +- .../execution/physical_plan/plan_top_n.cpp | 2 +- .../execution/physical_plan/plan_unnest.cpp | 2 +- .../execution/physical_plan/plan_vacuum.cpp | 2 +- .../execution/physical_plan/plan_window.cpp | 2 +- .../src/execution/physical_plan_generator.cpp | 93 +- .../function/aggregate/bignum_aggregates.cpp | 67 + .../aggregate/distributive/decimal_avg.cpp | 95 +- .../aggregate/distributive/minmax.cpp | 42 +- .../src/function/aggregate_function.cpp | 7 +- .../aggregate_state_serialization.cpp | 3 +- .../src/function/built_in_functions.cpp | 3 + src/duckdb/src/function/builtin_encodings.cpp | 68 +- .../src/function/cast/cast_statistics.cpp | 24 + .../src/function/cast/variant/to_json.cpp | 3 +- src/duckdb/src/function/function_list.cpp | 1 + .../src/function/scalar/list/list_resize.cpp | 20 + .../src/function/scalar/list/list_select.cpp | 28 + .../function/scalar/operator/arithmetic.cpp | 57 +- .../src/function/scalar/string/concat.cpp | 15 + .../scalar/system/aggregate_export.cpp | 35 +- .../scalar/system/share_transaction.cpp | 27 + .../function/table/system/duckdb_columns.cpp | 40 +- src/duckdb/src/function/table/table_scan.cpp | 33 +- .../function/table/version/pragma_version.cpp | 6 +- .../duckdb/common/base_file_system.hpp | 370 + .../include/duckdb/common/bignum_limbs.hpp | 71 +- .../duckdb/common/compressed_file_system.hpp | 4 +- .../duckdb/common/enums/filter_result.hpp | 15 + .../src/include/duckdb/common/file_system.hpp | 523 +- .../src/include/duckdb/common/hugeint.hpp | 146 +- .../src/include/duckdb/common/in_clause.hpp | 19 + .../duckdb/common/local_file_system.hpp | 33 +- .../duckdb/common/opener_file_system.hpp | 304 - .../operator/decimal_cast_operators.hpp | 23 +- .../duckdb/common/pipe_file_system.hpp | 4 +- .../serializer/buffered_file_reader.hpp | 4 +- .../src/include/duckdb/common/types.hpp | 2 +- .../duckdb/common/types/bignum_decimal.hpp | 3 + .../src/include/duckdb/common/types/date.hpp | 4 +- .../common/types/variant/variant_builder.hpp | 5 +- .../duckdb/common/types/variant_visitor.hpp | 16 +- .../duckdb/common/uint128_arithmetic.hpp | 164 + .../vector_operations/aggregate_executor.hpp | 40 +- .../duckdb/common/virtual_file_system.hpp | 28 +- .../execution/aggregate_state_spilling.hpp | 5 +- .../duckdb/execution/index/art/art.hpp | 4 +- .../execution/index/art/art_builder.hpp | 21 +- .../duckdb/execution/index/art/node.hpp | 6 +- .../duckdb/execution/index/bound_index.hpp | 13 +- .../csv_scanner/encode/csv_encoder.hpp | 8 +- .../operator/helper/physical_limit.hpp | 3 + .../operator/join/join_filter_pushdown.hpp | 25 +- .../execution/physical_plan_generator.hpp | 13 +- .../function/aggregate/bignum_aggregates.hpp | 91 + .../function/aggregate/minmax_n_helpers.hpp | 249 +- .../duckdb/function/aggregate_function.hpp | 12 +- .../function/aggregate_state_layout.hpp | 3 + .../aggregate_state_serialization.hpp | 19 +- .../duckdb/function/encoding_function.hpp | 3 + .../duckdb/function/scalar/generic_common.hpp | 9 +- .../function/scalar/system_functions.hpp | 10 + .../duckdb/function/table/table_scan.hpp | 5 + .../variant/variant_value_convert.hpp | 3 +- .../capi_v2/capi_v2_data_source_internal.hpp | 142 + .../duckdb/main/capi_v2/capi_v2_internal.hpp | 2 + .../duckdb/main/capi_v2/extension_api_v2.hpp | 426 +- .../include/duckdb/main/client_context.hpp | 2 + src/duckdb/src/include/duckdb/main/config.hpp | 2 + .../src/include/duckdb/main/connection.hpp | 5 + .../duckdb/main/database_file_opener.hpp | 10 +- .../main/extension_repository_manager.hpp | 3 +- .../optimizer/compressed_materialization.hpp | 1 + .../include/duckdb/optimizer/cte_inlining.hpp | 1 + .../duckdb/optimizer/filter_combiner.hpp | 33 +- .../duckdb/optimizer/filter_pullup.hpp | 10 +- .../duckdb/optimizer/in_clause_rewriter.hpp | 3 +- .../join_filter_pushdown_optimizer.hpp | 4 +- .../join_order/cardinality_estimator.hpp | 33 +- .../join_order/cardinality_value.hpp | 130 - .../optimizer/join_order/cost_model.hpp | 2 +- .../duckdb/optimizer/join_order/join_node.hpp | 2 +- .../join_order/join_order_candidate.hpp | 2 +- .../join_order/join_order_source_stats.hpp | 3 +- .../optimizer/join_order/join_predicate.hpp | 3 + .../join_order/join_relation_set.hpp | 1 + .../join_order/query_graph_manager.hpp | 22 +- .../optimizer/join_order/relation_manager.hpp | 2 + .../relation_statistics/cardinality_value.hpp | 208 + .../relation_statistics.hpp | 27 +- .../relation_statistics_helper.hpp | 58 +- .../optimizer/statistics_propagator.hpp | 3 +- .../parser/parsed_data/transaction_info.hpp | 4 +- .../duckdb/parser/peg/inlined_grammar.hpp | 3 +- .../include/duckdb/parser/peg/peg_rule_id.hpp | 1 + .../peg/transformer/peg_transformer.hpp | 3 + .../filter/constant_filter_combiner.hpp | 69 + .../planner/filter/expression_filter.hpp | 9 + .../duckdb/planner/logical_operator.hpp | 9 +- .../logical_operator_repeatability.hpp | 3 + .../duckdb/planner/operator/logical_get.hpp | 3 + .../duckdb/planner/table_filter_set.hpp | 4 + .../duckdb/storage/block_allocator.hpp | 6 +- .../src/include/duckdb/storage/data_table.hpp | 29 +- .../caching_file_system.hpp | 3 +- .../caching_file_system_wrapper.hpp | 44 +- .../src/include/duckdb/storage/index.hpp | 2 +- .../duckdb/storage/table/column_data.hpp | 8 +- .../duckdb/storage/table/index_entry.hpp | 61 +- .../storage/table/row_group_collection.hpp | 9 +- .../duckdb/storage/table/scan_state.hpp | 9 + .../duckdb/storage/table/table_index_list.hpp | 34 +- .../duckdb/transaction/commit_state.hpp | 6 +- .../duckdb/transaction/duck_transaction.hpp | 2 + .../duckdb/transaction/local_storage.hpp | 27 +- .../duckdb/transaction/meta_transaction.hpp | 59 +- .../transaction/transaction_context.hpp | 34 +- .../duckdb/transaction/undo_buffer.hpp | 1 - src/duckdb/src/include/duckdb_extension_v2.h | 593 +- src/duckdb/src/include/duckdb_v2.h | 12745 ++++++++-------- src/duckdb/src/main/attached_database.cpp | 8 +- .../src/main/capi/v2/capi_v2_connection.cpp | 13 + .../src/main/capi/v2/capi_v2_data_source.cpp | 1295 ++ .../src/main/capi/v2/capi_v2_file_system.cpp | 5 +- .../src/main/capi/v2/capi_v2_func_copy.cpp | 455 +- .../src/main/capi/v2/capi_v2_func_table.cpp | 1714 +-- src/duckdb/src/main/client_context.cpp | 20 + .../src/main/client_context_execution.cpp | 8 + src/duckdb/src/main/client_data.cpp | 7 +- src/duckdb/src/main/connection.cpp | 11 + src/duckdb/src/main/context.cpp | 5 +- src/duckdb/src/main/database.cpp | 4 +- src/duckdb/src/main/database_manager.cpp | 8 +- .../src/main/extension/extension_helper.cpp | 1 + .../optimizer/build_probe_side_optimizer.cpp | 6 +- .../optimizer/common_subplan_optimizer.cpp | 361 +- .../optimizer/compressed_materialization.cpp | 27 +- src/duckdb/src/optimizer/cte_inlining.cpp | 10 +- .../src/optimizer/cte_join_filter_pusher.cpp | 20 +- .../optimizer/cte_runtime_filter_pushdown.cpp | 6 +- .../duplicate_eliminated_domain_optimizer.cpp | 49 +- src/duckdb/src/optimizer/filter_combiner.cpp | 464 +- src/duckdb/src/optimizer/filter_pullup.cpp | 135 +- src/duckdb/src/optimizer/filter_pushdown.cpp | 15 + .../src/optimizer/in_clause_rewriter.cpp | 2 +- .../join_filter_pushdown_optimizer.cpp | 534 +- .../join_order/cardinality_estimator.cpp | 724 +- .../src/optimizer/join_order/cost_model.cpp | 15 +- .../join_order/join_order_candidate.cpp | 8 +- .../join_order/join_order_linearizer.cpp | 9 +- .../join_order/join_order_optimizer.cpp | 87 +- .../optimizer/join_order/join_order_plan.cpp | 2 +- .../join_order/join_order_source_stats.cpp | 7 +- .../optimizer/join_order/join_predicate.cpp | 24 +- .../join_order/join_relation_set.cpp | 18 +- .../src/optimizer/join_order/query_graph.cpp | 2 +- .../join_order/query_graph_manager.cpp | 273 +- .../optimizer/join_order/relation_manager.cpp | 274 +- .../optimizer/partial_aggregate_pushdown.cpp | 22 +- .../optimizer/pullup/pullup_constraints.cpp | 136 + .../src/optimizer/pullup/pullup_from_left.cpp | 12 +- .../optimizer/pullup/pullup_projection.cpp | 173 +- .../optimizer/pullup/pullup_set_operation.cpp | 146 +- .../optimizer/pushdown/pushdown_filter.cpp | 15 +- .../src/optimizer/pushdown/pushdown_get.cpp | 15 +- .../relation_statistics.cpp | 34 +- .../relation_statistics_extractor.cpp | 27 +- .../relation_statistics_helper.cpp | 261 +- .../relation_statistics_operator.cpp | 101 +- .../relation_statistics_scan.cpp | 136 +- src/duckdb/src/optimizer/row_group_pruner.cpp | 6 +- .../operator/propagate_aggregate.cpp | 2 + .../statistics/operator/propagate_join.cpp | 2 + .../src/optimizer/statistics_propagator.cpp | 11 +- src/duckdb/src/optimizer/topn_optimizer.cpp | 4 +- .../parser/parsed_data/transaction_info.cpp | 4 + src/duckdb/src/parser/peg/peg_rule_id.cpp | 1 + .../transform_generated_trampoline.cpp | 11 + .../peg/transformer/transform_transaction.cpp | 7 + .../binder/tableref/bind_basetableref.cpp | 8 +- .../expression_binder/index_binder.cpp | 91 + .../filter/constant_filter_combiner.cpp | 163 + .../src/planner/filter/expression_filter.cpp | 46 +- src/duckdb/src/planner/logical_operator.cpp | 37 +- .../logical_operator_repeatability.cpp | 12 +- .../src/planner/operator/logical_get.cpp | 16 +- .../src/planner/table_filter_combiner.cpp | 261 + src/duckdb/src/planner/table_filter_set.cpp | 42 +- src/duckdb/src/planner/table_filter_state.cpp | 61 +- src/duckdb/src/storage/block_allocator.cpp | 59 +- src/duckdb/src/storage/data_table.cpp | 108 +- .../caching_file_system.cpp | 2 +- .../caching_file_system_wrapper.cpp | 71 +- src/duckdb/src/storage/index_entry.cpp | 209 +- src/duckdb/src/storage/local_storage.cpp | 137 +- .../serialization/serialize_parse_info.cpp | 2 + src/duckdb/src/storage/table/column_data.cpp | 6 + .../src/storage/table/list_column_data.cpp | 2 +- .../storage/table/row_group_collection.cpp | 69 +- .../storage/table/standard_column_data.cpp | 6 +- .../src/storage/table/struct_column_data.cpp | 3 +- .../src/storage/table/variant_column_data.cpp | 45 +- src/duckdb/src/storage/table_index_list.cpp | 93 +- src/duckdb/src/transaction/commit_state.cpp | 20 +- .../transaction/duck_transaction_manager.cpp | 2 +- .../src/transaction/meta_transaction.cpp | 63 +- .../src/transaction/transaction_context.cpp | 155 +- src/duckdb/src/transaction/undo_buffer.cpp | 6 +- src/duckdb/ub_src_common.cpp | 4 +- src/duckdb/ub_src_function_aggregate.cpp | 4 + src/duckdb/ub_src_function_scalar_system.cpp | 2 + src/duckdb/ub_src_main_capi_v2.cpp | 2 + src/duckdb/ub_src_optimizer_pullup.cpp | 2 + src/duckdb/ub_src_planner.cpp | 2 + src/duckdb/ub_src_planner_filter.cpp | 2 + 301 files changed, 17308 insertions(+), 13772 deletions(-) create mode 100644 src/duckdb/src/common/base_file_system.cpp delete mode 100644 src/duckdb/src/common/opener_file_system.cpp create mode 100644 src/duckdb/src/function/aggregate/bignum_aggregates.cpp create mode 100644 src/duckdb/src/function/scalar/system/share_transaction.cpp create mode 100644 src/duckdb/src/include/duckdb/common/base_file_system.hpp create mode 100644 src/duckdb/src/include/duckdb/common/enums/filter_result.hpp create mode 100644 src/duckdb/src/include/duckdb/common/in_clause.hpp delete mode 100644 src/duckdb/src/include/duckdb/common/opener_file_system.hpp create mode 100644 src/duckdb/src/include/duckdb/common/uint128_arithmetic.hpp create mode 100644 src/duckdb/src/include/duckdb/function/aggregate/bignum_aggregates.hpp create mode 100644 src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_data_source_internal.hpp delete mode 100644 src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_value.hpp create mode 100644 src/duckdb/src/include/duckdb/optimizer/relation_statistics/cardinality_value.hpp create mode 100644 src/duckdb/src/include/duckdb/planner/filter/constant_filter_combiner.hpp create mode 100644 src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp create mode 100644 src/duckdb/src/optimizer/pullup/pullup_constraints.cpp create mode 100644 src/duckdb/src/planner/filter/constant_filter_combiner.cpp create mode 100644 src/duckdb/src/planner/table_filter_combiner.cpp create mode 100644 src/duckdb/ub_src_function_aggregate.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9d3747f0e..941db1718 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -186,7 +186,6 @@ set(DUCKDB_SRC_FILES 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/function/aggregate/sorted_aggregate_function.cpp src/duckdb/src/function/cast/union/from_struct.cpp src/duckdb/src/function/scalar/date/strftime.cpp src/duckdb/src/function/scalar/geometry/geometry_functions.cpp @@ -432,6 +431,7 @@ set(DUCKDB_SRC_FILES src/duckdb/ub_src_execution_physical_plan.cpp src/duckdb/ub_src_execution_sample.cpp src/duckdb/ub_src_function.cpp + src/duckdb/ub_src_function_aggregate.cpp src/duckdb/ub_src_function_aggregate_distributive.cpp src/duckdb/ub_src_function_cast.cpp src/duckdb/ub_src_function_cast_variant.cpp diff --git a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp index 8faceae82..f39c00408 100644 --- a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp +++ b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp @@ -6,7 +6,7 @@ #include "duckdb/common/types/decimal.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/types/time.hpp" -#include "duckdb/common/vector/struct_vector.hpp" +#include "duckdb/function/aggregate/bignum_aggregates.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/likely.hpp" #include "duckdb/function/function_set.hpp" @@ -505,12 +505,6 @@ struct TimeTZAverageOperation : public BaseSumOperation - static void Initialize(STATE &state) { - state.count = 0; - state.value = BignumIntermediate(); - } - - template - static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) { - if (state.count == 0) { - state.value.Initialize(unary_input.input.allocator); - } - state.count++; - BignumIntermediate rhs(input); - state.value.AddInPlace(unary_input.input.allocator, rhs); - } - - template - static void ConstantOperation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input, - idx_t count) { - for (idx_t i = 0; i < count; i++) { - Operation(state, input, unary_input); - } - } - - template - static void Combine(const STATE &source, STATE &target, AggregateInputData &input) { - if (source.count == 0) { - return; - } - if (target.count == 0) { - target.value.Initialize(input.allocator); - } - target.count += source.count; - target.value.AddInPlace(input.allocator, source.value); - } - +//! The average of the bignum_t tier of decimals: the exact BIGNUM sum, divided once at the end like the hugeint tier +struct BignumAverageOperation : BignumAvgOperation { template static void Finalize(STATE &state, T &target, AggregateFinalizeData &finalize_data) { if (state.count == 0) { @@ -621,10 +580,6 @@ struct BignumAverageOperation { auto &bind_data = finalize_data.input.bind_data->Cast(); target = BignumExactAverage(state.value, state.count, bind_data.decimal_scale); } - - static bool IgnoreNull() { - return true; - } }; //! The states are exported as STRUCT(count UBIGINT, value BIGNUM), the value is NULL for an empty state @@ -639,49 +594,26 @@ AggregateStateLayout BignumAvgStateLayout(AggregateLayoutInput &input) { void BignumAvgExportState(Vector &state_vector, AggregateFinalizeInputData &, Vector &result, idx_t count, idx_t offset) { auto states = state_vector.Values(); - auto &entries = StructVector::GetEntries(result); - auto count_data = FlatVector::GetDataMutable(entries[0]); - auto value_data = FlatVector::GetDataMutable(entries[1]); - auto &value_validity = FlatVector::ValidityMutable(entries[1]); + auto writer = FlatVector::Writer>(result, count, offset); for (idx_t i = 0; i < count; i++) { - auto &state = *states[i].GetValue(); - count_data[offset + i] = state.count; - if (state.count == 0) { - value_validity.SetInvalid(offset + i); - continue; - } - value_data[offset + i] = BignumAggregates::WriteBignum(state.value, entries[1]); + writer.WriteValue([&](auto &count_writer, auto &value_writer) { + BignumAggregates::WriteAvgState(*states[i].GetValue(), count_writer, value_writer); + }); } } void BignumAvgImportState(AggregateImportInputData &input) { - auto &input_vec = input.input_vec; - auto count = input_vec.size(); - UnifiedVectorFormat struct_format; - input_vec.ToUnifiedFormat(struct_format); - auto &entries = StructVector::GetEntries(input_vec); - UnifiedVectorFormat count_format; - UnifiedVectorFormat value_format; - entries[0].ToUnifiedFormat(count_format); - entries[1].ToUnifiedFormat(value_format); - auto count_data = count_format.GetData(count_format); - auto value_data = value_format.GetData(value_format); - for (idx_t i = 0; i < count; i++) { + auto entries = input.input_vec.Values>(); + for (idx_t i = 0; i < input.input_vec.size(); i++) { auto &state = *reinterpret_cast(input.dest_buffer + i * input.layout.total_state_size); - BignumAverageOperation::Initialize(state); - const auto struct_idx = struct_format.sel->get_index(i); - const auto count_idx = count_format.sel->get_index(i); - const auto value_idx = value_format.sel->get_index(i); - if (!struct_format.validity.RowIsValid(struct_idx) || !count_format.validity.RowIsValid(count_idx) || - count_data[count_idx] == 0) { + BignumAvgOperation::Initialize(state); + const auto entry = entries[i]; + if (!entry.IsValid()) { // an empty state, e.g. to_aggregate_state(NULL, ...) continue; } - if (!value_format.validity.RowIsValid(value_idx)) { - throw InvalidInputException("Invalid avg state - the value cannot be NULL when the count is not 0"); - } - state.count = count_data[count_idx]; - state.value = BignumAggregates::ImportBignum(value_data[value_idx], input.allocator); + BignumAggregates::ImportAvgState(state, entry.GetChildValue<0>(), entry.GetChildValue<1>(), input.allocator, + "avg", "value"); } } 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 420a9d2ae..4a7cc5bc2 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 @@ -683,6 +683,41 @@ class ArgMinMaxNState { heap.Initialize(allocator, nval); is_initialized = true; } + + void ExportSlot(Vector &entries, idx_t entry_idx, idx_t slot, bool nulls_last) const { + auto &children = StructVector::GetEntries(entries); + auto &entry = heap.GetSlot(slot); + VAL_TYPE::Assign(children[0], entry_idx, entry.second.value, nulls_last); + ARG_TYPE::Assign(children[1], entry_idx, entry.first.value, nulls_last); + } + + struct ImportData { + ImportData(const Vector &entries, idx_t count, bool nulls_last) + : validity(entries.Validity()), val_extra_state(VAL_TYPE::CreateExtraState(count)), + arg_extra_state(ARG_TYPE::CreateExtraState(count)) { + auto &children = StructVector::GetEntries(entries); + VAL_TYPE::PrepareData(children[0], val_extra_state, val_format, nulls_last); + ARG_TYPE::PrepareData(children[1], arg_extra_state, arg_format, nulls_last); + } + + VectorValidityIterator validity; + typename VAL_TYPE::EXTRA_STATE val_extra_state; + typename ARG_TYPE::EXTRA_STATE arg_extra_state; + UnifiedVectorFormat val_format; + UnifiedVectorFormat arg_format; + }; + + void ImportSlot(ArenaAllocator &allocator, const ImportData &entries, idx_t entry_idx, bool reject_nulls) { + const auto val_idx = entries.val_format.sel->get_index(entry_idx); + const auto arg_idx = entries.arg_format.sel->get_index(entry_idx); + if (!entries.validity.IsValid(entry_idx) || + (reject_nulls && + (!entries.val_format.validity.RowIsValid(val_idx) || !entries.arg_format.validity.RowIsValid(arg_idx)))) { + throw InvalidInputException("Invalid arg_min/arg_max state - the entries cannot be NULL"); + } + heap.AppendSlot(allocator, ARG_TYPE::Create(entries.arg_format, arg_idx), + VAL_TYPE::Create(entries.val_format, val_idx)); + } }; //------------------------------------------------------------------------------ @@ -703,8 +738,8 @@ void ArgMinMaxNUpdate(Vector inputs[], AggregateInputData &aggr_input, idx_t inp UnifiedVectorFormat n_format; UnifiedVectorFormat state_format; - auto val_extra_state = STATE::VAL_TYPE::CreateExtraState(); - auto arg_extra_state = STATE::ARG_TYPE::CreateExtraState(); + auto val_extra_state = STATE::VAL_TYPE::CreateExtraState(count); + auto arg_extra_state = STATE::ARG_TYPE::CreateExtraState(count); STATE::VAL_TYPE::PrepareData(val_vector, val_extra_state, val_format, bind_data.nulls_last); STATE::ARG_TYPE::PrepareData(arg_vector, arg_extra_state, arg_format, bind_data.nulls_last); @@ -773,7 +808,8 @@ void SpecializeArgMinMaxNFunction(BoundAggregateFunction &function) { function.SetStateSizeCallback(AggregateFunction::StateSize); function.SetStateInitCallback(AggregateFunction::StateInitialize); function.SetStateCombineCallback(AggregateFunction::StateCombine); - function.SetStateDestructorCallback(AggregateFunction::StateDestroy); + function.SetExportAggregateStateCallback(MinMaxNOperation::ExportState); + function.SetImportAggregateStateCallback(MinMaxNOperation::ImportState); function.SetStateFinalizeCallback(MinMaxNOperation::Finalize); function.SetStateUpdateCallback(ArgMinMaxNUpdate); @@ -840,7 +876,8 @@ void SpecializeArgMinMaxNullNFunction(BoundAggregateFunction &function) { function.SetStateSizeCallback(AggregateFunction::StateSize); function.SetStateInitCallback(AggregateFunction::StateInitialize); function.SetStateCombineCallback(AggregateFunction::StateCombine); - function.SetStateDestructorCallback(AggregateFunction::StateDestroy); + function.SetExportAggregateStateCallback(MinMaxNOperation::ExportState); + function.SetImportAggregateStateCallback(MinMaxNOperation::ImportState); function.SetStateFinalizeCallback(MinMaxNOperation::Finalize); function.SetStateUpdateCallback(ArgMinMaxNUpdate); } @@ -912,6 +949,8 @@ unique_ptr ArgMinMaxNBind(BindAggregateFunctionInput &input) { } } ExpressionBinder::PushCollation(context, arguments[1], arguments[1]->GetReturnType(), input.GetCollationType()); + function.GetArguments()[0] = arguments[0]->GetReturnType(); + function.GetArguments()[1] = arguments[1]->GetReturnType(); const auto val_type = arguments[0]->GetReturnType().InternalType(); const auto arg_type = arguments[1]->GetReturnType().InternalType(); @@ -924,10 +963,24 @@ unique_ptr ArgMinMaxNBind(BindAggregateFunctionInput &input) { } else { SpecializeArgMinMaxNFunction(val_type, arg_type, function); } + if (arguments[2]->HasParameter()) { + // n is constant per execution: bind again once its value is known + throw ParameterNotResolvedException(); + } + if (!arguments[2]->IsFoldable()) { + MinMaxNOperation::BindPerRowN(function); + } return unique_ptr(std::move(function_data)); } +AggregateStateLayout ArgMinMaxNGetStateType(AggregateLayoutInput &input) { + child_list_t entry_children; + entry_children.emplace_back("arg", input.function.GetArguments()[0]); + entry_children.emplace_back("val", input.function.GetArguments()[1]); + return MinMaxNOperation::GetStateType(input, LogicalType::STRUCT(std::move(entry_children))); +} + template void AddArgMinMaxNFunction(AggregateFunctionSet &set) { AggregateFunction function({}, LogicalType::LIST(LogicalType::ANY), nullptr, nullptr, nullptr, nullptr, nullptr, @@ -936,6 +989,8 @@ void AddArgMinMaxNFunction(AggregateFunctionSet &set) { .AddParameter("arg", LogicalTypeId::ANY) .AddParameter("val", LogicalTypeId::ANY) .AddParameter("N", LogicalType::BIGINT); + function.SetStructStateExport(ArgMinMaxNGetStateType); + function.SetCombineSourceRetention(AggregateCombineSourceRetention::NEVER_RETAINS); function.SetFallible(); // the update callback rejects NULL and out-of-range n values at runtime set.AddFunction(function); diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp index dd5d956e4..d513dfa31 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp @@ -352,6 +352,74 @@ struct UhugeintSumOperation } }; +struct IntervalSumState { + static constexpr const char *STATE_NAMES[] = {"months", "days", "micros"}; + using STATE_TYPE = OptionalStateType>; + + hugeint_t months; + hugeint_t days; + hugeint_t micros; + bool is_set; + + void Add(hugeint_t input_months, hugeint_t input_days, hugeint_t input_micros) { + months = Hugeint::Add(months, input_months); + days = Hugeint::Add(days, input_days); + micros = Hugeint::Add(micros, input_micros); + is_set = true; + } + + void AddRepeated(hugeint_t input_months, hugeint_t input_days, hugeint_t input_micros, idx_t count) { + if (count == 0) { + return; + } + const auto multiplier = Hugeint::Convert(count); + Add(Hugeint::Multiply(input_months, multiplier), Hugeint::Multiply(input_days, multiplier), + Hugeint::Multiply(input_micros, multiplier)); + } +}; + +//! Keep intermediate totals wide and preserve the independent calendar components +struct IntervalSumOperation { + template + static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &) { + state.Add(Hugeint::Convert(input.months), Hugeint::Convert(input.days), Hugeint::Convert(input.micros)); + } + + template + static void ConstantOperation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &, idx_t count) { + state.AddRepeated(Hugeint::Convert(input.months), Hugeint::Convert(input.days), Hugeint::Convert(input.micros), + count); + } + + template + static void Combine(const STATE &source, STATE &target, AggregateInputData &) { + if (source.is_set) { + target.Add(source.months, source.days, source.micros); + } + } + + template + static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &, idx_t count) { + if (source.is_set) { + target.AddRepeated(source.months, source.days, source.micros, count); + } + } + + template + static void Finalize(STATE &state, T &target, AggregateFinalizeData &finalize_data) { + if (!state.is_set) { + finalize_data.ReturnNull(); + } else if (!Hugeint::TryCast(state.months, target.months) || !Hugeint::TryCast(state.days, target.days) || + !Hugeint::TryCast(state.micros, target.micros)) { + throw OutOfRangeException("Overflow in SUM of INTERVAL: the result does not fit in INTERVAL"); + } + } + + static bool IgnoreNull() { + return true; + } +}; + //! The sum of a DECIMAL is a DECIMAL(38) - finalizing throws if the sum does not fit in it template struct DecimalSumOperation : public OP { @@ -782,20 +850,19 @@ AggregateStateLayout BignumSumStateLayout(AggregateLayoutInput &input) { void BignumSumExportState(Vector &state_vector, AggregateFinalizeInputData &, Vector &result, idx_t count, idx_t offset) { auto states = state_vector.Values(); - auto result_data = FlatVector::GetDataMutable(result); - auto &result_validity = FlatVector::ValidityMutable(result); + auto writer = FlatVector::Writer(result, count, offset); for (idx_t i = 0; i < count; i++) { auto &state = *states[i].GetValue(); if (!state.is_set) { - result_validity.SetInvalid(offset + i); + writer.WriteNull(); continue; } if (state.is_wide) { - result_data[offset + i] = BignumAggregates::WriteBignum(state.wide, result); + BignumAggregates::WriteBignum(state.wide, writer); } else { char blob[2 * BignumLimb::BYTES + Bignum::BIGNUM_HEADER_SIZE]; const auto size = BignumOperation::EncodeSmall(state.small, blob); - result_data[offset + i] = StringVector::AddStringOrBlob(result, blob, size); + writer.WriteValue(string_t(blob, UnsafeNumericCast(size))); } } } @@ -865,6 +932,13 @@ AggregateFunctionSet SumFun::GetFunctions() { LogicalType::DOUBLE, LogicalType::DOUBLE); sum_double.GetSignature().GetParameter(0).SetName("arg"); sum.AddFunction(sum_double); + auto sum_interval = + AggregateFunction::UnaryAggregate( + LogicalType::INTERVAL, LogicalType::INTERVAL); + sum_interval.GetSignature().GetParameter(0).SetName("arg"); + sum_interval.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); + sum_interval.SetFallible(); + sum.AddFunction(sum_interval); auto sum_bignum = AggregateFunction::UnaryAggregate( LogicalType::BIGNUM, LogicalType::BIGNUM); sum_bignum.GetSignature().GetParameter(0).SetName("arg"); diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp index 0d9204152..22fbbf8d8 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp @@ -17,6 +17,7 @@ #include "duckdb/common/operator/multiply.hpp" #include "duckdb/common/types/value.hpp" #include "duckdb/common/optional.hpp" +#include "duckdb/function/aggregate/bignum_aggregates.hpp" #include "duckdb/function/aggregate_state.hpp" #include "duckdb/function/aggregate_state_layout.hpp" #include "duckdb/common/operator/cast_operators.hpp" @@ -26,48 +27,6 @@ namespace duckdb { -//! The BIGNUM accumulators of aggregate states: exported as (trimmed) BIGNUM blobs, imported as copies in the arena -struct BignumAggregates { - //! Writes the value as a BIGNUM blob in the heap of the result vector - static string_t WriteBignum(const BignumIntermediate &value, Vector &result) { - // trimmed like BignumIntermediate::ToBignum, the intermediate itself is only read - auto start = value.GetStartDataPos(); - uint32_t size = value.size - start; - if (size == 0) { - // the value is all sign-extension bytes: keep one of them - start = 0; - size = 1; - } - auto blob = StringVector::EmptyString(result, Bignum::BIGNUM_HEADER_SIZE + size); - auto ptr = blob.GetDataWriteable(); - Bignum::SetHeader(ptr, size, value.is_negative); - memcpy(ptr + Bignum::BIGNUM_HEADER_SIZE, value.data + start, size); - blob.Finalize(); - return blob; - } - - //! Copies an imported BIGNUM blob into the arena and returns the intermediate over the copy - static BignumIntermediate ImportBignum(string_t blob, ArenaAllocator &allocator) { - const auto size = blob.GetSize(); - auto header = const_data_ptr_cast(blob.GetData()); - if (size < Bignum::BIGNUM_HEADER_SIZE + 1) { - throw InvalidInputException("Invalid BIGNUM state - the blob is shorter than a header and a byte"); - } - // the header holds the data size, inverted for negative values (see Bignum::SetHeader) - uint32_t data_size = (uint32_t(header[0]) << 16) | (uint32_t(header[1]) << 8) | uint32_t(header[2]); - if ((header[0] & 0x80) == 0) { - data_size = ~data_size; - } - data_size &= 0x7FFFFF; - if (size != data_size + Bignum::BIGNUM_HEADER_SIZE) { - throw InvalidInputException("Invalid BIGNUM state - the header does not match the size of the blob"); - } - auto ptr = allocator.Allocate(size); - memcpy(ptr, blob.GetData(), size); - return BignumIntermediate(ptr, size); - } -}; - struct AggregateStatisticsInput; struct SumAccumulatorBounds { diff --git a/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp b/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp index 92744e70c..a20c47720 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp @@ -1,3 +1,4 @@ +#include "duckdb/storage/statistics/list_stats.hpp" #include "duckdb/main/context.hpp" #include "core_functions/aggregate/nested_functions.hpp" #include "core_functions/scalar/list_functions.hpp" @@ -598,11 +599,23 @@ ScalarFunction ListAggregateFun::GetFunction() { return result; } +//! The distinct non-NULL elements of a list are at most as many as its elements +static unique_ptr ListDistinctStats(ClientContext &context, FunctionStatisticsInput &input) { + auto &list_stats = input.child_stats[0]; + if (list_stats.GetStatsType() != StatisticsType::LIST_STATS || list_stats.GetType() != input.expr.GetReturnType()) { + return nullptr; + } + auto result = list_stats.Copy(); + ListStats::SetLengthBounds(result, 0, ListStats::MaxListLength(list_stats)); + return result.ToUnique(); +} + ScalarFunction ListDistinctFun::GetFunction() { ScalarFunction fun({}, LogicalType::LIST(LogicalType::TEMPLATE("T")), ListDistinctFunction, ListAggregatesBind, nullptr, ListAggregatesInitLocalState); fun.GetSignature().AddParameter("list", LogicalType::LIST(LogicalType::TEMPLATE("T"))); fun.SetResolveTypesCallback(ListAggregatesResolveTypes); + fun.SetStatisticsCallback(ListDistinctStats); return fun; } diff --git a/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp b/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp index cf06772d0..191662f98 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp @@ -8,6 +8,7 @@ #include "core_functions/scalar/list_functions.hpp" #include "duckdb/common/enum_util.hpp" #include "duckdb/common/numeric_utils.hpp" +#include "duckdb/storage/statistics/list_stats.hpp" #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" @@ -464,6 +465,27 @@ static void ListSortResolveTypes(ResolveScalarFunctionTypesInput &input) { } } +//! Sorting keeps the elements, so the result has the statistics of the list +static unique_ptr ListSortStats(ClientContext &context, FunctionStatisticsInput &input) { + auto &list_stats = input.child_stats[0]; + if (list_stats.GetStatsType() != StatisticsType::LIST_STATS || list_stats.GetType() != input.expr.GetReturnType()) { + return nullptr; + } + return list_stats.Copy().ToUnique(); +} + +//! The result holds one index per element of the list +static unique_ptr ListGradeUpStats(ClientContext &context, FunctionStatisticsInput &input) { + auto &list_stats = input.child_stats[0]; + if (list_stats.GetStatsType() != StatisticsType::LIST_STATS) { + return nullptr; + } + auto result = ListStats::CreateUnknown(input.expr.GetReturnType()); + result.CopyValidity(list_stats); + ListStats::SetLengthData(result, ListStats::GetLengthData(list_stats)); + return result.ToUnique(); +} + static void SetListSortSerialization(ScalarFunction &function) { function.SetUnbindCallback(ListSortUnbind); function.SetSerializeCallback(ListSortBindData::Serialize); @@ -489,10 +511,13 @@ ScalarFunctionSet ListSortFun::GetFunctions() { .AddParameter("null_order", LogicalType::VARCHAR); SetListSortSerialization(sort); sort.SetResolveTypesCallback(ListSortResolveTypes); + sort.SetStatisticsCallback(ListSortStats); SetListSortSerialization(sort_order); sort_order.SetResolveTypesCallback(ListSortResolveTypes); + sort_order.SetStatisticsCallback(ListSortStats); SetListSortSerialization(sort_orders); sort_orders.SetResolveTypesCallback(ListSortResolveTypes); + sort_orders.SetStatisticsCallback(ListSortStats); ScalarFunctionSet list_sort; list_sort.AddFunction(sort); @@ -519,8 +544,11 @@ ScalarFunctionSet ListGradeUpFun::GetFunctions() { .AddParameter("sort_order", LogicalType::VARCHAR) .AddParameter("null_order", LogicalType::VARCHAR); SetListSortSerialization(sort); + sort.SetStatisticsCallback(ListGradeUpStats); SetListSortSerialization(sort_order); + sort_order.SetStatisticsCallback(ListGradeUpStats); SetListSortSerialization(sort_orders); + sort_orders.SetStatisticsCallback(ListGradeUpStats); ScalarFunctionSet list_grade_up; list_grade_up.AddFunction(sort); @@ -542,8 +570,10 @@ ScalarFunctionSet ListReverseSortFun::GetFunctions() { .AddParameter("null_order", LogicalType::VARCHAR); SetListSortSerialization(sort_reverse); sort_reverse.SetResolveTypesCallback(ListSortResolveTypes); + sort_reverse.SetStatisticsCallback(ListSortStats); SetListSortSerialization(sort_reverse_null_order); sort_reverse_null_order.SetResolveTypesCallback(ListSortResolveTypes); + sort_reverse_null_order.SetStatisticsCallback(ListSortStats); ScalarFunctionSet list_reverse_sort; list_reverse_sort.AddFunction(sort_reverse); diff --git a/src/duckdb/extension/icu/datetime/chinese.cpp b/src/duckdb/extension/icu/datetime/chinese.cpp index ebd76d4a2..813e4a645 100644 --- a/src/duckdb/extension/icu/datetime/chinese.cpp +++ b/src/duckdb/extension/icu/datetime/chinese.cpp @@ -221,7 +221,13 @@ int32_t ChineseCalendar::NewYear(int32_t gyear) const { } const auto solstice_before = WinterSolstice(gyear - 1); + if (HasFailedInternal()) { + return 0; + } const auto solstice_after = WinterSolstice(gyear); + if (HasFailedInternal()) { + return 0; + } const auto new_moon1 = NewMoonNear(solstice_before + 1, true); const auto new_moon2 = NewMoonNear(new_moon1 + SYNODIC_GAP, true); const auto new_moon11 = NewMoonNear(solstice_after + 1, false); @@ -370,7 +376,10 @@ int64_t ChineseCalendar::ComputeMonthStart(int32_t eyear, int32_t month, bool is } const auto new_year = NewYear(eyear); - auto new_moon = NewMoonNear(new_year + month * 29, true); + if (HasFailedInternal()) { + return 0; + } + auto new_moon = NewMoonNear(double(new_year) + month * 29, true); if (HasFailedInternal()) { return 0; } diff --git a/src/duckdb/extension/parquet/column_reader.cpp b/src/duckdb/extension/parquet/column_reader.cpp index 758d95687..7086151b7 100644 --- a/src/duckdb/extension/parquet/column_reader.cpp +++ b/src/duckdb/extension/parquet/column_reader.cpp @@ -515,7 +515,7 @@ void ColumnReader::ReadEncrypted(duckdb_apache::thrift::TBase &object) { } void ColumnReader::ReadDataEncrypted(const data_ptr_t buffer, const uint32_t buffer_size, PageType::type page_type) { - aad_crypto_metadata.module = ParquetCrypto::GetModule(*chunk, page_type, aad_crypto_metadata.page_ordinal); + aad_crypto_metadata.module = ParquetCrypto::GetModule(*chunk, page_type); aad_crypto_metadata.page_ordinal = ParquetCrypto::GetFinalPageOrdinal(*chunk, aad_crypto_metadata.module, aad_crypto_metadata.page_ordinal); reader.ReadDataEncrypted(*protocol, buffer, buffer_size, aad_crypto_metadata); diff --git a/src/duckdb/extension/parquet/include/parquet_crypto.hpp b/src/duckdb/extension/parquet/include/parquet_crypto.hpp index bc7d801fc..2369888cc 100644 --- a/src/duckdb/extension/parquet/include/parquet_crypto.hpp +++ b/src/duckdb/extension/parquet/include/parquet_crypto.hpp @@ -177,7 +177,7 @@ class ParquetCrypto { public: static int8_t GetModuleHeader(const ColumnChunk &chunk, uint16_t page_ordinal); - static int8_t GetModule(const ColumnChunk &chunk, PageType::type page_type, uint16_t page_ordinal); + static int8_t GetModule(const ColumnChunk &chunk, PageType::type page_type); static int16_t GetFinalPageOrdinal(const ColumnChunk &chunk, uint8_t module, uint16_t page_ordinal); static void GenerateAdditionalAuthenticatedData(Allocator &allocator, CryptoMetaData &aad_crypto_metadata); static unique_ptr GenerateFooterAAD(Allocator &allocator, diff --git a/src/duckdb/extension/parquet/include/parquet_reader.hpp b/src/duckdb/extension/parquet/include/parquet_reader.hpp index a3820e608..25766dab8 100644 --- a/src/duckdb/extension/parquet/include/parquet_reader.hpp +++ b/src/duckdb/extension/parquet/include/parquet_reader.hpp @@ -491,8 +491,11 @@ class ParquetReader : public BaseFileReader { void InitializeSchema(ClientContext &context); //! Parse the schema of the file unique_ptr ParseSchema(ClientContext &context); - ParquetColumnSchema ParseSchemaRecursive(idx_t depth, idx_t max_define, idx_t max_repeat, idx_t &next_schema_idx, - idx_t &next_file_idx, ClientContext &context); + struct ParseSchemaFrame; + ParquetColumnSchema ParseSchemaTree(ClientContext &context, idx_t &next_schema_idx, idx_t &next_file_idx); + bool ParseSchemaElement(ClientContext &context, idx_t depth, idx_t max_define, idx_t max_repeat, idx_t schema_idx, + idx_t &next_file_idx, vector &frames, ParquetColumnSchema &result); + ParquetColumnSchema FinishSchemaElement(ParseSchemaFrame &frame, idx_t next_file_idx); unique_ptr CreateReaderRecursive(ClientContext &context, const ColumnIndex &index, const ParquetColumnSchema &schema) const; diff --git a/src/duckdb/extension/parquet/include/parquet_statistics.hpp b/src/duckdb/extension/parquet/include/parquet_statistics.hpp index 2557e20c4..5eaa249ab 100644 --- a/src/duckdb/extension/parquet/include/parquet_statistics.hpp +++ b/src/duckdb/extension/parquet/include/parquet_statistics.hpp @@ -41,6 +41,7 @@ class Statistics; namespace duckdb { class Allocator; +class ParquetReader; class TableFilter; enum class LogicalTypeId : uint8_t; @@ -83,9 +84,11 @@ struct ParquetStatisticsUtils { ParquetIntervalBloomFilterVersion interval_bloom_filter_version); static bool HasBloomFilterConstants(const TableFilter &filter, ParquetBloomFilterHashStrategy hash_strategy); + //! The reader plus the row group and column ordinals are needed to decrypt the bloom filter of an encrypted file static bool BloomFilterExcludes(const TableFilter &filter, const duckdb_parquet::ColumnMetaData &column_meta_data, duckdb_apache::thrift::protocol::TProtocol &file_proto, Allocator &allocator, - const ParquetColumnSchema &schema, ParquetBloomFilterHashStrategy hash_strategy); + const ParquetColumnSchema &schema, ParquetBloomFilterHashStrategy hash_strategy, + const ParquetReader &reader, int16_t row_group_ordinal, idx_t column_ordinal); static unique_ptr CreateNumericStats(const LogicalType &type, const ParquetColumnSchema &schema_ele, const duckdb_parquet::Statistics &parquet_stats); diff --git a/src/duckdb/extension/parquet/parquet_crypto.cpp b/src/duckdb/extension/parquet/parquet_crypto.cpp index ed92302c8..fe2d016d8 100644 --- a/src/duckdb/extension/parquet/parquet_crypto.cpp +++ b/src/duckdb/extension/parquet/parquet_crypto.cpp @@ -480,24 +480,18 @@ int8_t ParquetCrypto::GetModuleHeader(const ColumnChunk &chunk, uint16_t page_or // always return data page header if ordinal > 0 return DATA_PAGE_HEADER; } - // There is at maximum 1 dictionary, index or bf filter page header per column chunk + // There is at maximum 1 dictionary or index page header per column chunk. + // Bloom filters are not interleaved with the pages: they are read separately via bloom_filter_offset. if (chunk.meta_data.__isset.dictionary_page_offset) { return DICTIONARY_PAGE_HEADER; } else if (chunk.meta_data.__isset.index_page_offset) { return OFFSET_INDEX; - } else if (chunk.meta_data.__isset.bloom_filter_offset) { - return ParquetCrypto::BLOOM_FILTER_HEADER; } return DATA_PAGE_HEADER; } -int8_t ParquetCrypto::GetModule(const ColumnChunk &chunk, PageType::type page_type, uint16_t page_ordinal) { - if (chunk.meta_data.__isset.bloom_filter_offset && page_ordinal == 0) { - // return bitset if it is the first page ordinal - return ParquetCrypto::BLOOM_FILTER_BITSET; - } - +int8_t ParquetCrypto::GetModule(const ColumnChunk &chunk, PageType::type page_type) { switch (page_type) { case PageType::DATA_PAGE: case PageType::DATA_PAGE_V2: @@ -530,8 +524,6 @@ int16_t ParquetCrypto::GetFinalPageOrdinal(const ColumnChunk &chunk, uint8_t mod page_ordinal -= 1; } else if (chunk.meta_data.__isset.index_page_offset) { page_ordinal -= 1; - } else if (chunk.meta_data.__isset.bloom_filter_offset) { - page_ordinal -= 1; } return CheckedPageOrdinal(page_ordinal); case DATA_PAGE: diff --git a/src/duckdb/extension/parquet/parquet_metadata.cpp b/src/duckdb/extension/parquet/parquet_metadata.cpp index 9ff7a4afc..e76635a74 100644 --- a/src/duckdb/extension/parquet/parquet_metadata.cpp +++ b/src/duckdb/extension/parquet/parquet_metadata.cpp @@ -956,9 +956,9 @@ void ParquetBloomProbeProcessor::ReadRow(vector> &output, idx_ D_ASSERT(!probe_constant.IsNull()); auto &column_schema = reader.root_schema->children[probe_column_idx.GetIndex()]; - auto bloom_excludes = - hash_strategy && ParquetStatisticsUtils::BloomFilterExcludes(*filter, column.meta_data, *protocol, - reader.allocator, column_schema, *hash_strategy); + auto bloom_excludes = hash_strategy && ParquetStatisticsUtils::BloomFilterExcludes( + *filter, column.meta_data, *protocol, reader.allocator, column_schema, + *hash_strategy, reader, row_group.ordinal, probe_column_idx.GetIndex()); output[0].get().Append(Value(reader.file.path)); output[1].get().Append(Value::BIGINT(NumericCast(row_idx))); diff --git a/src/duckdb/extension/parquet/parquet_reader.cpp b/src/duckdb/extension/parquet/parquet_reader.cpp index b1accb7f0..39d03c1a8 100644 --- a/src/duckdb/extension/parquet/parquet_reader.cpp +++ b/src/duckdb/extension/parquet/parquet_reader.cpp @@ -1144,9 +1144,28 @@ static optional_ptr FindNonBinaryShreddedValue(const return nullptr; } -ParquetColumnSchema ParquetReader::ParseSchemaRecursive(idx_t depth, idx_t max_define, idx_t max_repeat, - idx_t &next_schema_idx, idx_t &next_file_idx, - ClientContext &context) { +//! A group being parsed, with the schemas of the children parsed so far. The open groups are kept on an explicit +//! stack, so that deeply nested schemas cannot overflow the call stack +struct ParquetReader::ParseSchemaFrame { + ParseSchemaFrame(idx_t schema_idx, idx_t depth, idx_t max_define, idx_t max_repeat, + FieldRepetitionType::type repetition_type, idx_t num_children) + : schema_idx(schema_idx), depth(depth), max_define(max_define), max_repeat(max_repeat), + repetition_type(repetition_type), num_children(num_children) { + } + + idx_t schema_idx; + idx_t depth; + idx_t max_define; + idx_t max_repeat; + FieldRepetitionType::type repetition_type; + idx_t num_children; + vector child_schemas; +}; + +//! Parses a leaf into 'result', or opens the frame of a group and returns true +bool ParquetReader::ParseSchemaElement(ClientContext &context, idx_t depth, idx_t max_define, idx_t max_repeat, + idx_t schema_idx, idx_t &next_file_idx, vector &frames, + ParquetColumnSchema &result) { auto file_meta_data = GetFileMetadata(); D_ASSERT(file_meta_data); if (depth > MAX_PARQUET_SCHEMA_DEPTH) { @@ -1155,15 +1174,14 @@ ParquetColumnSchema ParquetReader::ParseSchemaRecursive(idx_t depth, idx_t max_d "deep", file.path, MAX_PARQUET_SCHEMA_DEPTH); } - if (next_schema_idx >= file_meta_data->schema.size()) { + if (schema_idx >= file_meta_data->schema.size()) { throw InvalidInputException("Malformed Parquet schema in file \"%s\": invalid schema index %d", file.path, - next_schema_idx); + schema_idx); } - auto &s_ele = file_meta_data->schema[next_schema_idx]; - auto this_idx = next_schema_idx; + auto &s_ele = file_meta_data->schema[schema_idx]; auto repetition_type = FieldRepetitionType::REQUIRED; - if (s_ele.__isset.repetition_type && this_idx > 0) { + if (s_ele.__isset.repetition_type && schema_idx > 0) { repetition_type = s_ele.repetition_type; } if (repetition_type != FieldRepetitionType::REQUIRED) { @@ -1197,12 +1215,13 @@ ParquetColumnSchema ParquetReader::ParseSchemaRecursive(idx_t depth, idx_t max_d // Inner BLOB schema vector geometry_child; - geometry_child.emplace_back(ParseColumnSchema(s_ele, max_define, max_repeat, this_idx, next_file_idx)); + geometry_child.emplace_back(ParseColumnSchema(s_ele, max_define, max_repeat, schema_idx, next_file_idx)); // Wrap in geometry schema - return ParquetColumnSchema::FromChildSchemas(s_ele.name, target_type, max_define, max_repeat, this_idx, - next_file_idx++, std::move(geometry_child), - ParquetColumnSchemaType::GEOMETRY); + result = ParquetColumnSchema::FromChildSchemas(s_ele.name, target_type, max_define, max_repeat, schema_idx, + next_file_idx++, std::move(geometry_child), + ParquetColumnSchemaType::GEOMETRY); + return false; } // Determine if this is an inner node @@ -1216,142 +1235,169 @@ ParquetColumnSchema ParquetReader::ParseSchemaRecursive(idx_t depth, idx_t max_d is_inner_node = s_ele.__isset.num_children && s_ele.num_children > 0; } - if (is_inner_node) { // inner node - vector child_schemas; - - idx_t c_idx = 0; + if (is_inner_node) { idx_t num_children = 0; if (s_ele.__isset.num_children && !TryCast::Operation(s_ele.num_children, num_children)) { throw InvalidInputException( "Failed to read Parquet file \"%s\": schema element has negative number of children", file.path); } - while (c_idx < num_children) { - next_schema_idx++; + frames.emplace_back(schema_idx, depth, max_define, max_repeat, repetition_type, num_children); + return true; + } + // leaf node + if (!s_ele.__isset.type) { + throw InvalidInputException( + "Node '%s' has neither num_children nor type set - this violates the Parquet spec (corrupted file)", + s_ele.name.c_str()); + } + result = ParseColumnSchema(s_ele, max_define, max_repeat, schema_idx, next_file_idx++); + if (s_ele.repetition_type == FieldRepetitionType::REPEATED) { + auto list_type = LogicalType::LIST(result.type); + vector list_child = {std::move(result)}; + result = ParquetColumnSchema::FromChildSchemas(s_ele.name, list_type, max_define, max_repeat, schema_idx, + next_file_idx, std::move(list_child)); + } + return false; +} - auto child_schema = - ParseSchemaRecursive(depth + 1, max_define, max_repeat, next_schema_idx, next_file_idx, context); - child_schemas.push_back(std::move(child_schema)); - c_idx++; +//! Builds the schema of a group once the schemas of all its children are parsed +ParquetColumnSchema ParquetReader::FinishSchemaElement(ParseSchemaFrame &frame, idx_t next_file_idx) { + auto file_meta_data = GetFileMetadata(); + const auto this_idx = frame.schema_idx; + const auto max_define = frame.max_define; + const auto max_repeat = frame.max_repeat; + auto &s_ele = file_meta_data->schema[this_idx]; + auto &child_schemas = frame.child_schemas; + + // rename child type entries if there are case-insensitive duplicates by appending _1, _2 etc. + // behavior consistent with CSV reader fwiw + case_insensitive_map_t name_collision_count; + for (auto &child_schema : child_schemas) { + auto &col_name = child_schema.name; + // avoid duplicate header names + while (name_collision_count.find(col_name) != name_collision_count.end()) { + name_collision_count[col_name] += 1; + col_name = col_name + "_" + to_string(name_collision_count[col_name]); + } + child_schema.name = col_name; + name_collision_count[col_name] = 0; + } + + bool is_repeated = frame.repetition_type == FieldRepetitionType::REPEATED; + const bool is_list = s_ele.__isset.converted_type && s_ele.converted_type == ConvertedType::LIST; + const bool is_map = s_ele.__isset.converted_type && s_ele.converted_type == ConvertedType::MAP; + bool is_map_kv = s_ele.__isset.converted_type && s_ele.converted_type == ConvertedType::MAP_KEY_VALUE; + bool is_variant = s_ele.__isset.logicalType && s_ele.logicalType.__isset.VARIANT == true; + if (!is_variant && parquet_options.variant_legacy_encoding && IsVariantType(s_ele, child_schemas)) { + is_variant = true; + } + if (is_variant) { + if (child_schemas.size() < 2) { + throw DataCorruptionException("Failed to read Parquet file \"%s\": VARIANT column \"%s\" must have a " + "'metadata' and a 'value' column", + file.path, string(s_ele.name)); } - // rename child type entries if there are case-insensitive duplicates by appending _1, _2 etc. - // behavior consistent with CSV reader fwiw - case_insensitive_map_t name_collision_count; for (auto &child_schema : child_schemas) { - auto &col_name = child_schema.name; - // avoid duplicate header names - while (name_collision_count.find(col_name) != name_collision_count.end()) { - name_collision_count[col_name] += 1; - col_name = col_name + "_" + to_string(name_collision_count[col_name]); - } - child_schema.name = col_name; - name_collision_count[col_name] = 0; - } - - bool is_repeated = repetition_type == FieldRepetitionType::REPEATED; - const bool is_list = s_ele.__isset.converted_type && s_ele.converted_type == ConvertedType::LIST; - const bool is_map = s_ele.__isset.converted_type && s_ele.converted_type == ConvertedType::MAP; - bool is_map_kv = s_ele.__isset.converted_type && s_ele.converted_type == ConvertedType::MAP_KEY_VALUE; - bool is_variant = s_ele.__isset.logicalType && s_ele.logicalType.__isset.VARIANT == true; - if (!is_variant && parquet_options.variant_legacy_encoding && IsVariantType(s_ele, child_schemas)) { - is_variant = true; - } - if (is_variant) { - if (child_schemas.size() < 2) { - throw DataCorruptionException("Failed to read Parquet file \"%s\": VARIANT column \"%s\" must have a " - "'metadata' and a 'value' column", - file.path, string(s_ele.name)); - } - for (auto &child_schema : child_schemas) { - if (child_schema.name != "metadata" && child_schema.name != "value") { - // the 'value' columns of the groups below 'typed_value' are read as binary as well - if (FindNonBinaryShreddedValue(child_schema)) { - throw DataCorruptionException( - "Failed to read Parquet file \"%s\": the 'value' column of a shredded field of VARIANT " - "column \"%s\" must be a binary BYTE_ARRAY column", - file.path, string(s_ele.name)); - } - continue; - } - if (!IsVariantBinaryColumn(child_schema)) { + if (child_schema.name != "metadata" && child_schema.name != "value") { + // the 'value' columns of the groups below 'typed_value' are read as binary as well + if (FindNonBinaryShreddedValue(child_schema)) { throw DataCorruptionException( - "Failed to read Parquet file \"%s\": the '%s' column of VARIANT column \"%s\" " - "must be a binary BYTE_ARRAY column", - file.path, child_schema.name, string(s_ele.name)); + "Failed to read Parquet file \"%s\": the 'value' column of a shredded field of VARIANT " + "column \"%s\" must be a binary BYTE_ARRAY column", + file.path, string(s_ele.name)); } + continue; + } + if (!IsVariantBinaryColumn(child_schema)) { + throw DataCorruptionException("Failed to read Parquet file \"%s\": the '%s' column of VARIANT column " + "\"%s\" must be a binary BYTE_ARRAY column", + file.path, child_schema.name, string(s_ele.name)); } } + } + + if (!is_map_kv && this_idx > 0) { + // check if the parent node of this is a map + auto &p_ele = file_meta_data->schema[this_idx - 1]; + bool parent_is_map = p_ele.__isset.converted_type && p_ele.converted_type == ConvertedType::MAP; + bool parent_has_children = p_ele.__isset.num_children && p_ele.num_children == 1; + is_map_kv = parent_is_map && parent_has_children; + } - if (!is_map_kv && this_idx > 0) { - // check if the parent node of this is a map - auto &p_ele = file_meta_data->schema[this_idx - 1]; - bool parent_is_map = p_ele.__isset.converted_type && p_ele.converted_type == ConvertedType::MAP; - bool parent_has_children = p_ele.__isset.num_children && p_ele.num_children == 1; - is_map_kv = parent_is_map && parent_has_children; + if (is_map_kv) { + if (child_schemas.size() != 2) { + throw IOException("MAP_KEY_VALUE requires two children"); + } + if (!is_repeated) { + throw IOException("MAP_KEY_VALUE needs to be repeated"); + } + auto result_type = LogicalType::MAP(child_schemas[0].type, child_schemas[1].type); + vector map_children; + map_children.emplace_back(ParquetColumnSchema::FromChildSchemas(s_ele.name, ListType::GetChildType(result_type), + max_define - 1, max_repeat - 1, this_idx, + next_file_idx, std::move(child_schemas))); + return ParquetColumnSchema::FromChildSchemas(s_ele.name, result_type, max_define, max_repeat, this_idx, + next_file_idx, std::move(map_children)); + } + ParquetColumnSchema result; + if (child_schemas.size() > 1 || (!is_list && !is_map && !is_repeated)) { + child_list_t struct_types; + for (auto &child_schema : child_schemas) { + struct_types.emplace_back(make_pair(child_schema.name, child_schema.type)); } - if (is_map_kv) { - if (child_schemas.size() != 2) { - throw IOException("MAP_KEY_VALUE requires two children"); - } - if (!is_repeated) { - throw IOException("MAP_KEY_VALUE needs to be repeated"); - } - auto result_type = LogicalType::MAP(child_schemas[0].type, child_schemas[1].type); - vector map_children; - map_children.emplace_back(ParquetColumnSchema::FromChildSchemas( - s_ele.name, ListType::GetChildType(result_type), max_define - 1, max_repeat - 1, this_idx, - next_file_idx, std::move(child_schemas))); - return ParquetColumnSchema::FromChildSchemas(s_ele.name, result_type, max_define, max_repeat, this_idx, - next_file_idx, std::move(map_children)); - } - ParquetColumnSchema result; - if (child_schemas.size() > 1 || (!is_list && !is_map && !is_repeated)) { - child_list_t struct_types; - for (auto &child_schema : child_schemas) { - struct_types.emplace_back(make_pair(child_schema.name, child_schema.type)); - } + LogicalType result_type; + if (is_variant) { + result_type = LogicalType::VARIANT(); + } else { + result_type = LogicalType::STRUCT(std::move(struct_types)); + } + ParquetColumnSchemaType schema_type = + is_variant ? ParquetColumnSchemaType::VARIANT : ParquetColumnSchemaType::COLUMN; + result = ParquetColumnSchema::FromChildSchemas(s_ele.name, result_type, max_define, max_repeat, this_idx, + next_file_idx, std::move(child_schemas), schema_type); + } else if (child_schemas.empty()) { + throw InvalidInputException("Failed to read Parquet file \"%s\": schema element has no children", file.path); + } else { + // if we have a struct with only a single type, pull up + result = std::move(child_schemas[0]); + result.name = s_ele.name; + } + if (is_repeated) { + auto list_type = LogicalType::LIST(result.type); + vector list_child = {std::move(result)}; + result = ParquetColumnSchema::FromChildSchemas(s_ele.name, list_type, max_define, max_repeat, this_idx, + next_file_idx, std::move(list_child)); + } + result.parent_schema_index = this_idx; + return result; +} - LogicalType result_type; - if (is_variant) { - result_type = LogicalType::VARIANT(); - } else { - result_type = LogicalType::STRUCT(std::move(struct_types)); +ParquetColumnSchema ParquetReader::ParseSchemaTree(ClientContext &context, idx_t &next_schema_idx, + idx_t &next_file_idx) { + vector frames; + ParquetColumnSchema root; + if (!ParseSchemaElement(context, 0, 0, 0, next_schema_idx, next_file_idx, frames, root)) { + return root; + } + while (true) { + auto &frame = frames.back(); + if (frame.child_schemas.size() < frame.num_children) { + next_schema_idx++; + ParquetColumnSchema child; + // the frame is not used after the child opened a frame of its own, which may move it + if (!ParseSchemaElement(context, frame.depth + 1, frame.max_define, frame.max_repeat, next_schema_idx, + next_file_idx, frames, child)) { + frame.child_schemas.push_back(std::move(child)); } - ParquetColumnSchemaType schema_type = - is_variant ? ParquetColumnSchemaType::VARIANT : ParquetColumnSchemaType::COLUMN; - result = ParquetColumnSchema::FromChildSchemas(s_ele.name, result_type, max_define, max_repeat, this_idx, - next_file_idx, std::move(child_schemas), schema_type); - } else if (child_schemas.empty()) { - throw InvalidInputException("Failed to read Parquet file \"%s\": schema element has no children", - file.path); - } else { - // if we have a struct with only a single type, pull up - result = std::move(child_schemas[0]); - result.name = s_ele.name; - } - if (is_repeated) { - auto list_type = LogicalType::LIST(result.type); - vector list_child = {std::move(result)}; - result = ParquetColumnSchema::FromChildSchemas(s_ele.name, list_type, max_define, max_repeat, this_idx, - next_file_idx, std::move(list_child)); - } - result.parent_schema_index = this_idx; - return result; - } else { // leaf node - if (!s_ele.__isset.type) { - throw InvalidInputException( - "Node '%s' has neither num_children nor type set - this violates the Parquet spec (corrupted file)", - s_ele.name.c_str()); + continue; } - auto result = ParseColumnSchema(s_ele, max_define, max_repeat, this_idx, next_file_idx++); - if (s_ele.repetition_type == FieldRepetitionType::REPEATED) { - auto list_type = LogicalType::LIST(result.type); - vector list_child = {std::move(result)}; - return ParquetColumnSchema::FromChildSchemas(s_ele.name, list_type, max_define, max_repeat, this_idx, - next_file_idx, std::move(list_child)); + auto schema = FinishSchemaElement(frame, next_file_idx); + frames.pop_back(); + if (frames.empty()) { + return schema; } - - return result; + frames.back().child_schemas.push_back(std::move(schema)); } } @@ -1374,7 +1420,7 @@ unique_ptr ParquetReader::ParseSchema(ClientContext &contex if (file_meta_data->schema[0].num_children == 0) { throw IOException("Failed to read Parquet file \"%s\": root schema element has no children", file.path); } - auto root = ParseSchemaRecursive(0, 0, 0, next_schema_idx, next_file_idx, context); + auto root = ParseSchemaTree(context, next_schema_idx, next_file_idx); if (!StructType::IsStruct(root.type)) { throw InvalidInputException("Failed to read Parquet file \"%s\": Root element of Parquet file must be a struct", file.path); @@ -2048,7 +2094,8 @@ void ParquetReader::PrepareRowGroupBuffer(ClientContext &context, ParquetReaderS } if (ParquetStatisticsUtils::BloomFilterExcludes( *bloom_filter, group.columns[bloom_reader->ColumnIndex()].meta_data, - *state.thrift_file_proto, allocator, bloom_reader->Schema(), *hash_strategy)) { + *state.thrift_file_proto, allocator, bloom_reader->Schema(), *hash_strategy, *this, + group.ordinal, bloom_reader->ColumnIndex())) { prune_result = FilterPropagateResult::FILTER_ALWAYS_FALSE; } } diff --git a/src/duckdb/extension/parquet/parquet_statistics.cpp b/src/duckdb/extension/parquet/parquet_statistics.cpp index 8a5e8a79a..608fbce99 100644 --- a/src/duckdb/extension/parquet/parquet_statistics.cpp +++ b/src/duckdb/extension/parquet/parquet_statistics.cpp @@ -55,6 +55,7 @@ #include "duckdb/storage/statistics/string_stats.hpp" #include "duckdb/storage/statistics/variant_stats.hpp" #include "parquet_column_schema.hpp" +#include "parquet_crypto.hpp" #include "parquet_reader.hpp" #include "parquet_types.h" #include "thrift/protocol/TProtocol.h" @@ -1287,15 +1288,24 @@ bool ParquetStatisticsUtils::HasBloomFilterConstants(const TableFilter &filter, return HasFilterConstants(filter, hash_strategy); } -bool ParquetStatisticsUtils::BloomFilterExcludes(const TableFilter &duckdb_filter, - const duckdb_parquet::ColumnMetaData &column_meta_data, - TProtocol &file_proto, Allocator &allocator, - const ParquetColumnSchema &schema, - ParquetBloomFilterHashStrategy hash_strategy) { +bool ParquetStatisticsUtils::BloomFilterExcludes( + const TableFilter &duckdb_filter, const duckdb_parquet::ColumnMetaData &column_meta_data, TProtocol &file_proto, + Allocator &allocator, const ParquetColumnSchema &schema, ParquetBloomFilterHashStrategy hash_strategy, + const ParquetReader &reader, int16_t row_group_ordinal, idx_t column_ordinal) { if (!HasFilterConstants(duckdb_filter, hash_strategy) || !column_meta_data.__isset.bloom_filter_offset || column_meta_data.bloom_filter_offset <= 0) { return false; } + optional_ptr file_crypto_metadata; + if (reader.metadata) { + file_crypto_metadata = reader.metadata->crypto_metadata.get(); + } + const bool encrypted = file_crypto_metadata != nullptr; + if (encrypted && (!reader.parquet_options.encryption_config || !reader.encryption_util || + !file_crypto_metadata->encryption_algorithm.__isset.AES_GCM_V1)) { + // the bloom filter modules cannot be decrypted + return false; + } auto &transport = reinterpret_cast(*file_proto.getTransport()); auto bloom_filter_start = UnsafeNumericCast(column_meta_data.bloom_filter_offset); @@ -1323,8 +1333,15 @@ bool ParquetStatisticsUtils::BloomFilterExcludes(const TableFilter &duckdb_filte } duckdb_parquet::BloomFilterHeader filter_header; - // TODO the bloom filter could be encrypted, too, so need to double check that this is NOT the case - filter_header.read(&file_proto); + CryptoMetaData bloom_crypto_metadata(allocator); + if (encrypted) { + bloom_crypto_metadata.Initialize(file_crypto_metadata->encryption_algorithm.AES_GCM_V1.aad_file_unique, + row_group_ordinal, NumericCast(column_ordinal), + ParquetCrypto::BLOOM_FILTER_HEADER); + reader.ReadEncrypted(filter_header, file_proto, bloom_crypto_metadata); + } else { + filter_header.read(&file_proto); + } if (!filter_header.algorithm.__isset.BLOCK || !filter_header.compression.__isset.UNCOMPRESSED || !filter_header.hash.__isset.XXHASH) { return false; @@ -1337,20 +1354,30 @@ bool ParquetStatisticsUtils::BloomFilterExcludes(const TableFilter &duckdb_filte if (bloom_filter_data_size % sizeof(ParquetBloomBlock) != 0) { return false; } - if (bloom_filter_data_start < bloom_filter_start || bloom_filter_data_size > transport.GetSize() || - bloom_filter_data_start > transport.GetSize() - bloom_filter_data_size) { + // an encrypted bitset module is framed by its length, nonce and tag on disk + const idx_t bloom_filter_on_disk_size = encrypted ? bloom_filter_data_size + ParquetCrypto::LENGTH_BYTES + + ParquetCrypto::NONCE_BYTES + ParquetCrypto::TAG_BYTES + : bloom_filter_data_size; + if (bloom_filter_data_start < bloom_filter_start || bloom_filter_on_disk_size > transport.GetSize() || + bloom_filter_data_start > transport.GetSize() - bloom_filter_on_disk_size) { return false; } if (bloom_filter_length > 0) { auto bloom_filter_header_size = bloom_filter_data_start - bloom_filter_start; if (bloom_filter_header_size > bloom_filter_length || - bloom_filter_data_size != bloom_filter_length - bloom_filter_header_size) { + bloom_filter_on_disk_size != bloom_filter_length - bloom_filter_header_size) { return false; } } auto new_buffer = make_uniq(allocator, bloom_filter_data_size); - transport.read(new_buffer->GetCurrentLoc(), UnsafeNumericCast(bloom_filter_data_size)); + if (encrypted) { + bloom_crypto_metadata.SetModule(ParquetCrypto::BLOOM_FILTER_BITSET); + reader.ReadDataEncrypted(file_proto, new_buffer->GetCurrentLoc(), + UnsafeNumericCast(bloom_filter_data_size), bloom_crypto_metadata); + } else { + transport.read(new_buffer->GetCurrentLoc(), UnsafeNumericCast(bloom_filter_data_size)); + } ParquetBloomFilter bloom_filter(std::move(new_buffer)); return ApplyBloomFilter(duckdb_filter, bloom_filter, schema, hash_strategy); } diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 07e0650e6..9a32effb0 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-alpha57892"; + descriptor->api_version = "v2.1.0-alpha58110"; 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-alpha57892"; + descriptor->api_version = "v2.1.0-alpha58110"; 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-alpha57892"; + descriptor->api_version = "v2.1.0-alpha58110"; 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-alpha57892"; + descriptor->api_version = "v2.1.0-alpha58110"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/catalog/catalog.cpp b/src/duckdb/src/catalog/catalog.cpp index 510a089fc..de344d286 100644 --- a/src/duckdb/src/catalog/catalog.cpp +++ b/src/duckdb/src/catalog/catalog.cpp @@ -91,6 +91,9 @@ optional_ptr Catalog::GetCatalogEntry(CatalogEntryRetriever &retriever, auto &context = retriever.GetContext(); auto &db_manager = DatabaseManager::Get(context); if (catalog_name == TEMP_CATALOG) { + if (context.transaction.HasActiveTransaction()) { + return &context.transaction.ActiveTransaction().GetTemporaryObjects().GetCatalog(); + } return &ClientData::Get(context).temporary_objects->GetCatalog(); } if (catalog_name == SYSTEM_CATALOG) { diff --git a/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp b/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp index 0f8fdd313..87da4b915 100644 --- a/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp @@ -35,6 +35,8 @@ #include "duckdb/storage/table/data_table_info.hpp" #include "duckdb/storage/data_table.hpp" #include "duckdb/transaction/local_storage.hpp" +#include "duckdb/transaction/meta_transaction.hpp" +#include "duckdb/main/client_context.hpp" #include "duckdb/main/attached_database.hpp" namespace duckdb { @@ -213,6 +215,10 @@ const ColumnList &DuckTableEntry::GetColumns() const { } unique_ptr DuckTableEntry::GetStatistics(ClientContext &context, const StorageIndex &column_id) { + if (context.transaction.HasActiveTransaction() && context.transaction.ActiveTransaction().IsShared()) { + // connections sharing the transaction can write values outside of the statistics before the query reads them + return nullptr; + } // Get the committed statistics auto stats = storage->GetStatistics(context, column_id); if (!stats) { @@ -1418,7 +1424,7 @@ unique_ptr DuckTableEntry::AddConstraint(ClientContext &context, A } // The indexes of constraints must precede all other indexes. A concurrent CREATE INDEX is not visible as a - // dependency yet, but it has already registered its index with the storage. + // dependency yet, so the new storage checks the indexes registered with it. idx_t constraint_index_count = 0; for (const auto &constraint : GetConstraints()) { if (constraint->type == ConstraintType::UNIQUE) { @@ -1431,9 +1437,6 @@ unique_ptr DuckTableEntry::AddConstraint(ClientContext &context, A } } } - if (storage->GetDataTableInfo()->GetIndexes().Count() > constraint_index_count) { - throw DependencyException("Cannot alter entry %s because there are entries that depend on it.", name); - } // We create a physical table with a new constraint and a new unique index. const auto binder = Binder::CreateBinder(context); @@ -1442,7 +1445,7 @@ unique_ptr DuckTableEntry::AddConstraint(ClientContext &context, A const auto bound_create_info = binder->BindCreateTableInfo(std::move(create_info), schema, info.bind_mode); SetAlterDependencies(context, *bound_create_info, info); - auto new_storage = make_shared_ptr(context, *storage, *bound_constraint); + auto new_storage = make_shared_ptr(context, *storage, *bound_constraint, constraint_index_count); auto new_entry = make_uniq(catalog, schema, *bound_create_info, new_storage, triggers); return std::move(new_entry); } diff --git a/src/duckdb/src/catalog/catalog_set.cpp b/src/duckdb/src/catalog/catalog_set.cpp index 1e7757323..d2a285214 100644 --- a/src/duckdb/src/catalog/catalog_set.cpp +++ b/src/duckdb/src/catalog/catalog_set.cpp @@ -356,7 +356,12 @@ bool CatalogSet::AlterEntry(CatalogTransaction transaction, const Identifier &na // fetch the entry again before doing the modification // this will catch any write-write conflicts between transactions + auto original_entry = entry.get(); entry = GetEntryInternal(transaction, name); + if (!entry || entry.get() != original_entry) { + // a connection that shares the transaction changed the entry in the meantime + throw TransactionException("Catalog write-write conflict on alter with %s", name); + } // Mark this entry as being created by this transaction value->timestamp = transaction.GetTransactionId(); diff --git a/src/duckdb/src/catalog/default/default_views.cpp b/src/duckdb/src/catalog/default/default_views.cpp index 11511d524..008c01dba 100644 --- a/src/duckdb/src/catalog/default/default_views.cpp +++ b/src/duckdb/src/catalog/default/default_views.cpp @@ -40,8 +40,10 @@ static const DefaultView internal_views[] = { {"pg_catalog", "pg_attribute", "SELECT table_oid attrelid, column_name attname, " "coalesce(map_type_id_to_pg_oid(data_type_id), data_type_id + 16384) atttypid, 0 attstattarget, NULL attlen, " - "column_index attnum, 0 attndims, -1 attcacheoff, case when data_type ilike '%decimal%' then " - "numeric_precision*1000+numeric_scale else -1 end atttypmod, false attbyval, NULL attstorage, NULL attalign, NOT " + "column_index attnum, 0 attndims, -1 attcacheoff, coalesce(case when data_type ilike '%decimal%' and " + "numeric_scale <= 999 then try_cast(numeric_precision*1000+numeric_scale as integer) end, -1) atttypmod, " + "false attbyval, NULL attstorage, " + "NULL attalign, NOT " "is_nullable attnotnull, column_default IS NOT NULL atthasdef, false atthasmissing, '' attidentity, '' " "attgenerated, false attisdropped, true attislocal, 0 attinhcount, 0 attcollation, NULL attcompression, NULL " "attacl, NULL attoptions, NULL attfdwoptions, NULL attmissingval FROM duckdb_columns()"}, diff --git a/src/duckdb/src/catalog/dependency_manager.cpp b/src/duckdb/src/catalog/dependency_manager.cpp index 829bcbc93..594403220 100644 --- a/src/duckdb/src/catalog/dependency_manager.cpp +++ b/src/duckdb/src/catalog/dependency_manager.cpp @@ -1,4 +1,5 @@ #include "duckdb/catalog/dependency_manager.hpp" +#include "duckdb/common/exception/transaction_exception.hpp" #include "duckdb/transaction/transaction_data.hpp" #include "duckdb/catalog/catalog_entry/type_catalog_entry.hpp" #include "duckdb/catalog/duck_catalog.hpp" @@ -257,7 +258,9 @@ void DependencyManager::CreateDependency(CatalogTransaction transaction, Depende auto subject_entry = LookupEntry(transaction, info.subject.entry); info.subject.oid = subject_entry ? subject_entry->oid : optional_idx(); if (!subject_entry) { - throw InternalException("Couldn't locate entry: '%s'", CatalogEntryInfoToString(info.subject.entry)); + // a connection that shares the transaction dropped or renamed the entry in the meantime + throw TransactionException("Catalog write-write conflict: could not locate entry '%s'", + CatalogEntryInfoToString(info.subject.entry)); } DependencyCatalogSet subjects(Subjects(), info.dependent.entry); diff --git a/src/duckdb/src/common/adbc/adbc.cpp b/src/duckdb/src/common/adbc/adbc.cpp index 643918a6b..4d30982be 100644 --- a/src/duckdb/src/common/adbc/adbc.cpp +++ b/src/duckdb/src/common/adbc/adbc.cpp @@ -3039,9 +3039,9 @@ AdbcStatusCode ConnectionGetObjects(struct AdbcConnection *connection, int depth WHEN base_type = 'DATE' THEN 10::INTEGER WHEN data_type IN ('TIME', 'TIME WITH TIME ZONE', 'TIME_NS') THEN 15::INTEGER WHEN data_type LIKE 'TIMESTAMP%%' THEN 26::INTEGER - ELSE numeric_precision::INTEGER + ELSE TRY_CAST(numeric_precision AS INTEGER) END, - xdbc_decimal_digits: numeric_scale::SMALLINT, + xdbc_decimal_digits: TRY_CAST(numeric_scale AS SMALLINT), xdbc_num_prec_radix: numeric_precision_radix::SMALLINT, xdbc_nullable: CASE is_nullable WHEN FALSE THEN 0::SMALLINT diff --git a/src/duckdb/src/common/base_file_system.cpp b/src/duckdb/src/common/base_file_system.cpp new file mode 100644 index 000000000..5d9d10416 --- /dev/null +++ b/src/duckdb/src/common/base_file_system.cpp @@ -0,0 +1,1021 @@ +#include "duckdb/main/context.hpp" +#include "duckdb/common/base_file_system.hpp" +#include "duckdb/common/file_system.hpp" + +#include "duckdb/common/checksum.hpp" +#include "duckdb/common/time_point.hpp" +#include "duckdb/common/compressed_file_system.hpp" +#include "duckdb/common/exception.hpp" +#include "duckdb/common/file_opener.hpp" +#include "duckdb/common/helper.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/common/multi_file/multi_file_list.hpp" +#include "duckdb/common/windows.hpp" +#include "duckdb/function/scalar/string_functions.hpp" +#include "duckdb/logging/log_type.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/client_data.hpp" +#include "duckdb/main/database.hpp" +#include "duckdb/main/extension_helper.hpp" +#include "duckdb/common/windows_util.hpp" +#include "duckdb/common/operator/multiply.hpp" +#include "duckdb/logging/log_manager.hpp" + +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef __EMSCRIPTEN__ +#include +#endif + +#else +#include +#include + +#ifdef __MINGW32__ +// need to manually define this for mingw +extern "C" WINBASEAPI BOOL WINAPI GetPhysicallyInstalledSystemMemory(PULONGLONG); +#endif + +#undef FILE_CREATE // woo mingw +#endif + +namespace duckdb { + +const FileOpenFlags FileFlags::FILE_FLAGS_READ = FileOpenFlags(FileOpenFlags::FILE_FLAGS_READ); +const FileOpenFlags FileFlags::FILE_FLAGS_WRITE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_WRITE); +const FileOpenFlags FileFlags::FILE_FLAGS_DIRECT_IO = FileOpenFlags(FileOpenFlags::FILE_FLAGS_DIRECT_IO); +const FileOpenFlags FileFlags::FILE_FLAGS_FILE_CREATE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_FILE_CREATE); +const FileOpenFlags FileFlags::FILE_FLAGS_FILE_CREATE_NEW = FileOpenFlags(FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW); +const FileOpenFlags FileFlags::FILE_FLAGS_APPEND = FileOpenFlags(FileOpenFlags::FILE_FLAGS_APPEND); +const FileOpenFlags FileFlags::FILE_FLAGS_PRIVATE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_PRIVATE); +const FileOpenFlags FileFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS = + FileOpenFlags(FileOpenFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS); +const FileOpenFlags FileFlags::FILE_FLAGS_PARALLEL_ACCESS = FileOpenFlags(FileOpenFlags::FILE_FLAGS_PARALLEL_ACCESS); +const FileOpenFlags FileFlags::FILE_FLAGS_EXCLUSIVE_CREATE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_EXCLUSIVE_CREATE); +const FileOpenFlags FileFlags::FILE_FLAGS_NULL_IF_EXISTS = FileOpenFlags(FileOpenFlags::FILE_FLAGS_NULL_IF_EXISTS); +const FileOpenFlags FileFlags::FILE_FLAGS_MULTI_CLIENT_ACCESS = + FileOpenFlags(FileOpenFlags::FILE_FLAGS_MULTI_CLIENT_ACCESS); +const FileOpenFlags FileFlags::FILE_FLAGS_DISABLE_LOGGING = FileOpenFlags(FileOpenFlags::FILE_FLAGS_DISABLE_LOGGING); +const FileOpenFlags FileFlags::FILE_FLAGS_ENABLE_EXTENSION_INSTALL = + FileOpenFlags(FileOpenFlags::FILE_FLAGS_ENABLE_EXTENSION_INSTALL); + +void FileOpenFlags::Verify() { +#ifdef DEBUG + bool is_read = flags & FileOpenFlags::FILE_FLAGS_READ; + bool is_write = flags & FileOpenFlags::FILE_FLAGS_WRITE; + bool is_create = + (flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE) || (flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW); + bool is_private = (flags & FileOpenFlags::FILE_FLAGS_PRIVATE); + bool null_if_not_exists = flags & FileOpenFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS; + bool exclusive_create = flags & FileOpenFlags::FILE_FLAGS_EXCLUSIVE_CREATE; + bool null_if_exists = flags & FileOpenFlags::FILE_FLAGS_NULL_IF_EXISTS; + + // require either READ or WRITE (or both) + D_ASSERT(is_read || is_write); + // CREATE/Append flags require writing + D_ASSERT(is_write || !(flags & FileOpenFlags::FILE_FLAGS_APPEND)); + D_ASSERT(is_write || !(flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE)); + D_ASSERT(is_write || !(flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW)); + // cannot combine CREATE and CREATE_NEW flags + D_ASSERT(!(flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE && flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW)); + + // For is_private can only be set along with a create flag + D_ASSERT(!is_private || is_create); + // FILE_FLAGS_NULL_IF_NOT_EXISTS cannot be combined with CREATE/CREATE_NEW + D_ASSERT(!(null_if_not_exists && is_create)); + // FILE_FLAGS_EXCLUSIVE_CREATE only can be combined with CREATE/CREATE_NEW + D_ASSERT(!exclusive_create || is_create); + // FILE_FLAGS_NULL_IF_EXISTS only can be set with EXCLUSIVE_CREATE + D_ASSERT(!null_if_exists || exclusive_create); +#endif +} + +BaseFileSystem::~BaseFileSystem() { +} + +FileSystem &FileSystem::GetFileSystem(ClientContext &context) { + return context.GetContext().GetFileSystem(); +} + +bool PathMatched(const string &path, const string &sub_path) { + return path.rfind(sub_path, 0) == 0; +} + +#ifndef _WIN32 + +string FileSystem::GetEnvVariable(const string &name) { + const char *env = getenv(name.c_str()); + if (!env) { + return string(); + } + return env; +} + +bool BaseFileSystem::IsPathAbsolute(const string &path) { + auto path_separator = PathSeparator(path); + return PathMatched(path, path_separator) || StringUtil::StartsWith(path, "file:/"); +} + +string BaseFileSystem::PathSeparator(const string &path) { + return "/"; +} + +void FileSystem::SetWorkingDirectory(const string &path) { + if (chdir(path.c_str()) != 0) { + throw IOException("Could not change working directory!"); + } +} + +optional_idx FileSystem::GetAvailableMemory() { + errno = 0; + +#ifdef __MVS__ + struct rlimit limit; + int rlim_rc = getrlimit(RLIMIT_AS, &limit); + idx_t max_memory = MinValue(limit.rlim_max, UINTPTR_MAX); +#else + idx_t max_memory = MinValue((idx_t)sysconf(_SC_PHYS_PAGES) * (idx_t)sysconf(_SC_PAGESIZE), UINTPTR_MAX); +#endif + if (errno != 0) { + return optional_idx(); + } + return max_memory; +} + +optional_idx FileSystem::GetAvailableDiskSpace(const string &path) { + struct statvfs vfs; + + auto ret = statvfs(path.c_str(), &vfs); + if (ret == -1) { + return optional_idx(); + } + auto block_size = vfs.f_frsize; + // These are the blocks available for creating new files or extending existing ones + auto available_blocks = vfs.f_bfree; + idx_t available_disk_space = DConstants::INVALID_INDEX; + if (!TryMultiplyOperator::Operation(static_cast(block_size), static_cast(available_blocks), + available_disk_space)) { + return optional_idx(); + } + return available_disk_space; +} + +string FileSystem::GetWorkingDirectory() { + auto buffer = make_unsafe_uniq_array(PATH_MAX); + char *ret = getcwd(buffer.get(), PATH_MAX); + if (!ret) { + throw IOException("Could not get working directory!"); + } + return string(buffer.get()); +} + +#else + +string FileSystem::GetEnvVariable(const string &env) { + // first convert the environment variable name to the correct encoding + auto env_w = WindowsUtil::UTF8ToUnicode(env.c_str()); + // use _wgetenv to get the value + auto res_w = _wgetenv(env_w.c_str()); + if (!res_w) { + // no environment variable of this name found + return string(); + } + return WindowsUtil::UnicodeToUTF8(res_w); +} + +static bool StartsWithSingleBackslash(const string &path) { + if (path.empty()) { + return false; + } + if (path[0] != '/' && path[0] != '\\') { + return false; + } + if (path.size() == 1) { + return true; + } + if (path[1] == '/' || path[1] == '\\') { + return false; + } + return true; +} + +bool BaseFileSystem::IsPathAbsolute(const string &path) { + // 1) A single backslash or forward-slash + if (StartsWithSingleBackslash(path)) { + return true; + } + // 2) special "long paths" on windows + if (PathMatched(path, "\\\\?\\")) { + return true; + } + // 3) a network path + if (PathMatched(path, "\\\\")) { + return true; + } + // 4) A disk designator with a backslash (e.g., C:\ or C:/) + auto path_aux = path; + path_aux.erase(0, 1); + if (PathMatched(path_aux, ":\\") || PathMatched(path_aux, ":/")) { + return true; + } + return false; +} + +string BaseFileSystem::PathSeparator(const string &path) { + if (StringUtil::StartsWith(path, "file:")) { + return "/"; + } else { + return "\\"; + } +} + +void FileSystem::SetWorkingDirectory(const string &path) { + auto unicode_path = WindowsUtil::UTF8ToUnicode(path.c_str()); + if (!SetCurrentDirectoryW(unicode_path.c_str())) { + throw IOException("Could not change working directory to \"%s\"", path); + } +} + +optional_idx FileSystem::GetAvailableMemory() { + ULONGLONG available_memory_kb; + if (GetPhysicallyInstalledSystemMemory(&available_memory_kb)) { + return MinValue(available_memory_kb * 1000, UINTPTR_MAX); + } + // fallback: try GlobalMemoryStatusEx + MEMORYSTATUSEX mem_state; + mem_state.dwLength = sizeof(MEMORYSTATUSEX); + + if (GlobalMemoryStatusEx(&mem_state)) { + return MinValue(mem_state.ullTotalPhys, UINTPTR_MAX); + } + return optional_idx(); +} + +optional_idx FileSystem::GetAvailableDiskSpace(const string &path) { + ULARGE_INTEGER available_bytes, total_bytes, free_bytes; + + auto unicode_path = WindowsUtil::UTF8ToUnicode(path.c_str()); + if (!GetDiskFreeSpaceExW(unicode_path.c_str(), &available_bytes, &total_bytes, &free_bytes)) { + return optional_idx(); + } + (void)total_bytes; + (void)free_bytes; + return NumericCast(available_bytes.QuadPart); +} + +string FileSystem::GetWorkingDirectory() { + idx_t count = GetCurrentDirectoryW(0, nullptr); + if (count == 0) { + throw IOException("Could not get working directory!"); + } + auto buffer = make_unsafe_uniq_array(count); + idx_t ret = GetCurrentDirectoryW(count, buffer.get()); + if (count != ret + 1) { + throw IOException("Could not get working directory!"); + } + return WindowsUtil::UnicodeToUTF8(buffer.get()); +} + +#endif + +optional_idx FileSystem::GetFileDescriptorLimit() { +#if !defined(_WIN32) && !defined(__EMSCRIPTEN__) + struct rlimit limit; + if (getrlimit(RLIMIT_NOFILE, &limit) != 0 || limit.rlim_cur == RLIM_INFINITY) { + return optional_idx(); + } + if (limit.rlim_cur >= NumericLimits::Maximum()) { + return optional_idx(); + } + return optional_idx(static_cast(limit.rlim_cur)); +#else + return optional_idx(); +#endif +} + +idx_t FileSystem::GetFileDescriptorShare(idx_t file_descriptor_limit) { + return MaxValue(file_descriptor_limit / 8, 1); +} + +string BaseFileSystem::JoinPath(const string &a, const string &b) { + // A remote URL may carry a "?query" suffix (object version, requester-pays, an SSE-C key, ...). + // Appending a path segment after it would bury the query mid-path and corrupt both the query and + // the object path, so join onto the path without the query and keep the query at the very end. + auto scheme = a.find("://"); + if (scheme != string::npos) { + auto query = a.find('?', scheme + 3); + if (query != string::npos) { + return Path::FromString(a.substr(0, query)).Join(b).ToString() + a.substr(query); + } + } + return Path::FromString(a).Join(b).ToString(); +} + +string BaseFileSystem::ConvertSeparators(const string &path) { + auto separator_str = PathSeparator(path); + char separator = separator_str[0]; + if (separator == '/') { + // on unix-based systems we only accept / as a separator + return path; + } + // on windows-based systems we accept both + return StringUtil::Replace(path, "/", separator_str); +} + +string BaseFileSystem::ExtractName(const string &path) { + if (path.empty()) { + return string(); + } + auto normalized_path = ConvertSeparators(path); + auto sep = PathSeparator(path); + auto splits = StringUtil::Split(normalized_path, sep); + D_ASSERT(!splits.empty()); + return splits.back(); +} + +string BaseFileSystem::ExtractBaseName(const string &path) { + if (path.empty()) { + return string(); + } + auto vec = StringUtil::Split(ExtractName(path), "."); + D_ASSERT(!vec.empty()); + return vec[0]; +} + +string BaseFileSystem::ExtractExtension(const string &path) { + if (path.empty()) { + return string(); + } + auto vec = StringUtil::Split(ExtractName(path), "."); + if (vec.size() < 2) { + return string(); + } + return vec.back(); +} + +string FileSystem::GetHomeDirectory(optional_ptr opener) { + // read the home_directory setting first, if it is set + if (opener) { + Value result; + if (opener->TryGetCurrentSetting("home_directory", result)) { + if (!result.IsNull() && !result.ToString().empty()) { + return result.ToString(); + } + } + } + // fallback to the default home directories for the specified system +#ifdef DUCKDB_WINDOWS + return FileSystem::GetEnvVariable("USERPROFILE"); +#else + return FileSystem::GetEnvVariable("HOME"); +#endif +} + +string BaseFileSystem::GetHomeDirectory() { + return FileSystem::GetHomeDirectory(nullptr); +} + +// Helper function to handle file:/ URLs +static idx_t GetFileUrlOffset(const string &path) { + if (!StringUtil::StartsWith(path, "file:/")) { + return 0; + } + + // Url without host: file:/some/path + if (path[6] != '/') { +#ifdef _WIN32 + return 6; +#else + return 5; +#endif + } + + // Url with empty host: file:///some/path + if (path[7] == '/') { +#ifdef _WIN32 + return 8; +#else + return 7; +#endif + } + + // Url with localhost: file://localhost/some/path + if (path.compare(7, 10, "localhost/") == 0) { +#ifdef _WIN32 + return 17; +#else + return 16; +#endif + } + + // unknown file:/ url format + return 0; +} + +string FileSystem::ExpandPath(const string &path, optional_ptr opener) { + if (path.empty()) { + return path; + } + if (path[0] == '~') { + return FileSystem::GetHomeDirectory(opener) + path.substr(1); + } + // handle file URIs + auto file_offset = GetFileUrlOffset(path); + if (file_offset > 0) { + return path.substr(file_offset); + } + return path; +} + +string BaseFileSystem::ExpandPath(const string &path) { + return FileSystem::ExpandPath(path, nullptr); +} + +// LCOV_EXCL_START +unique_ptr BaseFileSystem::OpenFileExtended(const OpenFileInfo &path, + FileOpenFlags flags, // NOLINT: virtual, overrides mutate flags + optional_ptr opener) { + throw NotImplementedException("%s: OpenFileExtended is not implemented!", GetName()); +} + +bool BaseFileSystem::ListFilesExtended(const string &directory, const std::function &callback, + optional_ptr opener) { + throw NotImplementedException("%s: ListFilesExtended is not implemented!", GetName()); +} + +unique_ptr BaseFileSystem::OpenFile(const string &path, FileOpenFlags flags, + optional_ptr opener) { + if (SupportsOpenFileExtended()) { + return OpenFileExtended(OpenFileInfo(path), std::move(flags), opener); + } + throw NotImplementedException("%s: OpenFile is not implemented!", GetName()); +} + +unique_ptr BaseFileSystem::OpenFile(const OpenFileInfo &file, const FileOpenFlags &flags, + optional_ptr opener) { + if (SupportsOpenFileExtended()) { + return OpenFileExtended(file, flags, opener); + } else { + return OpenFile(file.path, flags, opener); + } +} + +bool BaseFileSystem::SupportsOpenFileExtended() const { + return false; +} + +bool BaseFileSystem::SupportsListFilesExtended() const { + return false; +} + +bool BaseFileSystem::SupportsGlobExtended() const { + return false; +} + +void BaseFileSystem::Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) { + throw NotImplementedException("%s: Read (with location) is not implemented!", GetName()); +} + +void BaseFileSystem::Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) { + throw NotImplementedException("%s: Write (with location) is not implemented!", GetName()); +} + +int64_t BaseFileSystem::Read(FileHandle &handle, void *buffer, int64_t nr_bytes) { + throw NotImplementedException("%s: Read is not implemented!", GetName()); +} + +int64_t BaseFileSystem::Write(FileHandle &handle, void *buffer, int64_t nr_bytes) { + throw NotImplementedException("%s: Write is not implemented!", GetName()); +} + +bool BaseFileSystem::Trim(FileHandle &handle, idx_t offset_bytes, idx_t length_bytes) { + // This is not a required method. Derived FileSystems may optionally override/implement. + return false; +} + +int64_t BaseFileSystem::GetFileSize(FileHandle &handle) { + throw NotImplementedException("%s: GetFileSize is not implemented!", GetName()); +} + +timestamp_t BaseFileSystem::GetLastModifiedTime(FileHandle &handle) { + throw NotImplementedException("%s: GetLastModifiedTime is not implemented!", GetName()); +} + +string BaseFileSystem::GetVersionTag(FileHandle &handle) { + // Used to check cache invalidation for httpfs files with an ETag in CachingFileSystem + return ""; +} + +optional BaseFileSystem::GetCacheValidUntil(FileHandle &handle) { + return nullopt; +} + +FileType BaseFileSystem::GetFileType(FileHandle &handle) { + return FileType::FILE_TYPE_INVALID; +} + +FileMetadata BaseFileSystem::Stats(FileHandle &handle) { + FileMetadata metadata; + metadata.file_size = GetFileSize(handle); + metadata.last_modification_time = GetLastModifiedTime(handle); + metadata.file_type = GetFileType(handle); + metadata.version_tag = GetVersionTag(handle); + metadata.cache_valid_until = GetCacheValidUntil(handle); + return metadata; +} + +optional BaseFileSystem::GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) { + auto handle = OpenFile(file, FileFlags::FILE_FLAGS_READ | FileFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS, opener); + if (!handle) { + return nullopt; + } + return Stats(*handle); +} + +void BaseFileSystem::Truncate(FileHandle &handle, int64_t new_size) { + throw NotImplementedException("%s: Truncate is not implemented!", GetName()); +} + +bool BaseFileSystem::DirectoryExists(const string &directory, optional_ptr opener) { + throw NotImplementedException("%s: DirectoryExists is not implemented!", GetName()); +} + +void BaseFileSystem::CreateDirectory(const string &directory, optional_ptr opener) { + throw NotImplementedException("%s: CreateDirectory is not implemented!", GetName()); +} + +bool BaseFileSystem::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, + optional_ptr opener) { + switch (options.mode) { + case CreateDirectoryMode::SINGLE: + if (!DirectoryExists(directory, opener)) { + CreateDirectory(directory, opener); + } + return false; + case CreateDirectoryMode::RECURSIVE: { + auto parsed = Path::FromString(directory); + vector directories; + while (!parsed.GetPathSegments().empty() && !DirectoryExists(parsed.ToString(), opener)) { + directories.push_back(parsed.ToString()); + parsed = parsed.Parent(); + } + if (parsed.GetPathSegments().empty() && !DirectoryExists(parsed.ToString(), opener)) { + directories.push_back(parsed.ToString()); + } + + bool target_created = false; + for (auto riter = directories.rbegin(); riter != directories.rend(); ++riter) { + auto created = CreateDirectoryExtended(*riter, {CreateDirectoryMode::SINGLE}, opener); + if (*riter == directories.front()) { + target_created = created; + } + } + return target_created; + } + default: + throw InternalException("Unknown CreateDirectoryMode"); + } +} + +void BaseFileSystem::CreateDirectoriesRecursive(const string &path, optional_ptr opener) { + CreateDirectoryExtended(path, {CreateDirectoryMode::RECURSIVE}, opener); +} + +void BaseFileSystem::RemoveDirectory(const string &directory, optional_ptr opener) { + throw NotImplementedException("%s: RemoveDirectory is not implemented!", GetName()); +} + +bool BaseFileSystem::RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, + optional_ptr opener) { + switch (options.mode) { + case RemoveDirectoryMode::SINGLE: + return false; + case RemoveDirectoryMode::RECURSIVE: + RemoveDirectory(directory, opener); + return false; + default: + throw InternalException("Unknown RemoveDirectoryMode"); + } +} + +bool FileSystem::IsDirectory(const OpenFileInfo &info) { + if (!info.extended_info) { + return false; + } + string type; + if (!info.extended_info->TryGetOption("type", type)) { + return false; + } + return type == "directory"; +} + +bool BaseFileSystem::ListFiles(const string &directory, const std::function &callback, + FileOpener *opener) { + if (SupportsListFilesExtended()) { + return ListFilesExtended( + directory, + [&](const OpenFileInfo &info) { + bool is_dir = FileSystem::IsDirectory(info); + callback(info.path, is_dir); + }, + opener); + } + throw NotImplementedException("%s: ListFiles is not implemented!", GetName()); +} + +bool BaseFileSystem::ListFiles(const string &directory, const std::function &callback, + optional_ptr opener) { + if (SupportsListFilesExtended()) { + return ListFilesExtended(directory, callback, opener); + } else { + return ListFiles( + directory, + [&](const string &path, bool is_dir) { + OpenFileInfo info(path); + if (is_dir) { + info.extended_info = make_shared_ptr(); + info.extended_info->options["type"] = "directory"; + } + callback(info); + }, + opener.get()); + } +} + +void BaseFileSystem::MoveFile(const string &source, const string &target, optional_ptr opener) { + throw NotImplementedException("%s: MoveFile is not implemented!", GetName()); +} + +bool BaseFileSystem::FileExists(const string &filename, optional_ptr opener) { + throw NotImplementedException("%s: FileExists is not implemented!", GetName()); +} + +bool BaseFileSystem::IsPipe(const string &filename, optional_ptr opener) { + return false; +} + +void BaseFileSystem::RemoveFile(const string &filename, optional_ptr opener) { + throw NotImplementedException("%s: RemoveFile is not implemented!", GetName()); +} + +bool BaseFileSystem::TryRemoveFile(const string &filename, optional_ptr opener) { + if (FileExists(filename, opener)) { + RemoveFile(filename, opener); + return true; + } + return false; +} + +void BaseFileSystem::RemoveFiles(const vector &filenames, optional_ptr opener) { + for (const auto &filename : filenames) { + TryRemoveFile(filename, opener); + } +} + +void BaseFileSystem::FileSync(FileHandle &handle) { + throw NotImplementedException("%s: FileSync is not implemented!", GetName()); +} + +void BaseFileSystem::AbortFileWrite(FileHandle &handle) { + handle.Close(); +} + +bool FileSystem::HasGlob(const string &str) { + for (idx_t i = 0; i < str.size(); i++) { + switch (str[i]) { + case '*': + case '?': + case '[': + return true; + default: + break; + } + } + return false; +} + +vector BaseFileSystem::Glob(const string &path, FileOpener *opener) { + if (SupportsGlobExtended()) { + auto result = GlobFilesExtended(path, FileGlobOptions::ALLOW_EMPTY, opener); + return result->GetAllFiles(); + } + throw NotImplementedException("%s: Glob is not implemented!", GetName()); +} + +unique_ptr BaseFileSystem::Glob(const string &path, const FileGlobInput &input, + optional_ptr opener) { + if (!SupportsGlobExtended()) { + auto result = Glob(path, opener.get()); + return make_uniq(std::move(result)); + } else { + return GlobFilesExtended(path, input, opener); + } +} + +unique_ptr BaseFileSystem::GlobFilesExtended(const string &path, const FileGlobInput &input, + optional_ptr opener) { + throw NotImplementedException("%s: GlobFilesExtended is not implemented!", GetName()); +} + +bool BaseFileSystem::CanHandleFile(const string &fpath) { + throw NotImplementedException("%s: CanHandleFile is not implemented!", GetName()); +} + +void BaseFileSystem::Seek(FileHandle &handle, idx_t location) { + throw NotImplementedException("%s: Seek is not implemented!", GetName()); +} + +void BaseFileSystem::Reset(FileHandle &handle) { + handle.Seek(0); +} + +idx_t BaseFileSystem::SeekPosition(FileHandle &handle) { + throw NotImplementedException("%s: SeekPosition is not implemented!", GetName()); +} + +bool BaseFileSystem::CanSeek() { + throw NotImplementedException("%s: CanSeek is not implemented!", GetName()); +} + +bool BaseFileSystem::IsManuallySet() { + return false; +} + +FileWriteMode BaseFileSystem::GetWriteMode(FileHandle &handle) { + return FileWriteMode::SEQUENTIAL; +} + +unique_ptr BaseFileSystem::OpenCompressedFile(QueryContext context, unique_ptr handle, + bool write) { + throw NotImplementedException("%s: OpenCompressedFile is not implemented!", GetName()); +} + +bool BaseFileSystem::IsLocalFileSystem() const { + return false; +} + +bool BaseFileSystem::OnDiskFile(FileHandle &handle) { + throw NotImplementedException("%s: OnDiskFile is not implemented!", GetName()); +} +// LCOV_EXCL_STOP + +bool BaseFileSystem::TryGetNetworkThroughput(FileHandle &handle, NetworkThroughputEstimate &result) { + return false; +} + +FileHandle::FileHandle(BaseFileSystem &file_system, string path_p, FileOpenFlags flags_p) + : file_system(file_system), path(std::move(path_p)), flags(std::move(flags_p)) { +} + +FileHandle::~FileHandle() { +} + +int64_t FileHandle::Read(void *buffer, idx_t nr_bytes) { + return file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes)); +} + +static optional_ptr GetTrackingProfiler(bool track_io, const QueryContext &context) { + if (!track_io || !context.Valid()) { + return nullptr; + } + return context.GetContext()->TryGetQueryProfiler(); +} + +int64_t FileHandle::Read(QueryContext context, void *buffer, idx_t nr_bytes) { + auto profiler = GetTrackingProfiler(track_io, context); + const bool track = profiler != nullptr; + const auto start = track ? TimePoint::Tick() : TimePoint(); + // A sequential read can return fewer bytes than requested (e.g. at EOF), so track the bytes + // actually read rather than the requested amount. + auto bytes_read = file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes)); + if (track) { + const auto elapsed_us = NumericCast(start.ElapsedMicros()); + profiler->TrackBytesRead(UnsafeNumericCast(bytes_read), elapsed_us); + } + + return bytes_read; +} + +bool FileHandle::Trim(idx_t offset_bytes, idx_t length_bytes) { + return file_system.Trim(*this, offset_bytes, length_bytes); +} + +int64_t FileHandle::Write(void *buffer, idx_t nr_bytes) { + return file_system.Write(*this, buffer, UnsafeNumericCast(nr_bytes)); +} + +int64_t FileHandle::Write(QueryContext context, void *buffer, idx_t nr_bytes) { + auto profiler = GetTrackingProfiler(track_io, context); + const bool track = profiler != nullptr; + const auto start = track ? TimePoint::Tick() : TimePoint(); + auto bytes_written = file_system.Write(*this, buffer, UnsafeNumericCast(nr_bytes)); + if (bytes_written > 0 && track) { + const auto elapsed_us = NumericCast(start.ElapsedMicros()); + profiler->TrackBytesWritten(UnsafeNumericCast(bytes_written), elapsed_us); + } + + return bytes_written; +} + +void FileHandle::Read(void *buffer, idx_t nr_bytes, idx_t location) { + file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes), location); +} + +void FileHandle::Read(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location) { + auto profiler = GetTrackingProfiler(track_io, context); + const bool track = profiler != nullptr; + const auto start = track ? TimePoint::Tick() : TimePoint(); + file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes), location); + if (track) { + const auto elapsed_us = NumericCast(start.ElapsedMicros()); + profiler->TrackBytesRead(nr_bytes, elapsed_us); + } +} + +void FileHandle::Write(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location) { + auto profiler = GetTrackingProfiler(track_io, context); + const bool track = profiler != nullptr; + const auto start = track ? TimePoint::Tick() : TimePoint(); + file_system.Write(*this, buffer, UnsafeNumericCast(nr_bytes), location); + if (track) { + const auto elapsed_us = NumericCast(start.ElapsedMicros()); + profiler->TrackBytesWritten(nr_bytes, elapsed_us); + } +} + +void FileHandle::Seek(idx_t location) { + file_system.Seek(*this, location); +} + +void FileHandle::Reset() { + file_system.Reset(*this); +} + +idx_t FileHandle::SeekPosition() { + return file_system.SeekPosition(*this); +} + +bool FileHandle::CanSeek() { + return file_system.CanSeek(); +} + +FileWriteMode FileHandle::GetWriteMode() { + return file_system.GetWriteMode(*this); +} + +FileCompressionType FileHandle::GetFileCompressionType() { + return FileCompressionType::UNCOMPRESSED; +} + +bool FileHandle::IsPipe() { + return file_system.IsPipe(path, nullptr); +} + +string FileHandle::ReadLine() { + string result; + char buffer[1]; + while (true) { + auto tuples_read = UnsafeNumericCast(Read(buffer, 1)); + if (tuples_read == 0 || buffer[0] == '\n') { + return result; + } + if (buffer[0] != '\r') { + result += buffer[0]; + } + } +} + +string FileHandle::ReadLine(QueryContext context) { + string result; + char buffer[1]; + while (true) { + auto tuples_read = UnsafeNumericCast(Read(context, buffer, 1)); + if (tuples_read == 0 || buffer[0] == '\n') { + return result; + } + if (buffer[0] != '\r') { + result += buffer[0]; + } + } +} + +bool FileHandle::OnDiskFile() { + return file_system.OnDiskFile(*this); +} + +bool FileHandle::TryGetNetworkThroughput(NetworkThroughputEstimate &result) { + return file_system.TryGetNetworkThroughput(*this, result); +} + +idx_t FileHandle::GetFileSize() { + return NumericCast(file_system.GetFileSize(*this)); +} + +void FileHandle::Sync() { + file_system.FileSync(*this); +} + +void FileHandle::Truncate(int64_t new_size) { + file_system.Truncate(*this, new_size); +} + +void FileHandle::AbortWrite() { + file_system.AbortFileWrite(*this); +} + +FileType FileHandle::GetType() { + return file_system.GetFileType(*this); +} + +FileMetadata FileHandle::Stats() { + return file_system.Stats(*this); +} + +void FileHandle::TryAddLogger(FileOpener &opener) { + if (flags.DisableLogging()) { + return; + } + + auto &context = opener.TryGetContext(); + if (context.IsClient() && context.GetLogger().ShouldLog(FileSystemLogType::NAME, FileSystemLogType::LEVEL)) { + logger = context.GetLoggerPtr(); + return; + } + + auto database = opener.TryGetDatabase(); + if (database && Logger::Get(*database).ShouldLog(FileSystemLogType::NAME, FileSystemLogType::LEVEL)) { + logger = database->GetLogManager().GlobalLoggerReference(); + } +} + +idx_t FileHandle::GetProgress() { + throw NotImplementedException("GetProgress is not implemented for this file handle"); +} + +bool FileSystem::IsRemoteFile(const string &path) { + string extension = ""; + return FileSystem::IsRemoteFile(path, extension); +} + +bool FileSystem::IsRemoteFile(const string &path, string &extension) { + for (const auto &entry : EXTENSION_FILE_PREFIXES) { + if (StringUtil::StartsWith(path, entry.name)) { + extension = entry.extension; + return true; + } + } + return false; +} + +string BaseFileSystem::CanonicalizePath(const string &path_p, optional_ptr opener) { + // TODO: @benfleis - integrate this properly with Path (needs additional work) + if (FileSystem::IsRemoteFile(path_p) || !Path::FromString(path_p).IsLocal()) { + // don't canonicalize remote paths + return path_p; + } + auto path_sep = PathSeparator(path_p); + auto elements = StringUtil::Split(path_p, path_sep); + + deque path_stack; + string result; + for (idx_t i = 0; i < elements.size(); i++) { + if (elements[i].empty() || elements[i] == ".") { + // we ignore empty and `.` + continue; + } + if (elements[i] == "..") { + // .. pops from stack if possible, if already at root its ignored + if (!path_stack.empty()) { + path_stack.pop_back(); + } + } else { + path_stack.push_back(elements[i]); + } + } + // we lost the leading / in the split/loop so lets put it back + if (path_p[0] == '/') { + result = "/"; + } + while (!path_stack.empty()) { + result += path_stack.front(); + path_stack.pop_front(); + if (!path_stack.empty()) { + result += path_sep; + } + } + + return result; +} + +} // namespace duckdb diff --git a/src/duckdb/src/common/compressed_file_system.cpp b/src/duckdb/src/common/compressed_file_system.cpp index 97dcd81e5..ab3693df0 100644 --- a/src/duckdb/src/common/compressed_file_system.cpp +++ b/src/duckdb/src/common/compressed_file_system.cpp @@ -163,7 +163,7 @@ int64_t CompressedFile::WriteData(data_ptr_t buffer, int64_t nr_bytes) { } // Clear does most of the heavy lifting of a close, but leaves the child_handle intact. Specifically it is separated out -// to support upstream Reset() calls from the FileSystem, which should tear down / reset ephemeral state but leave +// to support upstream Reset() calls from the BaseFileSystem, which should tear down / reset ephemeral state but leave // persistent state (child_handle) intact. void CompressedFile::Clear() { if (stream_wrapper) { diff --git a/src/duckdb/src/common/enum_util.cpp b/src/duckdb/src/common/enum_util.cpp index 442a0f269..4df1fdfaa 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -3495,8 +3495,8 @@ IndexConstraintType EnumUtil::FromString(const char *value) const StringUtil::EnumStringLiteral *GetIndexDeltaTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(IndexDeltaType::DELETED_ROWS_IN_USE), "DELETED_ROWS_IN_USE" }, - { static_cast(IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT), "ADDED_DATA_DURING_CHECKPOINT" }, - { static_cast(IndexDeltaType::REMOVED_DATA_DURING_CHECKPOINT), "REMOVED_DATA_DURING_CHECKPOINT" } + { static_cast(IndexDeltaType::ADDED_DATA), "ADDED_DATA" }, + { static_cast(IndexDeltaType::REMOVED_DATA), "REMOVED_DATA" } }; return values; } @@ -7452,19 +7452,20 @@ const StringUtil::EnumStringLiteral *GetTransactionTypeValues() { { static_cast(TransactionType::INVALID), "INVALID" }, { static_cast(TransactionType::BEGIN_TRANSACTION), "BEGIN_TRANSACTION" }, { static_cast(TransactionType::COMMIT), "COMMIT" }, - { static_cast(TransactionType::ROLLBACK), "ROLLBACK" } + { static_cast(TransactionType::ROLLBACK), "ROLLBACK" }, + { static_cast(TransactionType::JOIN_TRANSACTION), "JOIN_TRANSACTION" } }; return values; } template<> const char* EnumUtil::ToChars(TransactionType value) { - return StringUtil::EnumToString(GetTransactionTypeValues(), 4, "TransactionType", static_cast(value)); + return StringUtil::EnumToString(GetTransactionTypeValues(), 5, "TransactionType", static_cast(value)); } template<> TransactionType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetTransactionTypeValues(), 4, "TransactionType", value)); + return static_cast(StringUtil::StringToEnum(GetTransactionTypeValues(), 5, "TransactionType", value)); } const StringUtil::EnumStringLiteral *GetTransformChildKindValues() { diff --git a/src/duckdb/src/common/enums/statement_type.cpp b/src/duckdb/src/common/enums/statement_type.cpp index 54e7ba7d2..fc6827e53 100644 --- a/src/duckdb/src/common/enums/statement_type.cpp +++ b/src/duckdb/src/common/enums/statement_type.cpp @@ -97,7 +97,13 @@ string StatementReturnTypeToString(StatementReturnType type) { void StatementProperties::RegisterDBRead(Catalog &catalog, ClientContext &context) { auto catalog_identity = CatalogIdentity {catalog.GetOid(), catalog.GetCatalogVersion(context)}; - D_ASSERT(read_databases.count(catalog.GetName()) == 0 || read_databases[catalog.GetName()] == catalog_identity); + auto entry = read_databases.find(catalog.GetName()); + if (entry != read_databases.end()) { + // a connection that shares the transaction can change the catalog version while the statement is bound: + // keep the first version, so that the statement is rebound + D_ASSERT(entry->second.catalog_oid == catalog_identity.catalog_oid); + return; + } read_databases[catalog.GetName()] = catalog_identity; } @@ -109,8 +115,9 @@ void StatementProperties::RegisterDBModify(Catalog &catalog, ClientContext &cont // new entry - set the identity entry.first->second.identity = catalog_identity; } else { - // existing entry - verify this has the same identity - D_ASSERT(entry.first->second.identity == catalog_identity); + // existing entry - the version can change when a connection that shares the transaction modifies the catalog, + // keep the first one so that the statement is rebound + D_ASSERT(entry.first->second.identity.catalog_oid == catalog_identity.catalog_oid); } entry.first->second.modifications |= modification; } diff --git a/src/duckdb/src/common/file_system.cpp b/src/duckdb/src/common/file_system.cpp index ddc350927..f235b73ba 100644 --- a/src/duckdb/src/common/file_system.cpp +++ b/src/duckdb/src/common/file_system.cpp @@ -1,739 +1,185 @@ -#include "duckdb/main/context.hpp" -#include "duckdb/common/file_system.hpp" - -#include "duckdb/common/checksum.hpp" -#include "duckdb/common/time_point.hpp" #include "duckdb/common/compressed_file_system.hpp" -#include "duckdb/common/exception.hpp" -#include "duckdb/common/file_opener.hpp" -#include "duckdb/common/helper.hpp" -#include "duckdb/common/string_util.hpp" +#include "duckdb/common/file_system.hpp" #include "duckdb/common/multi_file/multi_file_list.hpp" -#include "duckdb/common/windows.hpp" -#include "duckdb/function/scalar/string_functions.hpp" -#include "duckdb/logging/log_type.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/main/client_data.hpp" +#include "duckdb/common/path.hpp" +#include "duckdb/common/file_opener.hpp" +#include "duckdb/common/memory_mapped_file.hpp" #include "duckdb/main/database.hpp" -#include "duckdb/main/extension_helper.hpp" -#include "duckdb/common/windows_util.hpp" -#include "duckdb/common/operator/multiply.hpp" -#include "duckdb/logging/log_manager.hpp" - -#include -#include - -#ifndef _WIN32 -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef __EMSCRIPTEN__ -#include -#endif - -#else -#include -#include - -#ifdef __MINGW32__ -// need to manually define this for mingw -extern "C" WINBASEAPI BOOL WINAPI GetPhysicallyInstalledSystemMemory(PULONGLONG); -#endif - -#undef FILE_CREATE // woo mingw -#endif +#include "duckdb/main/config.hpp" +#include "duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp" namespace duckdb { -const FileOpenFlags FileFlags::FILE_FLAGS_READ = FileOpenFlags(FileOpenFlags::FILE_FLAGS_READ); -const FileOpenFlags FileFlags::FILE_FLAGS_WRITE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_WRITE); -const FileOpenFlags FileFlags::FILE_FLAGS_DIRECT_IO = FileOpenFlags(FileOpenFlags::FILE_FLAGS_DIRECT_IO); -const FileOpenFlags FileFlags::FILE_FLAGS_FILE_CREATE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_FILE_CREATE); -const FileOpenFlags FileFlags::FILE_FLAGS_FILE_CREATE_NEW = FileOpenFlags(FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW); -const FileOpenFlags FileFlags::FILE_FLAGS_APPEND = FileOpenFlags(FileOpenFlags::FILE_FLAGS_APPEND); -const FileOpenFlags FileFlags::FILE_FLAGS_PRIVATE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_PRIVATE); -const FileOpenFlags FileFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS = - FileOpenFlags(FileOpenFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS); -const FileOpenFlags FileFlags::FILE_FLAGS_PARALLEL_ACCESS = FileOpenFlags(FileOpenFlags::FILE_FLAGS_PARALLEL_ACCESS); -const FileOpenFlags FileFlags::FILE_FLAGS_EXCLUSIVE_CREATE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_EXCLUSIVE_CREATE); -const FileOpenFlags FileFlags::FILE_FLAGS_NULL_IF_EXISTS = FileOpenFlags(FileOpenFlags::FILE_FLAGS_NULL_IF_EXISTS); -const FileOpenFlags FileFlags::FILE_FLAGS_MULTI_CLIENT_ACCESS = - FileOpenFlags(FileOpenFlags::FILE_FLAGS_MULTI_CLIENT_ACCESS); -const FileOpenFlags FileFlags::FILE_FLAGS_DISABLE_LOGGING = FileOpenFlags(FileOpenFlags::FILE_FLAGS_DISABLE_LOGGING); -const FileOpenFlags FileFlags::FILE_FLAGS_ENABLE_EXTENSION_INSTALL = - FileOpenFlags(FileOpenFlags::FILE_FLAGS_ENABLE_EXTENSION_INSTALL); - -void FileOpenFlags::Verify() { -#ifdef DEBUG - bool is_read = flags & FileOpenFlags::FILE_FLAGS_READ; - bool is_write = flags & FileOpenFlags::FILE_FLAGS_WRITE; - bool is_create = - (flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE) || (flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW); - bool is_private = (flags & FileOpenFlags::FILE_FLAGS_PRIVATE); - bool null_if_not_exists = flags & FileOpenFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS; - bool exclusive_create = flags & FileOpenFlags::FILE_FLAGS_EXCLUSIVE_CREATE; - bool null_if_exists = flags & FileOpenFlags::FILE_FLAGS_NULL_IF_EXISTS; - - // require either READ or WRITE (or both) - D_ASSERT(is_read || is_write); - // CREATE/Append flags require writing - D_ASSERT(is_write || !(flags & FileOpenFlags::FILE_FLAGS_APPEND)); - D_ASSERT(is_write || !(flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE)); - D_ASSERT(is_write || !(flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW)); - // cannot combine CREATE and CREATE_NEW flags - D_ASSERT(!(flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE && flags & FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW)); - - // For is_private can only be set along with a create flag - D_ASSERT(!is_private || is_create); - // FILE_FLAGS_NULL_IF_NOT_EXISTS cannot be combined with CREATE/CREATE_NEW - D_ASSERT(!(null_if_not_exists && is_create)); - // FILE_FLAGS_EXCLUSIVE_CREATE only can be combined with CREATE/CREATE_NEW - D_ASSERT(!exclusive_create || is_create); - // FILE_FLAGS_NULL_IF_EXISTS only can be set with EXCLUSIVE_CREATE - D_ASSERT(!null_if_exists || exclusive_create); -#endif -} - -FileSystem::~FileSystem() { -} - -FileSystem &FileSystem::GetFileSystem(ClientContext &context) { - return context.GetContext().GetFileSystem(); -} - -bool PathMatched(const string &path, const string &sub_path) { - return path.rfind(sub_path, 0) == 0; -} - -#ifndef _WIN32 - -string FileSystem::GetEnvVariable(const string &name) { - const char *env = getenv(name.c_str()); - if (!env) { - return string(); - } - return env; -} - -bool FileSystem::IsPathAbsolute(const string &path) { - auto path_separator = PathSeparator(path); - return PathMatched(path, path_separator) || StringUtil::StartsWith(path, "file:/"); -} - -string FileSystem::PathSeparator(const string &path) { - return "/"; -} - -void FileSystem::SetWorkingDirectory(const string &path) { - if (chdir(path.c_str()) != 0) { - throw IOException("Could not change working directory!"); - } -} - -optional_idx FileSystem::GetAvailableMemory() { - errno = 0; - -#ifdef __MVS__ - struct rlimit limit; - int rlim_rc = getrlimit(RLIMIT_AS, &limit); - idx_t max_memory = MinValue(limit.rlim_max, UINTPTR_MAX); -#else - idx_t max_memory = MinValue((idx_t)sysconf(_SC_PHYS_PAGES) * (idx_t)sysconf(_SC_PAGESIZE), UINTPTR_MAX); -#endif - if (errno != 0) { - return optional_idx(); - } - return max_memory; -} - -optional_idx FileSystem::GetAvailableDiskSpace(const string &path) { - struct statvfs vfs; - - auto ret = statvfs(path.c_str(), &vfs); - if (ret == -1) { - return optional_idx(); - } - auto block_size = vfs.f_frsize; - // These are the blocks available for creating new files or extending existing ones - auto available_blocks = vfs.f_bfree; - idx_t available_disk_space = DConstants::INVALID_INDEX; - if (!TryMultiplyOperator::Operation(static_cast(block_size), static_cast(available_blocks), - available_disk_space)) { - return optional_idx(); - } - return available_disk_space; +void FileSystem::RegisterCompressionFilesystem(unique_ptr fs) { + GetFileSystem().RegisterCompressionFilesystem(std::move(fs)); } -string FileSystem::GetWorkingDirectory() { - auto buffer = make_unsafe_uniq_array(PATH_MAX); - char *ret = getcwd(buffer.get(), PATH_MAX); - if (!ret) { - throw IOException("Could not get working directory!"); - } - return string(buffer.get()); -} - -#else - -string FileSystem::GetEnvVariable(const string &env) { - // first convert the environment variable name to the correct encoding - auto env_w = WindowsUtil::UTF8ToUnicode(env.c_str()); - // use _wgetenv to get the value - auto res_w = _wgetenv(env_w.c_str()); - if (!res_w) { - // no environment variable of this name found - return string(); - } - return WindowsUtil::UnicodeToUTF8(res_w); +unique_ptr FileSystem::OpenFile(const string &path, const FileOpenFlags &flags) { + return OpenFile(OpenFileInfo(path), flags); } -static bool StartsWithSingleBackslash(const string &path) { - if (path.empty()) { - return false; - } - if (path[0] != '/' && path[0] != '\\') { - return false; +unique_ptr FileSystem::OpenFile(const OpenFileInfo &file, const FileOpenFlags &flags) { + VerifyCanAccessFile(file.path); + if (IsDuckDBExtensionName(file.path)) { + VerifyCanAccessExtension(file.path, flags); } - if (path.size() == 1) { - return true; + auto fixed_fs = GetFixedFileSystem(); + if (fixed_fs) { + return fixed_fs->OpenFile(file, flags, GetOpener()); } - if (path[1] == '/' || path[1] == '\\') { - return false; + if (flags.GetCachingMode() == CachingMode::NO_CACHING) { + return GetFileSystem().OpenFile(file, flags, GetOpener()); } - return true; + return OpenCachedFile(file, flags); } -bool FileSystem::IsPathAbsolute(const string &path) { - // 1) A single backslash or forward-slash - if (StartsWithSingleBackslash(path)) { - return true; - } - // 2) special "long paths" on windows - if (PathMatched(path, "\\\\?\\")) { - return true; - } - // 3) a network path - if (PathMatched(path, "\\\\")) { - return true; - } - // 4) A disk designator with a backslash (e.g., C:\ or C:/) - auto path_aux = path; - path_aux.erase(0, 1); - if (PathMatched(path_aux, ":\\") || PathMatched(path_aux, ":/")) { - return true; - } - return false; -} +unique_ptr FileSystem::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); -string FileSystem::PathSeparator(const string &path) { - if (StringUtil::StartsWith(path, "file:")) { - return "/"; - } else { - return "\\"; + auto opener = GetOpener(); + auto db = opener ? opener->TryGetDatabase() : nullptr; + if (!db) { + throw InvalidInputException("Cannot open \"%s\" through the external file cache without a database", file.path); } -} - -void FileSystem::SetWorkingDirectory(const string &path) { - auto unicode_path = WindowsUtil::UTF8ToUnicode(path.c_str()); - if (!SetCurrentDirectoryW(unicode_path.c_str())) { - throw IOException("Could not change working directory to \"%s\"", path); - } -} - -optional_idx FileSystem::GetAvailableMemory() { - ULONGLONG available_memory_kb; - if (GetPhysicallyInstalledSystemMemory(&available_memory_kb)) { - return MinValue(available_memory_kb * 1000, UINTPTR_MAX); - } - // fallback: try GlobalMemoryStatusEx - MEMORYSTATUSEX mem_state; - mem_state.dwLength = sizeof(MEMORYSTATUSEX); - - if (GlobalMemoryStatusEx(&mem_state)) { - return MinValue(mem_state.ullTotalPhys, UINTPTR_MAX); - } - return optional_idx(); -} - -optional_idx FileSystem::GetAvailableDiskSpace(const string &path) { - ULARGE_INTEGER available_bytes, total_bytes, free_bytes; - - auto unicode_path = WindowsUtil::UTF8ToUnicode(path.c_str()); - if (!GetDiskFreeSpaceExW(unicode_path.c_str(), &available_bytes, &total_bytes, &free_bytes)) { - return optional_idx(); - } - (void)total_bytes; - (void)free_bytes; - return NumericCast(available_bytes.QuadPart); -} - -string FileSystem::GetWorkingDirectory() { - idx_t count = GetCurrentDirectoryW(0, nullptr); - if (count == 0) { - throw IOException("Could not get working directory!"); - } - auto buffer = make_unsafe_uniq_array(count); - idx_t ret = GetCurrentDirectoryW(count, buffer.get()); - if (count != ret + 1) { - throw IOException("Could not get working directory!"); - } - return WindowsUtil::UnicodeToUTF8(buffer.get()); -} - -#endif - -optional_idx FileSystem::GetFileDescriptorLimit() { -#if !defined(_WIN32) && !defined(__EMSCRIPTEN__) - struct rlimit limit; - if (getrlimit(RLIMIT_NOFILE, &limit) != 0 || limit.rlim_cur == RLIM_INFINITY) { - return optional_idx(); - } - if (limit.rlim_cur >= NumericLimits::Maximum()) { - return optional_idx(); + auto caching_file_system = make_shared_ptr(*this, *db, flags.GetCachingMode()); + auto handle = caching_file_system->OpenFile(file, raw_flags, GetOpener()); + if (!handle) { + return nullptr; } - return optional_idx(static_cast(limit.rlim_cur)); -#else - return optional_idx(); -#endif -} - -idx_t FileSystem::GetFileDescriptorShare(idx_t file_descriptor_limit) { - return MaxValue(file_descriptor_limit / 8, 1); + return GetFileSystem().WrapOpenedFile(std::move(handle), file, flags, GetOpener()); } -string FileSystem::JoinPath(const string &a, const string &b) { - // A remote URL may carry a "?query" suffix (object version, requester-pays, an SSE-C key, ...). - // Appending a path segment after it would bury the query mid-path and corrupt both the query and - // the object path, so join onto the path without the query and keep the query at the very end. - auto scheme = a.find("://"); - if (scheme != string::npos) { - auto query = a.find('?', scheme + 3); - if (query != string::npos) { - return Path::FromString(a.substr(0, query)).Join(b).ToString() + a.substr(query); - } +unique_ptr FileSystem::MemoryMapFile(const OpenFileInfo &path, const FileOpenFlags &flags, + const MMapOptions &options) { + VerifyCanAccessFile(path.path); + if (IsDuckDBExtensionName(path.path)) { + VerifyCanAccessExtension(path.path, flags); } - return Path::FromString(a).Join(b).ToString(); + return FindFileSystem(path.path).MemoryMapFile(path, flags, options, GetOpener()); } -string FileSystem::ConvertSeparators(const string &path) { - auto separator_str = PathSeparator(path); - char separator = separator_str[0]; - if (separator == '/') { - // on unix-based systems we only accept / as a separator - return path; - } - // on windows-based systems we accept both - return StringUtil::Replace(path, "/", separator_str); +bool FileSystem::DirectoryExists(const string &directory) { + VerifyCanAccessDirectory(directory); + return FindFileSystem(directory).DirectoryExists(directory, GetOpener()); } -string FileSystem::ExtractName(const string &path) { - if (path.empty()) { - return string(); - } - auto normalized_path = ConvertSeparators(path); - auto sep = PathSeparator(path); - auto splits = StringUtil::Split(normalized_path, sep); - D_ASSERT(!splits.empty()); - return splits.back(); +void FileSystem::CreateDirectory(const string &directory) { + CreateDirectoryExtended(directory, {CreateDirectoryMode::SINGLE}); } -string FileSystem::ExtractBaseName(const string &path) { - if (path.empty()) { - return string(); +bool FileSystem::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options) { + if (options.mode != CreateDirectoryMode::RECURSIVE) { + VerifyCanAccessDirectory(directory); + return FindFileSystem(directory).CreateDirectoryExtended(directory, options, GetOpener()); } - auto vec = StringUtil::Split(ExtractName(path), "."); - D_ASSERT(!vec.empty()); - return vec[0]; -} - -string FileSystem::ExtractExtension(const string &path) { - if (path.empty()) { - return string(); + // access is checked for every ancestor: walk up to the first existing directory, then create downwards + auto parsed = Path::FromString(directory); + vector directories; + while (!parsed.GetPathSegments().empty() && !DirectoryExists(parsed.ToString())) { + directories.push_back(parsed.ToString()); + parsed = parsed.Parent(); } - auto vec = StringUtil::Split(ExtractName(path), "."); - if (vec.size() < 2) { - return string(); + if (parsed.GetPathSegments().empty() && !DirectoryExists(parsed.ToString())) { + directories.push_back(parsed.ToString()); } - return vec.back(); -} - -string FileSystem::GetHomeDirectory(optional_ptr opener) { - // read the home_directory setting first, if it is set - if (opener) { - Value result; - if (opener->TryGetCurrentSetting("home_directory", result)) { - if (!result.IsNull() && !result.ToString().empty()) { - return result.ToString(); - } + bool target_created = false; + for (auto riter = directories.rbegin(); riter != directories.rend(); ++riter) { + auto created = CreateDirectoryExtended(*riter, {CreateDirectoryMode::SINGLE}); + if (*riter == directories.front()) { + target_created = created; } } - // fallback to the default home directories for the specified system -#ifdef DUCKDB_WINDOWS - return FileSystem::GetEnvVariable("USERPROFILE"); -#else - return FileSystem::GetEnvVariable("HOME"); -#endif + return target_created; } -string FileSystem::GetHomeDirectory() { - return GetHomeDirectory(nullptr); +void FileSystem::CreateDirectoriesRecursive(const string &path) { + CreateDirectoryExtended(path, {CreateDirectoryMode::RECURSIVE}); } -// Helper function to handle file:/ URLs -static idx_t GetFileUrlOffset(const string &path) { - if (!StringUtil::StartsWith(path, "file:/")) { - return 0; - } - - // Url without host: file:/some/path - if (path[6] != '/') { -#ifdef _WIN32 - return 6; -#else - return 5; -#endif - } - - // Url with empty host: file:///some/path - if (path[7] == '/') { -#ifdef _WIN32 - return 8; -#else - return 7; -#endif - } - - // Url with localhost: file://localhost/some/path - if (path.compare(7, 10, "localhost/") == 0) { -#ifdef _WIN32 - return 17; -#else - return 16; -#endif - } - - // unknown file:/ url format - return 0; -} - -string FileSystem::ExpandPath(const string &path, optional_ptr opener) { - if (path.empty()) { - return path; - } - if (path[0] == '~') { - return GetHomeDirectory(opener) + path.substr(1); - } - // handle file URIs - auto file_offset = GetFileUrlOffset(path); - if (file_offset > 0) { - return path.substr(file_offset); - } - return path; +void FileSystem::RemoveDirectory(const string &directory) { + RemoveDirectoryExtended(directory, {RemoveDirectoryMode::RECURSIVE}); } -string FileSystem::ExpandPath(const string &path) { - return FileSystem::ExpandPath(path, nullptr); -} - -// LCOV_EXCL_START -unique_ptr FileSystem::OpenFileExtended(const OpenFileInfo &path, - FileOpenFlags flags, // NOLINT: virtual, overrides mutate flags - optional_ptr opener) { - throw NotImplementedException("%s: OpenFileExtended is not implemented!", GetName()); -} - -bool FileSystem::ListFilesExtended(const string &directory, const std::function &callback, - optional_ptr opener) { - throw NotImplementedException("%s: ListFilesExtended is not implemented!", GetName()); -} - -unique_ptr FileSystem::OpenFile(const string &path, FileOpenFlags flags, optional_ptr opener) { - if (SupportsOpenFileExtended()) { - return OpenFileExtended(OpenFileInfo(path), std::move(flags), opener); - } - throw NotImplementedException("%s: OpenFile is not implemented!", GetName()); +bool FileSystem::RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options) { + VerifyCanAccessDirectory(directory); + return FindFileSystem(directory).RemoveDirectoryExtended(directory, options, GetOpener()); } -unique_ptr FileSystem::OpenFile(const OpenFileInfo &file, const FileOpenFlags &flags, - optional_ptr opener) { - if (SupportsOpenFileExtended()) { - return OpenFileExtended(file, flags, opener); - } else { - return OpenFile(file.path, flags, opener); +void FileSystem::MoveFile(const string &source, const string &target) { + VerifyCanAccessFile(source); + VerifyCanAccessFile(target); + if (IsDuckDBExtensionName(target) && !IsDuckDBExtensionName(source)) { + throw PermissionException( + "File '%s' cannot be moved to '%s', files ending with '.duckdb_extension' are reserved for DuckDB " + "extensions, and these can only be installed through the INSTALL command, or moved if both are " + "extensions'", + source, target); } + FindFileSystem(source).MoveFile(source, target, GetOpener()); } -bool FileSystem::SupportsOpenFileExtended() const { - return false; +bool FileSystem::FileExists(const string &filename) { + VerifyCanAccessFile(filename); + return FindFileSystem(filename).FileExists(filename, GetOpener()); } -bool FileSystem::SupportsListFilesExtended() const { - return false; +optional FileSystem::GetStatsIfExists(const OpenFileInfo &file) { + VerifyCanAccessFile(file.path); + return FindFileSystem(file.path).GetStatsIfExists(file, GetOpener()); } -bool FileSystem::SupportsGlobExtended() const { - return false; +bool FileSystem::IsPipe(const string &filename) { + return FindFileSystem(filename).IsPipe(filename, GetOpener()); } -void FileSystem::Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) { - throw NotImplementedException("%s: Read (with location) is not implemented!", GetName()); +void FileSystem::RemoveFile(const string &filename) { + VerifyCanAccessFile(filename); + FindFileSystem(filename).RemoveFile(filename, GetOpener()); } -void FileSystem::Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) { - throw NotImplementedException("%s: Write (with location) is not implemented!", GetName()); +bool FileSystem::TryRemoveFile(const string &filename) { + VerifyCanAccessFile(filename); + return FindFileSystem(filename).TryRemoveFile(filename, GetOpener()); } -int64_t FileSystem::Read(FileHandle &handle, void *buffer, int64_t nr_bytes) { - throw NotImplementedException("%s: Read is not implemented!", GetName()); -} - -int64_t FileSystem::Write(FileHandle &handle, void *buffer, int64_t nr_bytes) { - throw NotImplementedException("%s: Write is not implemented!", GetName()); -} - -bool FileSystem::Trim(FileHandle &handle, idx_t offset_bytes, idx_t length_bytes) { - // This is not a required method. Derived FileSystems may optionally override/implement. - return false; -} - -int64_t FileSystem::GetFileSize(FileHandle &handle) { - throw NotImplementedException("%s: GetFileSize is not implemented!", GetName()); -} - -timestamp_t FileSystem::GetLastModifiedTime(FileHandle &handle) { - throw NotImplementedException("%s: GetLastModifiedTime is not implemented!", GetName()); -} - -string FileSystem::GetVersionTag(FileHandle &handle) { - // Used to check cache invalidation for httpfs files with an ETag in CachingFileSystem - return ""; -} - -optional FileSystem::GetCacheValidUntil(FileHandle &handle) { - return nullopt; -} - -FileType FileSystem::GetFileType(FileHandle &handle) { - return FileType::FILE_TYPE_INVALID; -} - -FileMetadata FileSystem::Stats(FileHandle &handle) { - FileMetadata metadata; - metadata.file_size = GetFileSize(handle); - metadata.last_modification_time = GetLastModifiedTime(handle); - metadata.file_type = GetFileType(handle); - metadata.version_tag = GetVersionTag(handle); - metadata.cache_valid_until = GetCacheValidUntil(handle); - return metadata; -} - -optional FileSystem::GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) { - auto handle = OpenFile(file, FileFlags::FILE_FLAGS_READ | FileFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS, opener); - if (!handle) { - return nullopt; - } - return Stats(*handle); -} - -void FileSystem::Truncate(FileHandle &handle, int64_t new_size) { - throw NotImplementedException("%s: Truncate is not implemented!", GetName()); -} - -bool FileSystem::DirectoryExists(const string &directory, optional_ptr opener) { - throw NotImplementedException("%s: DirectoryExists is not implemented!", GetName()); -} - -void FileSystem::CreateDirectory(const string &directory, optional_ptr opener) { - throw NotImplementedException("%s: CreateDirectory is not implemented!", GetName()); -} - -bool FileSystem::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener) { - switch (options.mode) { - case CreateDirectoryMode::SINGLE: - if (!DirectoryExists(directory, opener)) { - CreateDirectory(directory, opener); - } - return false; - case CreateDirectoryMode::RECURSIVE: { - auto parsed = Path::FromString(directory); - vector directories; - while (!parsed.GetPathSegments().empty() && !DirectoryExists(parsed.ToString(), opener)) { - directories.push_back(parsed.ToString()); - parsed = parsed.Parent(); - } - if (parsed.GetPathSegments().empty() && !DirectoryExists(parsed.ToString(), opener)) { - directories.push_back(parsed.ToString()); - } - - bool target_created = false; - for (auto riter = directories.rbegin(); riter != directories.rend(); ++riter) { - auto created = CreateDirectoryExtended(*riter, {CreateDirectoryMode::SINGLE}, opener); - if (*riter == directories.front()) { - target_created = created; - } - } - return target_created; - } - default: - throw InternalException("Unknown CreateDirectoryMode"); - } -} - -void FileSystem::CreateDirectoriesRecursive(const string &path, optional_ptr opener) { - CreateDirectoryExtended(path, {CreateDirectoryMode::RECURSIVE}, opener); -} - -void FileSystem::RemoveDirectory(const string &directory, optional_ptr opener) { - throw NotImplementedException("%s: RemoveDirectory is not implemented!", GetName()); -} - -bool FileSystem::RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener) { - switch (options.mode) { - case RemoveDirectoryMode::SINGLE: - return false; - case RemoveDirectoryMode::RECURSIVE: - RemoveDirectory(directory, opener); - return false; - default: - throw InternalException("Unknown RemoveDirectoryMode"); - } -} - -bool FileSystem::IsDirectory(const OpenFileInfo &info) { - if (!info.extended_info) { - return false; - } - string type; - if (!info.extended_info->TryGetOption("type", type)) { - return false; - } - return type == "directory"; -} - -bool FileSystem::ListFiles(const string &directory, const std::function &callback, - FileOpener *opener) { - if (SupportsListFilesExtended()) { - return ListFilesExtended( - directory, - [&](const OpenFileInfo &info) { - bool is_dir = IsDirectory(info); - callback(info.path, is_dir); - }, - opener); - } - throw NotImplementedException("%s: ListFiles is not implemented!", GetName()); -} - -bool FileSystem::ListFiles(const string &directory, const std::function &callback, - optional_ptr opener) { - if (SupportsListFilesExtended()) { - return ListFilesExtended(directory, callback, opener); - } else { - return ListFiles( - directory, - [&](const string &path, bool is_dir) { - OpenFileInfo info(path); - if (is_dir) { - info.extended_info = make_shared_ptr(); - info.extended_info->options["type"] = "directory"; - } - callback(info); - }, - opener.get()); - } -} - -void FileSystem::MoveFile(const string &source, const string &target, optional_ptr opener) { - throw NotImplementedException("%s: MoveFile is not implemented!", GetName()); -} - -bool FileSystem::FileExists(const string &filename, optional_ptr opener) { - throw NotImplementedException("%s: FileExists is not implemented!", GetName()); -} - -bool FileSystem::IsPipe(const string &filename, optional_ptr opener) { - return false; -} - -void FileSystem::RemoveFile(const string &filename, optional_ptr opener) { - throw NotImplementedException("%s: RemoveFile is not implemented!", GetName()); -} - -bool FileSystem::TryRemoveFile(const string &filename, optional_ptr opener) { - if (FileExists(filename, opener)) { - RemoveFile(filename, opener); - return true; - } - return false; -} - -void FileSystem::RemoveFiles(const vector &filenames, optional_ptr opener) { +void FileSystem::RemoveFiles(const vector &filenames) { + reference_map_t> files_by_fs; for (const auto &filename : filenames) { - TryRemoveFile(filename, opener); + VerifyCanAccessFile(filename); + files_by_fs[FindFileSystem(filename)].push_back(filename); } -} - -void FileSystem::FileSync(FileHandle &handle) { - throw NotImplementedException("%s: FileSync is not implemented!", GetName()); -} - -void FileSystem::AbortFileWrite(FileHandle &handle) { - handle.Close(); -} - -bool FileSystem::HasGlob(const string &str) { - for (idx_t i = 0; i < str.size(); i++) { - switch (str[i]) { - case '*': - case '?': - case '[': - return true; - default: - break; - } + for (auto &entry : files_by_fs) { + entry.first.get().RemoveFiles(entry.second, GetOpener()); } - return false; } -vector FileSystem::Glob(const string &path, FileOpener *opener) { - if (SupportsGlobExtended()) { - auto result = GlobFilesExtended(path, FileGlobOptions::ALLOW_EMPTY, opener); - return result->GetAllFiles(); - } - throw NotImplementedException("%s: Glob is not implemented!", GetName()); +bool FileSystem::ListFiles(const string &directory, const std::function &callback) { + VerifyCanAccessDirectory(directory); + return FindFileSystem(directory).ListFiles(directory, callback, GetOpener().get()); } -unique_ptr FileSystem::Glob(const string &path, const FileGlobInput &input, - optional_ptr opener) { - if (!SupportsGlobExtended()) { - auto result = Glob(path, opener.get()); - return make_uniq(std::move(result)); - } else { - return GlobFilesExtended(path, input, opener); - } +bool FileSystem::ListFiles(const string &directory, const std::function &callback) { + VerifyCanAccessDirectory(directory); + return FindFileSystem(directory).ListFiles(directory, callback, GetOpener()); } -unique_ptr FileSystem::GlobFilesExtended(const string &path, const FileGlobInput &input, - optional_ptr opener) { - throw NotImplementedException("%s: GlobFilesExtended is not implemented!", GetName()); +vector FileSystem::Glob(const string &path) { + VerifyCanAccessFile(path); + return FindFileSystem(path).Glob(path, GetOpener().get()); } -bool FileSystem::CanHandleFile(const string &fpath) { - throw NotImplementedException("%s: CanHandleFile is not implemented!", GetName()); +unique_ptr FileSystem::Glob(const string &path, const FileGlobInput &input) { + VerifyCanAccessFile(path); + return FindFileSystem(path).Glob(path, input, GetOpener()); } unique_ptr FileSystem::GlobFileList(const string &pattern, const FileGlobInput &input) { - auto result = GlobFilesExtended(pattern, input); + auto result = Glob(pattern, input); if (result->IsEmpty()) { - if (input.behavior == FileGlobOptions::FALLBACK_GLOB && !HasGlob(pattern)) { + if (input.behavior == FileGlobOptions::FALLBACK_GLOB && !FileSystem::HasGlob(pattern)) { // if we have no glob in the pattern and we have an extension, we try to glob if (input.extension.empty()) { throw InternalException("FALLBACK_GLOB requires an extension to be specified"); @@ -753,293 +199,66 @@ unique_ptr FileSystem::GlobFileList(const string &pattern, const } vector FileSystem::GlobFiles(const string &pattern, const FileGlobInput &input) { - auto file_list = GlobFileList(pattern, input); - return file_list->GetAllFiles(); -} - -void FileSystem::Seek(FileHandle &handle, idx_t location) { - throw NotImplementedException("%s: Seek is not implemented!", GetName()); -} - -void FileSystem::Reset(FileHandle &handle) { - handle.Seek(0); -} - -idx_t FileSystem::SeekPosition(FileHandle &handle) { - throw NotImplementedException("%s: SeekPosition is not implemented!", GetName()); -} - -bool FileSystem::CanSeek() { - throw NotImplementedException("%s: CanSeek is not implemented!", GetName()); -} - -bool FileSystem::IsManuallySet() { - return false; -} - -FileWriteMode FileSystem::GetWriteMode(FileHandle &handle) { - return FileWriteMode::SEQUENTIAL; -} - -unique_ptr FileSystem::OpenCompressedFile(QueryContext context, unique_ptr handle, bool write) { - throw NotImplementedException("%s: OpenCompressedFile is not implemented!", GetName()); -} - -bool FileSystem::IsLocalFileSystem() const { - return false; -} - -bool FileSystem::OnDiskFile(FileHandle &handle) { - throw NotImplementedException("%s: OnDiskFile is not implemented!", GetName()); -} -// LCOV_EXCL_STOP - -bool FileSystem::TryGetNetworkThroughput(FileHandle &handle, NetworkThroughputEstimate &result) { - return false; -} - -FileHandle::FileHandle(FileSystem &file_system, string path_p, FileOpenFlags flags_p) - : file_system(file_system), path(std::move(path_p)), flags(std::move(flags_p)) { -} - -FileHandle::~FileHandle() { -} - -int64_t FileHandle::Read(void *buffer, idx_t nr_bytes) { - return file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes)); -} - -static optional_ptr GetTrackingProfiler(bool track_io, const QueryContext &context) { - if (!track_io || !context.Valid()) { - return nullptr; - } - return context.GetContext()->TryGetQueryProfiler(); + return GlobFileList(pattern, input)->GetAllFiles(); } -int64_t FileHandle::Read(QueryContext context, void *buffer, idx_t nr_bytes) { - auto profiler = GetTrackingProfiler(track_io, context); - const bool track = profiler != nullptr; - const auto start = track ? TimePoint::Tick() : TimePoint(); - // A sequential read can return fewer bytes than requested (e.g. at EOF), so track the bytes - // actually read rather than the requested amount. - auto bytes_read = file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes)); - if (track) { - const auto elapsed_us = NumericCast(start.ElapsedMicros()); - profiler->TrackBytesRead(UnsafeNumericCast(bytes_read), elapsed_us); - } - - return bytes_read; +string FileSystem::CanonicalizePath(const string &path) { + return FindFileSystem(path).CanonicalizePath(path, GetOpener()); } -bool FileHandle::Trim(idx_t offset_bytes, idx_t length_bytes) { - return file_system.Trim(*this, offset_bytes, length_bytes); +string FileSystem::GetHomeDirectory() { + return FileSystem::GetHomeDirectory(GetOpener()); } -int64_t FileHandle::Write(void *buffer, idx_t nr_bytes) { - return file_system.Write(*this, buffer, UnsafeNumericCast(nr_bytes)); +string FileSystem::ExpandPath(const string &path) { + return FileSystem::ExpandPath(path, GetOpener()); } -int64_t FileHandle::Write(QueryContext context, void *buffer, idx_t nr_bytes) { - auto profiler = GetTrackingProfiler(track_io, context); - const bool track = profiler != nullptr; - const auto start = track ? TimePoint::Tick() : TimePoint(); - auto bytes_written = file_system.Write(*this, buffer, UnsafeNumericCast(nr_bytes)); - if (bytes_written > 0 && track) { - const auto elapsed_us = NumericCast(start.ElapsedMicros()); - profiler->TrackBytesWritten(UnsafeNumericCast(bytes_written), elapsed_us); +BaseFileSystem &FileSystem::FindFileSystem(const string &path) { + auto fixed_fs = GetFixedFileSystem(); + if (fixed_fs) { + return *fixed_fs; } - - return bytes_written; -} - -void FileHandle::Read(void *buffer, idx_t nr_bytes, idx_t location) { - file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes), location); + return GetFileSystem().FindFileSystem(path, GetOpener()); } -void FileHandle::Read(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location) { - auto profiler = GetTrackingProfiler(track_io, context); - const bool track = profiler != nullptr; - const auto start = track ? TimePoint::Tick() : TimePoint(); - file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes), location); - if (track) { - const auto elapsed_us = NumericCast(start.ElapsedMicros()); - profiler->TrackBytesRead(nr_bytes, elapsed_us); - } +string FileSystem::JoinPath(const string &a, const string &path) { + // BaseFileSystem::JoinPath is not virtual, so any file system joins the same way + auto fixed_fs = GetFixedFileSystem(); + auto &fs = fixed_fs ? *fixed_fs : GetFileSystem().GetDefaultFileSystem(); + return fs.JoinPath(a, path); } -void FileHandle::Write(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location) { - auto profiler = GetTrackingProfiler(track_io, context); - const bool track = profiler != nullptr; - const auto start = track ? TimePoint::Tick() : TimePoint(); - file_system.Write(*this, buffer, UnsafeNumericCast(nr_bytes), location); - if (track) { - const auto elapsed_us = NumericCast(start.ElapsedMicros()); - profiler->TrackBytesWritten(nr_bytes, elapsed_us); +BaseFileSystem &FileSystem::PathFileSystem(const string &path) const { + auto fixed_fs = GetFixedFileSystem(); + if (fixed_fs) { + return *fixed_fs; } + return GetFileSystem().FindFileSystem(path, nullptr); } -void FileHandle::Seek(idx_t location) { - file_system.Seek(*this, location); -} - -void FileHandle::Reset() { - file_system.Reset(*this); -} - -idx_t FileHandle::SeekPosition() { - return file_system.SeekPosition(*this); -} - -bool FileHandle::CanSeek() { - return file_system.CanSeek(); -} - -FileWriteMode FileHandle::GetWriteMode() { - return file_system.GetWriteMode(*this); -} - -FileCompressionType FileHandle::GetFileCompressionType() { - return FileCompressionType::UNCOMPRESSED; -} - -bool FileHandle::IsPipe() { - return file_system.IsPipe(path); -} - -string FileHandle::ReadLine() { - string result; - char buffer[1]; - while (true) { - auto tuples_read = UnsafeNumericCast(Read(buffer, 1)); - if (tuples_read == 0 || buffer[0] == '\n') { - return result; - } - if (buffer[0] != '\r') { - result += buffer[0]; - } - } -} - -string FileHandle::ReadLine(QueryContext context) { - string result; - char buffer[1]; - while (true) { - auto tuples_read = UnsafeNumericCast(Read(context, buffer, 1)); - if (tuples_read == 0 || buffer[0] == '\n') { - return result; - } - if (buffer[0] != '\r') { - result += buffer[0]; - } - } -} - -bool FileHandle::OnDiskFile() { - return file_system.OnDiskFile(*this); -} - -bool FileHandle::TryGetNetworkThroughput(NetworkThroughputEstimate &result) { - return file_system.TryGetNetworkThroughput(*this, result); -} - -idx_t FileHandle::GetFileSize() { - return NumericCast(file_system.GetFileSize(*this)); -} - -void FileHandle::Sync() { - file_system.FileSync(*this); -} - -void FileHandle::Truncate(int64_t new_size) { - file_system.Truncate(*this, new_size); -} - -void FileHandle::AbortWrite() { - file_system.AbortFileWrite(*this); -} - -FileType FileHandle::GetType() { - return file_system.GetFileType(*this); -} - -FileMetadata FileHandle::Stats() { - return file_system.Stats(*this); -} - -void FileHandle::TryAddLogger(FileOpener &opener) { - if (flags.DisableLogging()) { +void FileSystem::VerifyCanAccessFileInternal(const string &path, FileType type) { + auto opener = GetOpener(); + if (!opener) { return; } - - auto &context = opener.TryGetContext(); - if (context.IsClient() && context.GetLogger().ShouldLog(FileSystemLogType::NAME, FileSystemLogType::LEVEL)) { - logger = context.GetLoggerPtr(); + auto db = opener->TryGetDatabase(); + if (!db) { return; } - - auto database = opener.TryGetDatabase(); - if (database && Logger::Get(*database).ShouldLog(FileSystemLogType::NAME, FileSystemLogType::LEVEL)) { - logger = database->GetLogManager().GlobalLoggerReference(); + auto &config = db->config; + if (!config.CanAccessFile(path, type, opener)) { + throw PermissionException("Cannot access %s \"%s\" - file system operations are disabled by configuration", + type == FileType::FILE_TYPE_DIR ? "directory" : "file", path); } } -idx_t FileHandle::GetProgress() { - throw NotImplementedException("GetProgress is not implemented for this file handle"); +void FileSystem::VerifyCanAccessFile(const string &path) { + VerifyCanAccessFileInternal(path, FileType::FILE_TYPE_REGULAR); } -bool FileSystem::IsRemoteFile(const string &path) { - string extension = ""; - return IsRemoteFile(path, extension); -} - -bool FileSystem::IsRemoteFile(const string &path, string &extension) { - for (const auto &entry : EXTENSION_FILE_PREFIXES) { - if (StringUtil::StartsWith(path, entry.name)) { - extension = entry.extension; - return true; - } - } - return false; -} - -string FileSystem::CanonicalizePath(const string &path_p, optional_ptr opener) { - // TODO: @benfleis - integrate this properly with Path (needs additional work) - if (IsRemoteFile(path_p) || !Path::FromString(path_p).IsLocal()) { - // don't canonicalize remote paths - return path_p; - } - auto path_sep = PathSeparator(path_p); - auto elements = StringUtil::Split(path_p, path_sep); - - deque path_stack; - string result; - for (idx_t i = 0; i < elements.size(); i++) { - if (elements[i].empty() || elements[i] == ".") { - // we ignore empty and `.` - continue; - } - if (elements[i] == "..") { - // .. pops from stack if possible, if already at root its ignored - if (!path_stack.empty()) { - path_stack.pop_back(); - } - } else { - path_stack.push_back(elements[i]); - } - } - // we lost the leading / in the split/loop so lets put it back - if (path_p[0] == '/') { - result = "/"; - } - while (!path_stack.empty()) { - result += path_stack.front(); - path_stack.pop_front(); - if (!path_stack.empty()) { - result += path_sep; - } - } - - return result; +void FileSystem::VerifyCanAccessDirectory(const string &path) { + VerifyCanAccessFileInternal(path, FileType::FILE_TYPE_DIR); } } // namespace duckdb diff --git a/src/duckdb/src/common/local_file_system.cpp b/src/duckdb/src/common/local_file_system.cpp index f6b973a7e..d5ac19431 100644 --- a/src/duckdb/src/common/local_file_system.cpp +++ b/src/duckdb/src/common/local_file_system.cpp @@ -66,7 +66,7 @@ namespace duckdb { #ifndef _WIN32 bool LocalFileSystem::FileExists(const string &filename, optional_ptr opener) { if (!filename.empty()) { - auto normalized_file = ExpandPath(filename, opener); + auto normalized_file = FileSystem::ExpandPath(filename, opener); struct stat status; if (stat(normalized_file.c_str(), &status) == 0 && S_ISREG(status.st_mode)) { return true; @@ -78,7 +78,7 @@ bool LocalFileSystem::FileExists(const string &filename, optional_ptr opener) { if (!filename.empty()) { - auto normalized_file = ExpandPath(filename, opener); + auto normalized_file = FileSystem::ExpandPath(filename, opener); struct stat status; if (stat(normalized_file.c_str(), &status) == 0 && (S_ISFIFO(status.st_mode) || S_ISCHR(status.st_mode))) { return true; @@ -127,9 +127,9 @@ static std::wstring ConvertPathToNormalizedAbsolute(const std::wstring &path) { return std::wstring(buf.data(), written); } -static std::wstring NormalizePathAndConvertToUnicode(FileSystem &fs, const string &path, +static std::wstring NormalizePathAndConvertToUnicode(BaseFileSystem &fs, const string &path, optional_ptr opener) { - string normalized_path = fs.ExpandPath(path, opener); + string normalized_path = FileSystem::ExpandPath(path, opener); std::wstring unicode_path = ConvertPathToUnicode(normalized_path); // We need to get absolute path to check the length. Normalizing it (removing "." and "..", @@ -210,7 +210,8 @@ static void ApplyLocalFileSystemDelay(optional_ptr opener) { struct UnixFileHandle : public FileHandle { public: - UnixFileHandle(FileSystem &file_system, string path, int fd, FileOpenFlags flags, optional_ptr db) + UnixFileHandle(BaseFileSystem &file_system, string path, int fd, FileOpenFlags flags, + optional_ptr db) : FileHandle(file_system, std::move(path), std::move(flags)), fd(fd), db(db) { } ~UnixFileHandle() override { @@ -297,7 +298,7 @@ static FileMetadata StatsInternal(int fd, const string &path) { // Apply a fcntl advisory lock per flags.Lock(); throws (and closes fd) on failure. Shared // by OpenFile and MemoryMapFile. -static void TryAcquireFileLock(FileSystem &fs, int fd, const string &path, FileOpenFlags flags) { +static void TryAcquireFileLock(BaseFileSystem &fs, int fd, const string &path, FileOpenFlags flags) { if (flags.Lock() == FileLockType::NO_LOCK) { return; } @@ -379,7 +380,7 @@ bool LocalFileSystem::IsPrivateFile(const string &path_p, FileOpener *opener) { unique_ptr LocalFileSystem::OpenFile(const string &path_p, FileOpenFlags flags, optional_ptr opener) { - auto path = ExpandPath(path_p, opener); + auto path = FileSystem::ExpandPath(path_p, opener); if (flags.Compression() != FileCompressionType::UNCOMPRESSED) { throw NotImplementedException("Unsupported compression type for default file system"); } @@ -638,7 +639,7 @@ optional LocalFileSystem::GetStatsIfExists(const OpenFileInfo &fil if (path_p.empty()) { return nullopt; } - auto path = ExpandPath(path_p, opener); + auto path = FileSystem::ExpandPath(path_p, opener); struct stat status; if (stat(path.c_str(), &status) != 0) { auto retained_errno = errno; @@ -665,7 +666,7 @@ bool LocalFileSystem::DirectoryExists(const string &directory, optional_ptr opener) { if (options.mode == CreateDirectoryMode::RECURSIVE) { - return FileSystem::CreateDirectoryExtended(directory, options, opener); + return BaseFileSystem::CreateDirectoryExtended(directory, options, opener); } if (options.mode != CreateDirectoryMode::SINGLE) { throw InternalException("Unknown CreateDirectoryMode"); } ApplyLocalFileSystemDelay(opener); - auto normalized_dir = ExpandPath(directory, opener); + auto normalized_dir = FileSystem::ExpandPath(directory, opener); if (mkdir(normalized_dir.c_str(), 0755) == 0) { return true; } @@ -754,13 +755,13 @@ void LocalFileSystem::RemoveDirectory(const string &directory, optional_ptr opener) { if (options.mode == RemoveDirectoryMode::RECURSIVE) { - auto normalized_dir = ExpandPath(directory, opener); + auto normalized_dir = FileSystem::ExpandPath(directory, opener); return RemoveDirectoryRecursive(normalized_dir.c_str()) == 0; } if (options.mode != RemoveDirectoryMode::SINGLE) { throw InternalException("Unknown RemoveDirectoryMode"); } - auto normalized_dir = ExpandPath(directory, opener); + auto normalized_dir = FileSystem::ExpandPath(directory, opener); if (rmdir(normalized_dir.c_str()) == 0) { return true; } @@ -772,7 +773,7 @@ bool LocalFileSystem::RemoveDirectoryExtended(const string &directory, const Rem } void LocalFileSystem::RemoveFile(const string &filename, optional_ptr opener) { - auto normalized_file = ExpandPath(filename, opener); + auto normalized_file = FileSystem::ExpandPath(filename, opener); if (std::remove(normalized_file.c_str()) != 0) { throw IOException({{"errno", std::to_string(errno)}}, "Could not remove file \"%s\": %s", filename, strerror(errno)); @@ -782,7 +783,7 @@ void LocalFileSystem::RemoveFile(const string &filename, optional_ptr &callback, optional_ptr opener) { - auto normalized_dir = ExpandPath(directory, opener); + auto normalized_dir = FileSystem::ExpandPath(directory, opener); auto dir = opendir(normalized_dir.c_str()); if (!dir) { return false; @@ -864,8 +865,8 @@ void LocalFileSystem::FileSync(FileHandle &handle) { } void LocalFileSystem::MoveFile(const string &source, const string &target, optional_ptr opener) { - auto normalized_source = ExpandPath(source, opener); - auto normalized_target = ExpandPath(target, opener); + auto normalized_source = FileSystem::ExpandPath(source, opener); + auto normalized_target = FileSystem::ExpandPath(target, opener); //! FIXME: rename does not guarantee atomicity or overwriting target file if it exists if (rename(normalized_source.c_str(), normalized_target.c_str()) != 0) { throw IOException({{"errno", to_string(errno)}}, "Could not rename file \"%s\" to \"%s\": %s", source, target, @@ -933,12 +934,12 @@ bool LocalFileSystem::PathStartsWithDrive(const string &path) { } bool LocalFileSystem::IsPathAbsolute(const string &path) { - return FileSystem::IsPathAbsolute(path); + return BaseFileSystem::IsPathAbsolute(path); } string LocalFileSystem::MakePathAbsolute(const string &path_p, optional_ptr opener) { - auto parsed = Path::FromString(ExpandPath(path_p, opener)); - return (parsed.IsAbsolute() ? parsed : Path::FromString(GetWorkingDirectory()).Join(parsed)).ToString(); + auto parsed = Path::FromString(FileSystem::ExpandPath(path_p, opener)); + return (parsed.IsAbsolute() ? parsed : Path::FromString(FileSystem::GetWorkingDirectory()).Join(parsed)).ToString(); } //===----------------------------------------------------------------------===// @@ -1006,7 +1007,7 @@ void UnixMemoryMappedFile::Close() { unique_ptr LocalFileSystem::MemoryMapFile(const OpenFileInfo &path_info, FileOpenFlags flags, const MMapOptions &options, optional_ptr opener) { - auto path = ExpandPath(path_info.path, opener); + auto path = FileSystem::ExpandPath(path_info.path, opener); flags.Verify(); bool open_read = flags.OpenForReading(); @@ -1191,7 +1192,7 @@ static FileMetadata StatsFromDirInfo(const FILE_ID_BOTH_DIR_INFO &entry) { struct WindowsFileHandle : public FileHandle { public: - WindowsFileHandle(FileSystem &file_system, string path, HANDLE fd, FileOpenFlags flags, + WindowsFileHandle(BaseFileSystem &file_system, string path, HANDLE fd, FileOpenFlags flags, optional_ptr db) : FileHandle(file_system, path, flags), position(0), fd(fd), db(db) { } @@ -1522,7 +1523,7 @@ void LocalFileSystem::CreateDirectoriesRecursive(const string &path, optional_pt bool LocalFileSystem::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, optional_ptr opener) { if (options.mode == CreateDirectoryMode::RECURSIVE) { - return FileSystem::CreateDirectoryExtended(directory, options, opener); + return BaseFileSystem::CreateDirectoryExtended(directory, options, opener); } if (options.mode != CreateDirectoryMode::SINGLE) { throw InternalException("Unknown CreateDirectoryMode"); @@ -1544,7 +1545,7 @@ bool LocalFileSystem::CreateDirectoryExtended(const string &directory, const Cre throw IOException("Failed to create directory \"%s\": %s", abs_path, error); } -static void DeleteDirectoryRecursive(FileSystem &fs, string directory, optional_ptr opener) { +static void DeleteDirectoryRecursive(BaseFileSystem &fs, string directory, optional_ptr opener) { fs.ListFiles( directory, [&](const string &fname, bool is_directory) { @@ -1807,7 +1808,7 @@ bool LocalFileSystem::PathStartsWithDrive(const string &path) { } bool LocalFileSystem::IsPathAbsolute(const string &path) { - if (FileSystem::IsPathAbsolute(path)) { + if (BaseFileSystem::IsPathAbsolute(path)) { return true; } // check if this is a drive letter (e.g. C:) @@ -1818,14 +1819,14 @@ bool LocalFileSystem::IsPathAbsolute(const string &path) { } string LocalFileSystem::MakePathAbsolute(const string &path_p, optional_ptr opener) { - auto path = ExpandPath(path_p, opener); + auto path = FileSystem::ExpandPath(path_p, opener); auto parsed = Path::FromString(path); if (parsed.IsAbsolute()) { // already absolute - nothing to do return parsed.ToString(); } - auto parsed_wd = Path::FromString(GetWorkingDirectory()); + auto parsed_wd = Path::FromString(FileSystem::GetWorkingDirectory()); if (parsed.HasDrive() && parsed_wd.GetDriveChar() != parsed.GetDriveChar()) { // this is relative path "C:", and this is not the drive we are on right now // (referencing D: while in $PWD in C:); In this case, default as if PWD is @@ -1906,7 +1907,7 @@ void WindowsMemoryMappedFile::Close() { unique_ptr LocalFileSystem::MemoryMapFile(const OpenFileInfo &path_info, FileOpenFlags flags, const MMapOptions &options, optional_ptr opener) { - auto path = ExpandPath(path_info.path, opener); + auto path = FileSystem::ExpandPath(path_info.path, opener); flags.Verify(); bool open_read = flags.OpenForReading(); @@ -2019,7 +2020,7 @@ void LocalFileSystem::AbortFileWrite(FileHandle &handle) { auto path = handle.GetPath(); handle.Close(); if (remove_path) { - TryRemoveFile(path); + TryRemoveFile(path, nullptr); } } @@ -2066,7 +2067,7 @@ string LocalFileSystem::CanonicalizePath(const string &input, optional_ptr LocalFileSystem::FetchFileWithoutGlob(const string &path, o } struct PathSplit { - PathSplit(LocalFileSystem &fs, string path_p) : path(std::move(path_p)), has_glob(fs.HasGlob(path)) { + PathSplit(LocalFileSystem &fs, string path_p) : path(std::move(path_p)), has_glob(FileSystem::HasGlob(path)) { } string path; @@ -2240,9 +2241,10 @@ struct ExpandDirectory { } }; -static void CrawlDirectoryLevel(FileSystem &fs, const string &path, optional_ptr> files, +static void CrawlDirectoryLevel(LocalFileSystem &fs, optional_ptr opener, const string &path, + optional_ptr> files, std::priority_queue &directories, idx_t split_index) { - fs.ListFiles(path, [&](OpenFileInfo &info) { + auto callback = [&](OpenFileInfo &info) { info.path = fs.JoinPath(path, info.path); if (IsSymbolicLink(info.path)) { return; @@ -2253,12 +2255,13 @@ static void CrawlDirectoryLevel(FileSystem &fs, const string &path, optional_ptr } else if (files) { files->push_back(std::move(info)); } - }); + }; + fs.ListFiles(path, callback, opener); } -static void GlobFilesInternal(FileSystem &fs, const string &path, const string &glob, bool match_directory, - vector &result) { - fs.ListFiles(path, [&](OpenFileInfo &info) { +static void GlobFilesInternal(LocalFileSystem &fs, optional_ptr opener, const string &path, + const string &glob, bool match_directory, vector &result) { + auto callback = [&](OpenFileInfo &info) { bool is_directory = FileSystem::IsDirectory(info); if (is_directory != match_directory) { return; @@ -2267,7 +2270,8 @@ static void GlobFilesInternal(FileSystem &fs, const string &path, const string & info.path = fs.JoinPath(path, info.path); result.push_back(std::move(info)); } - }); + }; + fs.ListFiles(path, callback, opener); } struct LocalGlobResult : public LazyMultiFileList { @@ -2289,7 +2293,7 @@ struct LocalGlobResult : public LazyMultiFileList { LocalGlobResult::LocalGlobResult(LocalFileSystem &fs, const string &path_p, FileGlobOptions options_p, optional_ptr opener) - : LazyMultiFileList(FileOpener::TryGetContext(opener)), fs(fs), path(fs.ExpandPath(path_p, opener)), + : LazyMultiFileList(FileOpener::TryGetContext(opener)), fs(fs), path(FileSystem::ExpandPath(path_p, opener)), opener(opener) { if (path.empty()) { finished = true; @@ -2313,12 +2317,12 @@ LocalGlobResult::LocalGlobResult(LocalFileSystem &fs, const string &path_p, File } if (!splits.empty() && splits[0].path == "~") { // starts with home directory - auto home_directory = fs.GetHomeDirectory(opener); + auto home_directory = FileSystem::GetHomeDirectory(opener); if (!home_directory.empty()) { absolute_path = true; splits[0].path = home_directory; D_ASSERT(path[0] == '~'); - if (!fs.HasGlob(path)) { + if (!FileSystem::HasGlob(path)) { expanded_files = fs.FetchFileWithoutGlob(home_directory + path.substr(1), opener, absolute_path); finished = true; return; @@ -2326,7 +2330,7 @@ LocalGlobResult::LocalGlobResult(LocalFileSystem &fs, const string &path_p, File } } // Check if the path has a glob at all - if (!fs.HasGlob(path)) { + if (!FileSystem::HasGlob(path)) { // no glob: return only the file (if it exists or is a pipe) expanded_files = fs.FetchFileWithoutGlob(path, opener, absolute_path); finished = true; @@ -2410,23 +2414,23 @@ bool LocalGlobResult::ExpandNextPath() const { if (is_last_component) { // the crawl is the last component - we are looking for files in this directory // any directories we encounter are added to the expand directories - CrawlDirectoryLevel(fs, current_path, expanded_files, expand_directories, split_index); + CrawlDirectoryLevel(fs, opener, current_path, expanded_files, expand_directories, split_index); } else { // not the last crawl // ** also matches the current directory (i.e. dir/**/file.parquet also matches dir/file.parquet) expand_directories.emplace(current_path, split_index + 1); // now crawl the contents of this directory - but don't add any files we find - CrawlDirectoryLevel(fs, current_path, nullptr, expand_directories, split_index); + CrawlDirectoryLevel(fs, opener, current_path, nullptr, expand_directories, split_index); } } else { // glob this directory according to the next component if (is_last_component) { // last component - match files and place them in the result - GlobFilesInternal(fs, current_path, next_component, false, expanded_files); + GlobFilesInternal(fs, opener, current_path, next_component, false, expanded_files); } else { // not the last component - match directories and add to expansion list vector child_directories; - GlobFilesInternal(fs, current_path, next_component, true, child_directories); + GlobFilesInternal(fs, opener, current_path, next_component, true, child_directories); for (auto &file : child_directories) { expand_directories.emplace(std::move(file.path), split_index + 1); } diff --git a/src/duckdb/src/common/memory_mapped_file.cpp b/src/duckdb/src/common/memory_mapped_file.cpp index 6c0b7456d..24f2ebf1a 100644 --- a/src/duckdb/src/common/memory_mapped_file.cpp +++ b/src/duckdb/src/common/memory_mapped_file.cpp @@ -1,7 +1,7 @@ #include "duckdb/common/memory_mapped_file.hpp" #include "duckdb/common/exception.hpp" -#include "duckdb/common/file_system.hpp" +#include "duckdb/common/base_file_system.hpp" namespace duckdb { @@ -32,9 +32,10 @@ data_ptr_t MemoryMappedFile::GetDataMutable(idx_t location, idx_t nr_bytes) { return data + location; } -unique_ptr FileSystem::MemoryMapFile(const OpenFileInfo &path, - FileOpenFlags flags, // NOLINT: signature fixed by virtual API - const MMapOptions &options, optional_ptr opener) { +unique_ptr +BaseFileSystem::MemoryMapFile(const OpenFileInfo &path, + FileOpenFlags flags, // NOLINT: signature fixed by virtual API + const MMapOptions &options, optional_ptr opener) { throw NotImplementedException("Memory-mapped file access is not supported by this file system (%s) for path \"%s\"", GetName(), path.path); } diff --git a/src/duckdb/src/common/opener_file_system.cpp b/src/duckdb/src/common/opener_file_system.cpp deleted file mode 100644 index 7baec37f4..000000000 --- a/src/duckdb/src/common/opener_file_system.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include "duckdb/common/opener_file_system.hpp" -#include "duckdb/common/compressed_file_system.hpp" -#include "duckdb/common/multi_file/multi_file_list.hpp" -#include "duckdb/common/file_opener.hpp" -#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 { - -unique_ptr OpenerFileSystem::MemoryMapFile(const OpenFileInfo &path, FileOpenFlags flags, - const MMapOptions &options, - optional_ptr opener) { - VerifyNoOpener(opener); - VerifyCanAccessFile(path.path); - if (IsDuckDBExtensionName(path.path)) { - VerifyCanAccessExtension(path.path, flags); - } - 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 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) { - if (opener) { - throw InternalException("OpenerFileSystem cannot take an opener - the opener is pushed automatically"); - } -} -void OpenerFileSystem::VerifyCanAccessFileInternal(const string &path, FileType type) { - auto opener = GetOpener(); - if (!opener) { - return; - } - auto db = opener->TryGetDatabase(); - if (!db) { - return; - } - auto &config = db->config; - if (!config.CanAccessFile(path, type, opener)) { - throw PermissionException("Cannot access %s \"%s\" - file system operations are disabled by configuration", - type == FileType::FILE_TYPE_DIR ? "directory" : "file", path); - } -} - -void OpenerFileSystem::VerifyCanAccessFile(const string &path) { - VerifyCanAccessFileInternal(path, FileType::FILE_TYPE_REGULAR); -} - -void OpenerFileSystem::VerifyCanAccessDirectory(const string &path) { - VerifyCanAccessFileInternal(path, FileType::FILE_TYPE_DIR); -} - -} // namespace duckdb diff --git a/src/duckdb/src/common/operator/cast_operators.cpp b/src/duckdb/src/common/operator/cast_operators.cpp index 21c9dcf19..2b1b05308 100644 --- a/src/duckdb/src/common/operator/cast_operators.cpp +++ b/src/duckdb/src/common/operator/cast_operators.cpp @@ -27,7 +27,7 @@ #include "fast_float/fast_float.h" #include "duckdb/common/types/bit.hpp" #include "duckdb/common/types/bignum.hpp" -#include "duckdb/common/bignum_limbs.hpp" +#include "duckdb/common/uint128_arithmetic.hpp" #include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/operator/integer_cast_operator.hpp" #include "duckdb/common/operator/double_cast_operator.hpp" @@ -3367,7 +3367,7 @@ static void CastDecimalToFloatingPointRounded(hugeint_t input, DST &result, uint const auto upper = static_cast(input.upper); const auto dropped_digits = NumericHelper::UnsignedLength(upper); mantissa = - BignumLimb::DivRemPortable(upper, input.lower, Uhugeint::POWERS_OF_TEN[dropped_digits].lower, remainder); + Uint128DivRem64Portable(upper, input.lower, Uhugeint::POWERS_OF_TEN[dropped_digits].lower, remainder); exponent += dropped_digits; } // Eisel-Lemire; a truncated mantissa is only usable if mantissa + 1 rounds to the same float diff --git a/src/duckdb/src/common/process_util.cpp b/src/duckdb/src/common/process_util.cpp index 543700238..838bfc5a0 100644 --- a/src/duckdb/src/common/process_util.cpp +++ b/src/duckdb/src/common/process_util.cpp @@ -1,6 +1,5 @@ #include "duckdb/common/process_util.hpp" -#include "duckdb/common/file_system.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/windows.hpp" #include "duckdb/main/os_util.hpp" diff --git a/src/duckdb/src/common/serializer/async_file_writer.cpp b/src/duckdb/src/common/serializer/async_file_writer.cpp index 60fd2ad53..0f2ed94bc 100644 --- a/src/duckdb/src/common/serializer/async_file_writer.cpp +++ b/src/duckdb/src/common/serializer/async_file_writer.cpp @@ -300,7 +300,7 @@ FileWriteMode AsyncFileWriter::GetWriteMode() { } bool AsyncFileWriter::IsLocalFile() { - auto local_file = fs.IsLocalFileSystem(); + auto local_file = handle && handle->file_system.IsLocalFileSystem(); if (!local_file && handle) { try { local_file = handle->OnDiskFile(); diff --git a/src/duckdb/src/common/serializer/buffered_file_reader.cpp b/src/duckdb/src/common/serializer/buffered_file_reader.cpp index d2a26b175..271ab0195 100644 --- a/src/duckdb/src/common/serializer/buffered_file_reader.cpp +++ b/src/duckdb/src/common/serializer/buffered_file_reader.cpp @@ -8,11 +8,10 @@ namespace duckdb { -BufferedFileReader::BufferedFileReader(FileSystem &fs, const char *path, FileLockType lock_type, - optional_ptr opener) +BufferedFileReader::BufferedFileReader(FileSystem &fs, const char *path, FileLockType lock_type) : fs(fs), data(make_unsafe_uniq_array_uninitialized(FILE_BUFFER_SIZE)), offset(0), read_data(0), total_read(0) { - handle = fs.OpenFile(path, FileFlags::FILE_FLAGS_READ | lock_type, opener.get()); + handle = fs.OpenFile(path, FileFlags::FILE_FLAGS_READ | lock_type); file_size = NumericCast(fs.GetFileSize(*handle)); } diff --git a/src/duckdb/src/common/types/bignum_decimal.cpp b/src/duckdb/src/common/types/bignum_decimal.cpp index a551f81f9..61a61b7da 100644 --- a/src/duckdb/src/common/types/bignum_decimal.cpp +++ b/src/duckdb/src/common/types/bignum_decimal.cpp @@ -464,12 +464,13 @@ const string &DecimalHelper::RescaleState::GetPowerOfTen(idx_t exponen return cached_power; } -static string_t DivideAndRound(const BignumIntermediate &source, const BignumIntermediate &divisor, - DecimalRounding rounding, StringHeap &heap, BignumArithmeticState &state) { +string_t DecimalHelper::DivideAndRound(const BignumIntermediate &source, const BignumIntermediate &divisor, + DecimalRounding rounding, StringHeap &heap, + BignumArithmeticState &state) { string_t quotient; string_t remainder; if (!BignumIntermediate::TryDivMod(heap, state, source, divisor, quotient, remainder)) { - throw InternalException("Decimal rescaling: division by a power of ten failed"); + throw InternalException("DivideAndRound: division by zero"); } if (DecimalHelper::IsZero(bignum_t(remainder))) { return quotient; @@ -514,7 +515,8 @@ static string_t RescaleBignum(const bignum_t &value, uint32_t source_scale, uint if (target_scale > source_scale) { return BignumIntermediate::Multiply(heap, state, source.intermediate, factor.intermediate); } - return DivideAndRound(source.intermediate, factor.intermediate, DecimalRounding::HALF_AWAY_FROM_ZERO, heap, state); + return DecimalHelper::DivideAndRound(source.intermediate, factor.intermediate, + DecimalRounding::HALF_AWAY_FROM_ZERO, heap, state); } string DecimalHelper::Rescale(const bignum_t &value, uint32_t source_scale, uint32_t target_scale, diff --git a/src/duckdb/src/common/types/cast_helpers.cpp b/src/duckdb/src/common/types/cast_helpers.cpp index 66a801201..c9951fa6a 100644 --- a/src/duckdb/src/common/types/cast_helpers.cpp +++ b/src/duckdb/src/common/types/cast_helpers.cpp @@ -1,5 +1,4 @@ #include "duckdb/common/types/cast_helpers.hpp" -#include "duckdb/common/bignum_limbs.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/types/uhugeint.hpp" @@ -262,7 +261,7 @@ char *NumericHelper::FormatUnsigned(uhugeint_t value, char *ptr) { while (value.upper > 0) { uint64_t remainder; const auto upper = value.upper / DIVISOR; - const auto lower = BignumLimb::DivRemPortable(value.upper % DIVISOR, value.lower, DIVISOR, remainder); + const auto lower = Uint128DivRem64Portable(value.upper % DIVISOR, value.lower, DIVISOR, remainder); value = uhugeint_t(upper, lower); auto chunk_start = ptr - DIVISOR_DIGITS; diff --git a/src/duckdb/src/common/types/date.cpp b/src/duckdb/src/common/types/date.cpp index a0a4d48ec..eef4f516d 100644 --- a/src/duckdb/src/common/types/date.cpp +++ b/src/duckdb/src/common/types/date.cpp @@ -428,7 +428,8 @@ bool Date::IsValid(int32_t year, int32_t month, int32_t day) { return false; } else if (year == DATE_MIN_YEAR) { if (month < DATE_MIN_MONTH || (month == DATE_MIN_MONTH && day < DATE_MIN_DAY)) { - return false; + // the smallest date is two days below DATE_MIN_DAY (date_t::ninfinity() sits in between) + return month == DATE_MIN_MONTH && day == DATE_MIN_DAY - 2; } } } diff --git a/src/duckdb/src/common/types/hugeint.cpp b/src/duckdb/src/common/types/hugeint.cpp index 896ce3804..8ddfaaad9 100644 --- a/src/duckdb/src/common/types/hugeint.cpp +++ b/src/duckdb/src/common/types/hugeint.cpp @@ -92,37 +92,10 @@ hugeint_t Hugeint::Abs(hugeint_t n) { hugeint_t Hugeint::DivModPositive(hugeint_t lhs, uint64_t rhs, uint64_t &remainder) { D_ASSERT(lhs.upper >= 0); - // DivMod code adapted from: - // https://github.com/calccrypto/uint128_t/blob/master/uint128_t.cpp - - // initialize the result and remainder to 0 - hugeint_t div_result; - div_result.lower = 0; - div_result.upper = 0; - remainder = 0; - - uint8_t highest_bit_set = HugeintHighestBit(lhs); - // now iterate over the amount of bits that are set in the LHS - for (uint8_t x = highest_bit_set; x > 0; x--) { - // left-shift the current result and remainder by 1 - div_result = HugeintLeftShift(div_result, 1); - remainder <<= 1; - // we get the value of the bit at position X, where position 0 is the least-significant bit - if (HugeintIsBitSet(lhs, x - 1)) { - // increment the remainder - remainder++; - } - if (remainder >= rhs) { - // the remainder has passed the division multiplier: add one to the divide result - remainder -= rhs; - div_result.lower++; - if (div_result.lower == 0) { - // overflow - div_result.upper++; - } - } - } - return div_result; + D_ASSERT(rhs != 0); + const auto result = Uint128DivMod(static_cast(lhs.upper), lhs.lower, 0, rhs); + remainder = result.remainder_lower; + return hugeint_t(static_cast(result.quotient_upper), result.quotient_lower); } string Hugeint::ToString(hugeint_t input) { diff --git a/src/duckdb/src/common/types/uhugeint.cpp b/src/duckdb/src/common/types/uhugeint.cpp index a410b5444..cafdcb6e8 100644 --- a/src/duckdb/src/common/types/uhugeint.cpp +++ b/src/duckdb/src/common/types/uhugeint.cpp @@ -235,52 +235,26 @@ uhugeint_t Abs(uhugeint_t n) { return (n); } -static uint8_t Bits(uhugeint_t x) { - uint8_t out = 0; - if (x.upper) { - out = 64; - for (uint64_t upper = x.upper; upper; upper >>= 1) { - ++out; - } - } else { - for (uint64_t lower = x.lower; lower; lower >>= 1) { - ++out; - } - } - return out; -} - uhugeint_t Uhugeint::DivMod(uhugeint_t lhs, uhugeint_t rhs, uhugeint_t &remainder) { if (rhs == 0) { remainder = lhs; return uhugeint_t(0); } - - remainder = uhugeint_t(0); - if (rhs == uhugeint_t(1)) { + if (rhs == 1) { + remainder = uhugeint_t(0); return lhs; - } else if (lhs == rhs) { + } + if (lhs == rhs) { + remainder = uhugeint_t(0); return uhugeint_t(1); - } else if (lhs == uhugeint_t(0) || lhs < rhs) { + } + if (lhs < rhs) { remainder = lhs; return uhugeint_t(0); } - - uhugeint_t result = 0; - for (uint8_t idx = Bits(lhs); idx > 0; --idx) { - result <<= 1; - remainder <<= 1; - - if (((lhs >> (idx - 1U)) & 1) != 0) { - remainder += 1; - } - - if (remainder >= rhs) { - remainder -= rhs; - result += 1; - } - } - return result; + const auto result = Uint128DivMod(lhs.upper, lhs.lower, rhs.upper, rhs.lower); + remainder = uhugeint_t(result.remainder_upper, result.remainder_lower); + return uhugeint_t(result.quotient_upper, result.quotient_lower); } template <> 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 32e8c5990..367e2f9b8 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp @@ -650,8 +650,13 @@ ParquetArrayIterator ParquetVariantNode::GetArrayChildren() const { // ParquetObjectIterator //===--------------------------------------------------------------------===// void ParquetObjectIterator::Finalize() { - std::sort(ordered_entries.begin(), ordered_entries.end(), - [](const ParquetObjectEntry &a, const ParquetObjectEntry &b) { return a.key < b.key; }); + // the fields of a Parquet variant object are stored sorted by key, so this is usually a no-op + auto key_less = [](const ParquetObjectEntry &a, const ParquetObjectEntry &b) { + return a.key < b.key; + }; + if (!std::is_sorted(ordered_entries.begin(), ordered_entries.end(), key_less)) { + std::sort(ordered_entries.begin(), ordered_entries.end(), key_less); + } // the keys of a Variant object have to be unique for (idx_t i = 1; i < ordered_entries.size(); i++) { if (ordered_entries[i].key == ordered_entries[i - 1].key) { diff --git a/src/duckdb/src/common/virtual_file_system.cpp b/src/duckdb/src/common/virtual_file_system.cpp index 9c1176e0b..d30e947d2 100644 --- a/src/duckdb/src/common/virtual_file_system.cpp +++ b/src/duckdb/src/common/virtual_file_system.cpp @@ -19,17 +19,17 @@ namespace duckdb { struct FileSystemHandle { - explicit FileSystemHandle(unique_ptr fs) : file_system(std::move(fs)) { + explicit FileSystemHandle(unique_ptr fs) : file_system(std::move(fs)) { } - unique_ptr file_system; + unique_ptr file_system; }; //! The FileSystemRegistry holds the set of file systems that are registered. //! Note that it should be treated as read-only. //! When a change is made (e.g. by registering new file system) a copy of the registry is made struct FileSystemRegistry { - explicit FileSystemRegistry(unique_ptr fs) + explicit FileSystemRegistry(unique_ptr fs) : default_fs(make_shared_ptr(std::move(fs))) { } @@ -40,13 +40,13 @@ struct FileSystemRegistry { map> compressed_fs; public: - shared_ptr RegisterSubSystem(unique_ptr fs) const; + shared_ptr RegisterSubSystem(unique_ptr fs) const; shared_ptr RegisterCompressionFilesystem(unique_ptr fs) const; shared_ptr SetDisabledFileSystems(const vector &names) const; - shared_ptr ExtractSubSystem(const string &name, unique_ptr &result) const; + shared_ptr ExtractSubSystem(const string &name, unique_ptr &result) const; }; -shared_ptr FileSystemRegistry::RegisterSubSystem(unique_ptr fs) const { +shared_ptr FileSystemRegistry::RegisterSubSystem(unique_ptr fs) const { auto new_registry = make_shared_ptr(*this); const auto &name = fs->GetName(); for (auto &sub_system : new_registry->sub_systems) { @@ -90,7 +90,7 @@ shared_ptr FileSystemRegistry::SetDisabledFileSystems(const } shared_ptr FileSystemRegistry::ExtractSubSystem(const string &name, - unique_ptr &result) const { + unique_ptr &result) const { auto new_registry = make_shared_ptr(*this); // If the subsystem has been disabled, we don't allow extraction and return nullptr here. if (disabled_file_systems.find(name) != disabled_file_systems.end()) { @@ -113,7 +113,7 @@ shared_ptr FileSystemRegistry::ExtractSubSystem(const string VirtualFileSystem::VirtualFileSystem() : VirtualFileSystem(make_uniq()) { } -VirtualFileSystem::VirtualFileSystem(unique_ptr &&inner) +VirtualFileSystem::VirtualFileSystem(unique_ptr &&inner) : file_system_registry(make_shared_ptr(std::move(inner))) { VirtualFileSystem::RegisterCompressionFilesystem(make_uniq()); } @@ -121,7 +121,7 @@ VirtualFileSystem::VirtualFileSystem(unique_ptr &&inner) VirtualFileSystem::~VirtualFileSystem() { } -FileSystem &VirtualFileSystem::GetDefaultFileSystem() { +BaseFileSystem &VirtualFileSystem::GetDefaultFileSystem() { auto registry = file_system_registry.atomic_load(); return *registry->default_fs->file_system; } @@ -156,9 +156,9 @@ static FileCompressionType CompressionFromExtension(const string &lower_path) { return FileCompressionType::UNCOMPRESSED; } -optional_ptr VirtualFileSystem::FindCompressionFileSystem(FileSystemRegistry ®istry, - const FileCompressionType &compression, - const string &filepath, bool for_writing) { +optional_ptr VirtualFileSystem::FindCompressionFileSystem(FileSystemRegistry ®istry, + const FileCompressionType &compression, + const string &filepath, bool for_writing) { auto resolved = compression; // For auto-detection, check whether any registered compression filesystem can handle this file. if (resolved.IsAutoDetect()) { @@ -259,7 +259,7 @@ unique_ptr VirtualFileSystem::WrapOpenedFile(unique_ptr return file_handle; } -void VirtualFileSystem::RegisterSubSystem(unique_ptr fs) { +void VirtualFileSystem::RegisterSubSystem(unique_ptr fs) { lock_guard guard(registry_lock); auto new_registry = file_system_registry->RegisterSubSystem(std::move(fs)); file_system_registry.atomic_store(new_registry); @@ -295,9 +295,9 @@ vector VirtualFileSystem::GetDisabledFileSystems() { return names; } -unique_ptr VirtualFileSystem::ExtractSubSystem(const string &name) { +unique_ptr VirtualFileSystem::ExtractSubSystem(const string &name) { lock_guard guard(registry_lock); - unique_ptr result; + unique_ptr result; auto new_registry = file_system_registry->ExtractSubSystem(name, result); if (new_registry) { file_system_registry.atomic_store(new_registry); @@ -338,13 +338,13 @@ bool VirtualFileSystem::IsDisabledForPath(const string &path) { return disabled_file_systems.find(fs->GetName()) != disabled_file_systems.end(); } -FileSystem &VirtualFileSystem::FindFileSystem(const string &path, optional_ptr opener) { +BaseFileSystem &VirtualFileSystem::FindFileSystem(const string &path, optional_ptr opener) { auto registry = file_system_registry.atomic_load(); return FindFileSystem(registry, path, opener); } -FileSystem &VirtualFileSystem::FindFileSystem(shared_ptr ®istry, const string &path, - optional_ptr opener) { +BaseFileSystem &VirtualFileSystem::FindFileSystem(shared_ptr ®istry, const string &path, + optional_ptr opener) { auto db_instance = FileOpener::TryGetDatabase(opener); auto fs = FindFileSystemInternal(*registry, path); @@ -367,8 +367,9 @@ FileSystem &VirtualFileSystem::FindFileSystem(shared_ptr &re return *fs; } -optional_ptr VirtualFileSystem::FindFileSystemInternal(FileSystemRegistry ®istry, const string &path) { - optional_ptr fs; +optional_ptr VirtualFileSystem::FindFileSystemInternal(FileSystemRegistry ®istry, + const string &path) { + optional_ptr fs; for (auto &sub_system : registry.sub_systems) { auto &sub_fs = *sub_system->file_system; if (sub_fs.CanHandleFile(path)) { diff --git a/src/duckdb/src/execution/aggregate_state_spilling.cpp b/src/duckdb/src/execution/aggregate_state_spilling.cpp index 371d6f50b..63616fb42 100644 --- a/src/duckdb/src/execution/aggregate_state_spilling.cpp +++ b/src/duckdb/src/execution/aggregate_state_spilling.cpp @@ -44,27 +44,30 @@ unique_ptr AggregateStateSpilling::TryCreateSpillPlan(c return nullptr; } auto plan = make_uniq(); - plan->state_layouts.reserve(aggregates.size()); + plan->serializers.reserve(aggregates.size()); for (auto &aggr : aggregates) { if (aggr.function.HasStateDestructorCallback()) { // the state owns resources beyond the arena return nullptr; } - AggregateStateLayout state_layout; if (aggr.function.HasGetStateTypeCallback()) { - state_layout = aggr.function.GetStateType(aggr.GetFunctionData()); - } else if (!ExportAggregateFunction::TryGetCombinedStateLayout(aggr.function, aggr.GetFunctionData(), - state_layout)) { - // the aggregate cannot describe its state, and it is not a combine_aggr over states that can: the - // states combine_aggr accumulates have the layout of the aggregate that exported them + plan->serializers.emplace_back(aggr.function.GetStateType(aggr.GetFunctionData()), aggr.function, + aggr.GetFunctionData()); + continue; + } + // the states combine_aggr accumulates have the layout of the aggregate that exported them + auto combined = ExportAggregateFunction::TryGetCombinedStateSerializer(aggr.function, aggr.GetFunctionData()); + if (!combined) { + // the aggregate cannot describe its state, and it is not a combine_aggr over states that can return nullptr; } - plan->state_layouts.push_back(std::move(state_layout)); + plan->serializers.push_back(std::move(*combined)); } // only layouts whose states can reference the arena benefit from spilling bool arena_backed = false; - for (auto &state_layout : plan->state_layouts) { - if (FieldHasArenaReferences(state_layout.type, state_layout.field)) { + for (auto &serializer : plan->serializers) { + auto &state_layout = serializer.layout; + if (state_layout.spill_opaque_arena_memory || FieldHasArenaReferences(state_layout.type, state_layout.field)) { arena_backed = true; break; } @@ -73,8 +76,8 @@ unique_ptr AggregateStateSpilling::TryCreateSpillPlan(c return nullptr; } plan->exported_types = layout.GetTypes(); - for (auto &state_layout : plan->state_layouts) { - plan->exported_types.push_back(state_layout.type); + for (auto &serializer : plan->serializers) { + plan->exported_types.push_back(serializer.layout.type); } return plan; } @@ -83,7 +86,6 @@ void AggregateStateSpilling::ExportStates(ClientContext &context, const TupleDat const AggregateStateSpillPlan &plan, TupleDataCollection &source, vector> &exported, idx_t exported_radix_bits, ArenaAllocator &allocator) { - auto &state_layouts = plan.state_layouts; auto &exported_types = plan.exported_types; if (source.Count() == 0) { return; @@ -121,7 +123,8 @@ void AggregateStateSpilling::ExportStates(ClientContext &context, const TupleDat state_address_data[i] = row_locations[i] + aggr_offset; } auto &result = exported_chunk.data[column_count + aggr_idx]; - AggregateStateSerialization::SerializeStates(aggr.function, aggr.GetFunctionData(), state_layouts[aggr_idx], + auto &serializer = plan.serializers[aggr_idx]; + AggregateStateSerialization::SerializeStates(serializer.function, serializer.bind_data, serializer.layout, state_addresses, count, result, allocator, 0); aggr_offset += aggr.payload_size; } @@ -171,7 +174,6 @@ void AggregateStateSpilling::ImportStates(ClientContext &context, const shared_p const AggregateStateSpillPlan &plan, ColumnDataCollection &exported, ArenaAllocator &allocator, const std::function &combine) { - auto &state_layouts = plan.state_layouts; if (exported.Count() == 0) { return; } @@ -185,8 +187,8 @@ void AggregateStateSpilling::ImportStates(ClientContext &context, const shared_p // scratch buffer holding one vector of deserialized states, packed consecutively idx_t max_state_size = 0; - for (auto &state_layout : state_layouts) { - max_state_size = MaxValue(max_state_size, state_layout.total_state_size); + for (auto &serializer : plan.serializers) { + max_state_size = MaxValue(max_state_size, serializer.layout.total_state_size); } auto state_buffer = make_unsafe_uniq_array(max_state_size * STANDARD_VECTOR_SIZE); Vector state_addresses(LogicalType::POINTER); @@ -211,8 +213,8 @@ void AggregateStateSpilling::ImportStates(ClientContext &context, const shared_p idx_t aggr_offset = layout->GetAggrOffset(); for (idx_t aggr_idx = 0; aggr_idx < aggregates.size(); aggr_idx++) { auto &aggr = aggregates[aggr_idx]; - auto &state_layout = state_layouts[aggr_idx]; - const auto state_size = state_layout.total_state_size; + auto &serializer = plan.serializers[aggr_idx]; + const auto state_size = serializer.layout.total_state_size; D_ASSERT(state_size == aggr.payload_size); // initialize scratch states, deserialize into them, then place them in the rows @@ -221,7 +223,7 @@ void AggregateStateSpilling::ImportStates(ClientContext &context, const shared_p state_address_data[i] = state_buffer.get() + i * state_size; aggr.function.GetStateInitCallback()(state_input, &state_address_data[i], 1); } - AggregateStateSerialization::DeserializeStates(aggr.function, state_layout, + AggregateStateSerialization::DeserializeStates(serializer.function, serializer.bind_data, serializer.layout, exported_chunk.data[column_count + aggr_idx], count, state_buffer.get(), allocator, StateMemoryOwnership::OWNED); for (idx_t i = 0; i < count; i++) { diff --git a/src/duckdb/src/execution/index/art/art.cpp b/src/duckdb/src/execution/index/art/art.cpp index 171f952c8..feddfecbf 100644 --- a/src/duckdb/src/execution/index/art/art.cpp +++ b/src/duckdb/src/execution/index/art/art.cpp @@ -1,5 +1,6 @@ #include "duckdb/execution/index/art/art.hpp" #include "duckdb/common/helper.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/main/attached_database.hpp" #include "duckdb/common/types/conflict_manager.hpp" @@ -655,7 +656,7 @@ ErrorData ART::InsertKeys(ArenaAllocator &arena, unsafe_vector &keys, un } if (conflict_type == ARTConflictType::CONSTRAINT) { - // chunk is only null when called from MergeCheckpointDeltas. + // chunk is only null when merging a delta. auto msg = chunk ? AppendRowError(*chunk, conflict_idx.GetIndex()) : string("???"); return ErrorData(ConstraintException("PRIMARY KEY or UNIQUE constraint violation: duplicate key \"%s\"", msg)); } @@ -1166,6 +1167,17 @@ IndexStorageInfo ART::PrepareSerialize(const ARTSerializationFormat target_forma if (storage_version != StorageVersion::INVALID) { info.options["storage_version"] = Value::UBIGINT(static_cast(storage_version)); } + // From the storage version of wide decimals on, the types of the keys are recorded: the stored keys are encoded + // from them, so an index whose expressions bind to other types when it is loaded (the result type of a key + // expression is decided by the engine that binds it) is not used with keys it cannot match + if (storage_version != StorageVersion::INVALID && + !StorageManager::IsPriorToVersion(Decimal::WIDE_VERSION_ADDED, storage_version)) { + vector key_types; + for (auto &type : logical_types) { + key_types.push_back(Value::TYPE(type)); + } + info.options["key_types"] = Value::LIST(LogicalType::TYPE(), std::move(key_types)); + } #ifdef DEBUG if (target_format == ARTSerializationFormat::V1_0_0) { @@ -1486,7 +1498,7 @@ bool ART::MergeIndexes(IndexLock &state, BoundIndex &source_index) { } // FIXME : Make this a more efficient structural tree removal merge -// Right now this is only used in MergeCheckpointDeltas to avoid having to do a table scan. +// Right now this is only used to merge deltas, to avoid having to do a table scan. void ART::RemovalMerge(IndexLock &state, BoundIndex &source_index) { state.AssertHeld(*this); auto &source = source_index.Cast(); @@ -1567,16 +1579,15 @@ ErrorData ART::InsertMerge(BoundIndex &source_index, IndexAppendMode append_mode return InsertMerge(state, source_index, append_mode); } -ErrorData ART::MergeCheckpointDelta(const IndexDeltaType type, BoundIndex &delta_index) { +ErrorData ART::MergeDelta(const IndexDeltaType type, BoundIndex &delta_index, const IndexAppendMode append_mode) { switch (type) { - case IndexDeltaType::REMOVED_DATA_DURING_CHECKPOINT: + case IndexDeltaType::REMOVED_DATA: RemovalMerge(delta_index); return ErrorData(); - case IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT: - // Inserts happen before deletes during commit, so duplicates must be accepted while merging the added rows. - return InsertMerge(delta_index, IndexAppendMode::INSERT_DUPLICATES); + case IndexDeltaType::ADDED_DATA: + return InsertMerge(delta_index, append_mode); default: - throw InternalException("Unsupported ART checkpoint delta type"); + throw InternalException("Unsupported ART delta type"); } } diff --git a/src/duckdb/src/execution/index/art/art_builder.cpp b/src/duckdb/src/execution/index/art/art_builder.cpp index 060f7a489..5113009fc 100644 --- a/src/duckdb/src/execution/index/art/art_builder.cpp +++ b/src/duckdb/src/execution/index/art/art_builder.cpp @@ -8,6 +8,17 @@ namespace duckdb { +void ARTBuilder::SetChild(const NodeEntry &entry, const NodePtr node_ptr) { + if (!entry.parent_ptr.HasMetadata()) { + *root_ptr = node_ptr; + return; + } + NodeHandle handle(art, entry.parent_ptr); + auto child_ptr = NodePtr::GetChildMutable(handle, entry.byte, true); + D_ASSERT(child_ptr && !child_ptr->HasMetadata()); + *child_ptr = node_ptr; +} + ARTConflictType ARTBuilder::Build() { while (!s.empty()) { // Copy the entry so we can pop it. @@ -37,12 +48,13 @@ ARTConflictType ARTBuilder::Build() { } // Create the prefix, if any. The tail stays pinned while we fill its child. - reference node_ptr_ref(entry.node_ptr); + NodePtr node_ptr; + reference node_ptr_ref(node_ptr); optional tail; auto count = UnsafeNumericCast(start.len - prefix_depth); if (count != 0) { auto chain = PrefixHandle::New(art, start, prefix_depth, count); - entry.node_ptr = chain.root_ptr; + node_ptr = chain.root_ptr; tail = std::move(chain.tail); node_ptr_ref = tail->Child(art); } @@ -50,6 +62,7 @@ ARTConflictType ARTBuilder::Build() { // Inline the row ID. if (row_id_count == 1) { Leaf::New(node_ptr_ref, row_ids[entry.start].GetRowId()); + SetChild(entry, node_ptr); continue; } @@ -61,16 +74,18 @@ ARTConflictType ARTBuilder::Build() { DeleteIndexInfo(), IndexAppendMode::DEFAULT); } node_ptr_ref.get().SetGateStatus(GateStatus::GATE_SET); + SetChild(entry, node_ptr); continue; } // Create the prefix, if any. The tail stays pinned while we fill its child. - reference node_ptr_ref(entry.node_ptr); + NodePtr node_ptr; + reference node_ptr_ref(node_ptr); optional tail; auto prefix_length = entry.depth - prefix_depth; if (prefix_length != 0) { auto chain = PrefixHandle::New(art, start, prefix_depth, prefix_length); - entry.node_ptr = chain.root_ptr; + node_ptr = chain.root_ptr; tail = std::move(chain.tail); node_ptr_ref = tail->Child(art); } @@ -88,14 +103,13 @@ ARTConflictType ARTBuilder::Build() { auto start_offset = child_offsets[0]; for (idx_t i = 1; i <= child_offsets.size(); i++) { auto child_byte = keys[start_offset].data[entry.depth]; - // FIXME: Improve performance by either returning a reference to the child directly, - // FIXME: or by calling InsertChild after processing the child (at the end of the stack loop). + // FIXME: Insert the child after building it, instead of inserting an empty child here. NodePtr::InsertChild(art, node_ptr_ref, child_byte); - auto child_ptr_ref = node_ptr_ref.get().NodePtr::GetChildMutableUnsafe(art, child_byte, true); auto end_offset = i != child_offsets.size() ? child_offsets[i] - 1 : entry.end; - s.emplace(*child_ptr_ref, start_offset, end_offset, entry.depth + 1); + s.emplace(node_ptr_ref.get(), child_byte, start_offset, end_offset, entry.depth + 1); start_offset = end_offset + 1; } + SetChild(entry, node_ptr); } // We exhausted the stack. diff --git a/src/duckdb/src/execution/index/art/node.cpp b/src/duckdb/src/execution/index/art/node.cpp index b8f83dc3e..298976a96 100644 --- a/src/duckdb/src/execution/index/art/node.cpp +++ b/src/duckdb/src/execution/index/art/node.cpp @@ -230,8 +230,8 @@ const unsafe_optional_ptr NodePtr::GetChild(ART &art, const uint8_t byt return GetChildInternal(art, *this, byte, false); } -unsafe_optional_ptr NodePtr::GetChildMutableUnsafe(ART &art, const uint8_t byte, const bool unsafe) const { - return GetChildInternal(art, *this, byte, unsafe); +unsafe_optional_ptr NodePtr::GetChildMutableUnsafe(ART &art, const uint8_t byte) const { + return GetChildInternal(art, *this, byte, false); } OptionalNodePtr NodePtr::GetChildNode(const ART &art, const uint8_t byte) const { @@ -252,20 +252,20 @@ OptionalNodePtr NodePtr::GetChildNode(const ART &art, const uint8_t byte) const } } -unsafe_optional_ptr NodePtr::GetChildMutable(NodeHandle &handle, const uint8_t byte) { +unsafe_optional_ptr NodePtr::GetChildMutable(NodeHandle &handle, const uint8_t byte, const bool unsafe) { unsafe_optional_ptr child; switch (handle.GetType()) { case NType::NODE_4: - child = Node4::GetChild(handle.Get(), byte); + child = Node4::GetChild(handle.Get(), byte, unsafe); break; case NType::NODE_16: - child = Node16::GetChild(handle.Get(), byte); + child = Node16::GetChild(handle.Get(), byte, unsafe); break; case NType::NODE_48: - child = Node48::GetChild(handle.Get(), byte); + child = Node48::GetChild(handle.Get(), byte, unsafe); break; case NType::NODE_256: - child = Node256::GetChild(handle.Get(), byte); + child = Node256::GetChild(handle.Get(), byte, unsafe); break; default: throw InternalException("Invalid node type for GetChildMutable: %d.", handle.GetType()); diff --git a/src/duckdb/src/execution/index/bound_index.cpp b/src/duckdb/src/execution/index/bound_index.cpp index 377fe2f51..88ac4e2b5 100644 --- a/src/duckdb/src/execution/index/bound_index.cpp +++ b/src/duckdb/src/execution/index/bound_index.cpp @@ -183,8 +183,8 @@ unique_ptr BoundIndex::CreateEmptyCopy(IndexConstraintType) const { throw InternalException("BoundIndex::CreateEmptyCopy is not supported for this index type"); } -ErrorData BoundIndex::MergeCheckpointDelta(IndexDeltaType, BoundIndex &) { - throw InternalException("BoundIndex::MergeCheckpointDelta is not supported for this index type"); +ErrorData BoundIndex::MergeDelta(IndexDeltaType, BoundIndex &, IndexAppendMode) { + throw InternalException("BoundIndex::MergeDelta is not supported for this index type"); } IndexStorageInfo BoundIndex::SerializeToWAL(const StorageVersion) { diff --git a/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp b/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp index 7f819a52e..eb1e3a682 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp @@ -197,7 +197,7 @@ bool PhysicalStreamingWindow::IsStreamingFunction(ClientContext &client, BoundWi } if (wexpr.GetExpressionType() == ExpressionType::WINDOW_AGGREGATE) { // Aggregates with destructors (e.g., quantile) are too slow to repeatedly update/finalize - if (wexpr.AggregateFunction()->HasStateDestructorCallback()) { + if (wexpr.AggregateFunction()->HasStateDestructorCallback() || !wexpr.AggregateFunction()->CanStream()) { return false; } // We can stream aggregates if they are "running totals" diff --git a/src/duckdb/src/execution/operator/aggregate/physical_window.cpp b/src/duckdb/src/execution/operator/aggregate/physical_window.cpp index 6f533a33e..6ddd4b061 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_window.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_window.cpp @@ -150,6 +150,9 @@ class WindowHashGroup { return false; } + //! Decide whether co-evaluation is worth it + bool ShouldCoEvaluate(idx_t size = STANDARD_VECTOR_SIZE) const; + //! The shared global state from sinking WindowGlobalSinkState &gsink; //! The hash partition data @@ -1171,6 +1174,39 @@ void WindowLocalSourceState::BuildResult(ExecutionContext &context, DataChunk &i result.Verify(context.client.db); } +bool WindowHashGroup::ShouldCoEvaluate(idx_t size) const { + if (!gsink.op.partition_limit.IsValid()) { + return false; + } + + // Compute the expected value of the span used by co-evaluation + const auto partition_limit = LossyNumericCast(gsink.op.partition_limit.GetIndex()); + const auto npartitions = LossyNumericCast(partition_count.load()); + const auto dcount = LossyNumericCast(count); + const auto partition_avg = dcount / npartitions; + const auto k = MinValue(partition_limit, partition_avg); + const auto active_rows = npartitions * k; + const auto prob_i_active = active_rows / dcount; + const auto prob_i_inactive = 1 - prob_i_active; + const auto avg_inactive = (partition_avg - partition_limit) / 2; + const auto dsize = LossyNumericCast(size); + + double expected = 0; + // Case 1: begin is active + // Case 1a: end is active: the entire vector is active + expected += prob_i_active * prob_i_active * dsize; + // Case 1b: end is inactive: the tail has an inactive range + expected += prob_i_active * prob_i_inactive * (dsize - avg_inactive); + // Case 2: begin is inactive: the head has an inactive range + // Case 2a: end is active + expected += prob_i_inactive * prob_i_active * (dsize - avg_inactive); + // Case 2b: end is inactive: there are likely gaps at either end + expected += prob_i_inactive * prob_i_inactive * (dsize - avg_inactive * 2); + + // TODO: Scale for partition lookup cost. + return expected < 0.8 * dsize; +} + 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; @@ -1269,9 +1305,7 @@ void WindowLocalSourceState::GetData(ExecutionContext &context, DataChunk &resul 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) { + if (window_hash_group->ShouldCoEvaluate()) { CoEvaluate(context, result, interrupt); return; } 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 1e56571fd..9304c2acd 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 @@ -65,23 +65,51 @@ CSVEncoder::CSVEncoder(ClientContext &context_p, const string &encoding_name_to_ throw InvalidInputException(error.str()); } - // Bind the streaming overload: decode_(encoded BLOB, is_last BOOLEAN) - auto function = entry->functions.GetFunctionByArguments(context_p, {LogicalType::BLOB, LogicalType::BOOLEAN}); - vector> children; - children.push_back(make_uniq(LogicalType::BLOB, 0)); - children.push_back(make_uniq(LogicalType::BOOLEAN, 1)); - decode_expression = function->Bind(context_p, std::move(children)); - decode_executor = make_uniq(context_p, *decode_expression); + auto function = BindDecoder(context_p, *entry); decode_input.Initialize(context_p, {LogicalType::BLOB, LogicalType::BOOLEAN}, 1); auto window = function->GetProperties().GetProperty(EncodingFunction::MINIMUM_INPUT_WINDOW_PROPERTY); if (window) { minimum_input_window = MaxValue(window->GetValue(), 1); } + auto marks = function->GetProperties().GetProperty(EncodingFunction::BYTE_ORDER_MARKS_PROPERTY); + if (marks) { + for (auto &mark : ListValue::GetChildren(*marks)) { + auto &fields = StructValue::GetChildren(mark); + byte_order_marks.emplace_back(StringValue::Get(fields[0]), StringValue::Get(fields[1])); + } + } // The encoded buffer is even for utf-16, and fits a full input window plus the probe byte encoded_buffer.Initialize(MaxValue(buffer_size - buffer_size % 2, 2 * minimum_input_window + 2)); } +shared_ptr CSVEncoder::BindDecoder(ClientContext &context_p, ScalarFunctionCatalogEntry &entry) { + // Bind the streaming overload: decode_(encoded BLOB, is_last BOOLEAN) + auto function = entry.functions.GetFunctionByArguments(context_p, {LogicalType::BLOB, LogicalType::BOOLEAN}); + vector> children; + children.push_back(make_uniq(LogicalType::BLOB, 0)); + children.push_back(make_uniq(LogicalType::BOOLEAN, 1)); + decode_expression = function->Bind(context_p, std::move(children)); + decode_executor = make_uniq(context_p, *decode_expression); + return function; +} + +void CSVEncoder::DetectByteOrder() { + for (auto &mark : byte_order_marks) { + if (encoded_buffer.GetSize() < mark.first.size() || + memcmp(encoded_buffer.Ptr(), mark.first.data(), mark.first.size()) != 0) { + continue; + } + auto &client_context = *context.GetClientContext(); + auto entry = EncodingFunction::Find(client_context, mark.second); + if (!entry) { + throw InternalException("Encoding \"%s\" picked by a byte order mark does not exist", mark.second); + } + BindDecoder(client_context, *entry); + return; + } +} + void CSVEncoder::Reset() { encoded_buffer.Reset(); encoded_buffer.last_buffer = false; @@ -154,6 +182,7 @@ idx_t CSVEncoder::Encode(FileHandle &file_handle_input, char *output_buffer, con // 3. a new encoded buffer from the file while (output_buffer_pos < decoded_buffer_size) { idx_t current_decoded_buffer_start = output_buffer_pos; + const bool file_start = encoded_bytes_read == 0; // An incomplete character at the end of the buffer is moved to the start of the next buffer const idx_t tail_size = encoded_buffer.GetSize() - encoded_buffer.cur_pos; memmove(encoded_buffer.Ptr(), encoded_buffer.Ptr() + encoded_buffer.cur_pos, tail_size); @@ -179,6 +208,9 @@ idx_t CSVEncoder::Encode(FileHandle &file_handle_input, char *output_buffer, con has_pass_on_byte = true; } } + if (file_start) { + DetectByteOrder(); + } output_buffer_pos = DecodeBuffer(output_buffer, output_buffer_pos, decoded_buffer_size); if (output_buffer_pos == current_decoded_buffer_start) { return output_buffer_pos; diff --git a/src/duckdb/src/execution/operator/helper/physical_limit.cpp b/src/duckdb/src/execution/operator/helper/physical_limit.cpp index 997a6a648..3452cc226 100644 --- a/src/duckdb/src/execution/operator/helper/physical_limit.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_limit.cpp @@ -92,9 +92,9 @@ idx_t PhysicalLimit::GetLimitValue(const Value &val, idx_t null_value) { return value; } -bool PhysicalLimit::ComputeOffset(ExecutionContext &context, DataChunk &input, optional_idx &limit, - optional_idx &offset, idx_t current_offset, idx_t &max_element, - const BoundLimitNode &limit_val, const BoundLimitNode &offset_val) { +void PhysicalLimit::ResolveLimits(ExecutionContext &context, DataChunk &input, optional_idx &limit, + optional_idx &offset, const BoundLimitNode &limit_val, + const BoundLimitNode &offset_val) { if (!limit.IsValid()) { Value val = GetDelimiter(context, input, limit_val.GetValueExpression()); limit = GetLimitValue(val, MAX_LIMIT_VALUE); @@ -103,6 +103,12 @@ bool PhysicalLimit::ComputeOffset(ExecutionContext &context, DataChunk &input, o Value val = GetDelimiter(context, input, offset_val.GetValueExpression()); offset = GetLimitValue(val, 0); } +} + +bool PhysicalLimit::ComputeOffset(ExecutionContext &context, DataChunk &input, optional_idx &limit, + optional_idx &offset, idx_t current_offset, idx_t &max_element, + const BoundLimitNode &limit_val, const BoundLimitNode &offset_val) { + ResolveLimits(context, input, limit, offset, limit_val, offset_val); max_element = limit.GetIndex() + offset.GetIndex(); if (limit == 0 || current_offset >= max_element) { return false; diff --git a/src/duckdb/src/execution/operator/helper/physical_streaming_limit.cpp b/src/duckdb/src/execution/operator/helper/physical_streaming_limit.cpp index e61ca9db5..1851b6d4a 100644 --- a/src/duckdb/src/execution/operator/helper/physical_streaming_limit.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_streaming_limit.cpp @@ -25,10 +25,15 @@ class StreamingLimitOperatorState : public OperatorState { class StreamingLimitGlobalState : public GlobalOperatorState { public: - StreamingLimitGlobalState() : current_offset(0) { + explicit StreamingLimitGlobalState(const PhysicalStreamingLimit &op) : current_offset(0) { + PhysicalLimit::SetInitialLimits(op.limit_val, op.offset_val, limit, offset); } std::atomic current_offset; + //! Expression-valued limit and offset, evaluated once so that every thread uses the same values + mutex lock; + optional_idx limit; + optional_idx offset; }; void PhysicalStreamingLimit::InitializeOutputChunk(Allocator &allocator, DataChunk &chunk) const { @@ -41,7 +46,7 @@ unique_ptr PhysicalStreamingLimit::GetOperatorState(ExecutionCont } unique_ptr PhysicalStreamingLimit::GetGlobalOperatorState(ClientContext &context) const { - return make_uniq(); + return make_uniq(*this); } OperatorResultType PhysicalStreamingLimit::Execute(ExecutionContext &context, DataChunk &input, DataChunk &chunk, @@ -50,6 +55,12 @@ OperatorResultType PhysicalStreamingLimit::Execute(ExecutionContext &context, Da auto &state = state_p.Cast(); auto &limit = state.limit; auto &offset = state.offset; + if (!limit.IsValid() || !offset.IsValid()) { + lock_guard guard(gstate.lock); + PhysicalLimit::ResolveLimits(context, input, gstate.limit, gstate.offset, limit_val, offset_val); + limit = gstate.limit; + offset = gstate.offset; + } idx_t current_offset = gstate.current_offset.fetch_add(input.size()); idx_t max_element; if (!PhysicalLimit::ComputeOffset(context, input, limit, offset, current_offset, max_element, limit_val, diff --git a/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp b/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp index 29a31ff84..338f9f104 100644 --- a/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp +++ b/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp @@ -265,7 +265,8 @@ void JoinFilterPushdownInfo::DeferRuntimeFilter(DeferredRuntimeFilterType type, const JoinFilterPushdownFilter &info, const JoinFilterPushdownColumn &column, ProjectionIndex filter_col_idx, idx_t key_idx, JoinFilterGlobalState &gstate) const { - gstate.deferred_runtime_filters.push_back({type, &op, info.dynamic_filters, column, filter_col_idx, key_idx}); + gstate.deferred_runtime_filters.push_back( + {type, &op, info.dynamic_filters, column.Copy(), filter_col_idx, key_idx}); } bool JoinFilterPushdownInfo::TryRegisterPrefixRangeFilter(const JoinFilterPushdownFilter &info, ClientContext &context, diff --git a/src/duckdb/src/execution/operator/persistent/physical_batch_insert.cpp b/src/duckdb/src/execution/operator/persistent/physical_batch_insert.cpp index bbb4ac1e5..098ca80f1 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_batch_insert.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_batch_insert.cpp @@ -337,6 +337,10 @@ unique_ptr PhysicalBatchInsert::GetGlobalSinkState(ClientContex D_ASSERT(!insert_table); auto &catalog = schema->catalog; auto created_table = catalog.CreateTable(catalog.GetCatalogTransaction(context), *schema, *info); + if (!created_table) { + // a connection that shares the transaction created the table after the statement was bound + throw TransactionException("Catalog write-write conflict on create with %s", info->Base().GetTableName()); + } table = &created_table->Cast(); } else { D_ASSERT(insert_table); diff --git a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp index feaa4fc97..9ac85bad5 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp @@ -4532,7 +4532,7 @@ void PhysicalCopyToFile::PrepareOutputDirectory(ClientContext &context, const st CopyOverwriteMode overwrite_mode, CopyOutputLifecycle &output_lifecycle) { auto &fs = FileSystem::GetFileSystem(context); - if (!fs.IsRemoteFile(directory)) { + if (!FileSystem::IsRemoteFile(directory)) { if (fs.FileExists(directory)) { if (overwrite_mode == CopyOverwriteMode::COPY_OVERWRITE) { fs.RemoveFile(directory); diff --git a/src/duckdb/src/execution/operator/persistent/physical_insert.cpp b/src/duckdb/src/execution/operator/persistent/physical_insert.cpp index 4778019b8..32461bf5a 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_insert.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_insert.cpp @@ -118,7 +118,12 @@ unique_ptr PhysicalInsert::GetGlobalSinkState(ClientContext &co // CREATE TABLE AS D_ASSERT(!insert_table); auto &catalog = schema->catalog; - table = &catalog.CreateTable(catalog.GetCatalogTransaction(context), *schema, *info)->Cast(); + auto created_table = catalog.CreateTable(catalog.GetCatalogTransaction(context), *schema, *info); + if (!created_table) { + // a connection that shares the transaction created the table after the statement was bound + throw TransactionException("Catalog write-write conflict on create with %s", info->Base().GetTableName()); + } + table = &created_table->Cast(); } else { D_ASSERT(insert_table); D_ASSERT(insert_table->IsDuckTable()); 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 bed7ee669..fb3498d1d 100644 --- a/src/duckdb/src/execution/operator/schema/physical_create_index.cpp +++ b/src/duckdb/src/execution/operator/schema/physical_create_index.cpp @@ -15,6 +15,7 @@ #include "duckdb/storage/table/append_state.hpp" #include "duckdb/storage/table/data_table_info.hpp" #include "duckdb/storage/storage_manager.hpp" +#include "duckdb/transaction/duck_transaction.hpp" #include "duckdb/transaction/local_storage.hpp" #include "duckdb/execution/index/index_type.hpp" @@ -186,7 +187,10 @@ SinkFinalizeType PhysicalCreateIndex::Finalize(Pipeline &pipeline, Event &event, } // Add the index to the storage. - auto index_entry = storage.GetDataTableInfo()->GetIndexes().AddIndex(std::move(bound_index), index_oid, check_mode); + auto &transaction = DuckTransaction::Get(context, storage.db); + // an ALTER publishes to the new table, which shares the index list + auto &target = alter_table_info ? table.Parent().Cast().GetStorage() : storage; + auto index_entry = target.FinishIndexBuild(context, transaction, 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->GetDeleteIndexes()); diff --git a/src/duckdb/src/execution/operator/set/physical_union.cpp b/src/duckdb/src/execution/operator/set/physical_union.cpp index 78551361b..e8f11272c 100644 --- a/src/duckdb/src/execution/operator/set/physical_union.cpp +++ b/src/duckdb/src/execution/operator/set/physical_union.cpp @@ -66,15 +66,19 @@ void PhysicalUnion::BuildPipelines(Pipeline ¤t, MetaPipeline &meta_pipelin union_pipelines.push_back(union_pipeline); } // continue with the current pipeline - children[0].get().BuildPipelines(current, meta_pipeline); - bool can_saturate_threads = - ContainsSink(children[0].get()) && children[0].get().CanSaturateThreads(current.GetClientContext()); + D_ASSERT(!children.empty()); + auto child_it = children.begin(); + PhysicalOperator &first_child = *child_it; + first_child.BuildPipelines(current, meta_pipeline); + bool can_saturate_threads = ContainsSink(first_child) && first_child.CanSaturateThreads(current.GetClientContext()); for (idx_t i = 1; i < children.size(); i++) { + PhysicalOperator &previous_child = *child_it; + ++child_it; + PhysicalOperator &child = *child_it; auto &union_pipeline = union_pipelines[children.size() - i - 1].get(); vector> dependencies; optional_ptr last_child_ptr; - if (ContainsSink(children[i - 1].get()) && - children[i - 1].get().CanSaturateThreads(current.GetClientContext())) { + if (ContainsSink(previous_child) && previous_child.CanSaturateThreads(current.GetClientContext())) { can_saturate_threads = true; } if (order_matters || can_saturate_threads) { @@ -98,7 +102,7 @@ void PhysicalUnion::BuildPipelines(Pipeline ¤t, MetaPipeline &meta_pipelin // Assign proper batch index to the union pipeline meta_pipeline.AssignNextBatchIndex(union_pipeline); // build the union pipeline - children[i].get().BuildPipelines(union_pipeline, meta_pipeline); + child.BuildPipelines(union_pipeline, meta_pipeline); if (last_child_ptr) { // Explicitly ordered unions also order their children's sink pipelines. diff --git a/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp b/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp index 244d1d8d5..45dd1ab48 100644 --- a/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp @@ -266,7 +266,7 @@ static bool CanUsePerfectHashAggregate(ClientContext &context, LogicalAggregate PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalAggregate &op) { D_ASSERT(op.children.size() == 1); - reference plan = CreatePlan(*op.children[0]); + reference plan = CreatePlanRecursive(*op.children[0]); // the ungrouped aggregate evaluates its filters directly; grouped aggregates need them as payload columns const bool ungrouped = op.groups.empty() && op.grouping_sets.size() <= 1; plan = ExtractAggregateExpressions(plan, op.expressions, op.groups, op.grouping_sets, !ungrouped); diff --git a/src/duckdb/src/execution/physical_plan/plan_any_join.cpp b/src/duckdb/src/execution/physical_plan/plan_any_join.cpp index 360ff7588..ec54706f4 100644 --- a/src/duckdb/src/execution/physical_plan/plan_any_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_any_join.cpp @@ -8,8 +8,8 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalAnyJoin &op) { // Visit the child nodes. D_ASSERT(op.children.size() == 2); D_ASSERT(op.condition); - auto &left = CreatePlan(*op.children[0]); - auto &right = CreatePlan(*op.children[1]); + auto &left = CreatePlanRecursive(*op.children[0]); + auto &right = CreatePlanRecursive(*op.children[1]); // Create the blockwise NL join, which emits full child layouts. auto pruned = ExtractPrunedJoinProjection(op, left, right, true, true); diff --git a/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp b/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp index fb687d227..2fadf26be 100644 --- a/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp @@ -353,8 +353,8 @@ PhysicalOperator &PhysicalPlanGenerator::PlanAsOfJoin(LogicalComparisonJoin &op) idx_t rhs_cardinality = op.children[1]->EstimateCardinality(context); // Estimate the join cardinality before planning the children - planning consumes the bind data of their scans const idx_t join_cardinality = op.EstimateCardinality(context); - auto &left = CreatePlan(*op.children[0]); - auto &right = CreatePlan(*op.children[1]); + auto &left = CreatePlanRecursive(*op.children[0]); + auto &right = CreatePlanRecursive(*op.children[1]); // Validate vector equi_indexes; diff --git a/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp b/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp index 3372479d0..fe85ca028 100644 --- a/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp @@ -179,8 +179,8 @@ PhysicalOperator &PhysicalPlanGenerator::PlanComparisonJoin(LogicalComparisonJoi D_ASSERT(op.children.size() == 2); idx_t lhs_cardinality = op.children[0]->EstimateCardinality(context); idx_t rhs_cardinality = op.children[1]->EstimateCardinality(context); - auto &left = CreatePlan(*op.children[0]); - auto &right = CreatePlan(*op.children[1]); + auto &left = CreatePlanRecursive(*op.children[0]); + auto &right = CreatePlanRecursive(*op.children[1]); left.estimated_cardinality = lhs_cardinality; right.estimated_cardinality = rhs_cardinality; auto left_state = FindDirectRecursiveStateScan(left, recursive_cte_planning); diff --git a/src/duckdb/src/execution/physical_plan/plan_copy_to_file.cpp b/src/duckdb/src/execution/physical_plan/plan_copy_to_file.cpp index 8feba8dee..67c9ef747 100644 --- a/src/duckdb/src/execution/physical_plan/plan_copy_to_file.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_copy_to_file.cpp @@ -6,7 +6,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalCopyToFile &op) { - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); auto &fs = FileSystem::GetFileSystem(context); op.file_path = fs.ExpandPath(op.file_path); return CreatePlan(op, plan); diff --git a/src/duckdb/src/execution/physical_plan/plan_create.cpp b/src/duckdb/src/execution/physical_plan/plan_create.cpp index 761620ec8..2090db77c 100644 --- a/src/duckdb/src/execution/physical_plan/plan_create.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_create.cpp @@ -34,7 +34,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalCreate &op) { op.estimated_cardinality); if (!op.children.empty()) { D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); create.children.push_back(plan); } return create; diff --git a/src/duckdb/src/execution/physical_plan/plan_create_index.cpp b/src/duckdb/src/execution/physical_plan/plan_create_index.cpp index 8be5e0620..902ff6326 100644 --- a/src/duckdb/src/execution/physical_plan/plan_create_index.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_create_index.cpp @@ -1,5 +1,6 @@ #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/execution/physical_plan_generator.hpp" +#include "duckdb/function/table/table_scan.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/database.hpp" #include "duckdb/planner/expression/bound_operator_expression.hpp" @@ -12,6 +13,8 @@ #include "duckdb/execution/operator/projection/physical_projection.hpp" #include "duckdb/execution/operator/schema/physical_create_index.hpp" #include "duckdb/catalog/catalog_entry/duck_table_entry.hpp" +#include "duckdb/storage/index_storage_info.hpp" +#include "duckdb/storage/table_io_manager.hpp" namespace duckdb { @@ -25,6 +28,29 @@ static PhysicalOperator &AddCreateIndex(PhysicalPlanGenerator &plan, LogicalCrea return cindex; } +//! Returns an empty index to build in place, or nullptr if the index type does not support it +static shared_ptr CreateIndexTemplate(ClientContext &context, LogicalCreateIndex &op, + const IndexType &index_type) { + if (index_type.create_plan || !index_type.create_instance) { + return nullptr; + } + auto &table = op.table.Cast(); + auto &storage = table.GetStorage(); + vector storage_ids; + for (auto &column_id : op.info->column_ids) { + storage_ids.push_back(table.GetColumns().LogicalToPhysical(LogicalIndex(column_id)).index); + } + IndexStorageInfo storage_info; + CreateIndexInput input(context, TableIOManager::Get(storage), storage.db, IndexConstraintType::NONE, + op.info->GetIndexName(), storage_ids, op.unbound_expressions, storage_info, + op.info->options); + auto index = index_type.create_instance(input); + if (!index || !index->SupportsDeltaIndexes()) { + return nullptr; + } + return shared_ptr(std::move(index)); +} + static PhysicalOperator &AddFilter(PhysicalPlanGenerator &plan, LogicalCreateIndex &op, PhysicalOperator &prev) { auto cardinality = op.estimated_cardinality; @@ -133,7 +159,9 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalCreateIndex &op) { D_ASSERT(op.info->scan_types.size() - 1 <= op.info->column_ids.size()); D_ASSERT(op.children.size() == 1); - auto &scan = CreatePlan(*op.children[0]); + auto &get = op.children[0]->Cast(); + get.bind_data.write().Cast().index_template = CreateIndexTemplate(context, op, *index_type); + auto &scan = CreatePlanRecursive(*op.children[0]); // Index has a plan replacement function if (index_type->create_plan) { diff --git a/src/duckdb/src/execution/physical_plan/plan_create_table.cpp b/src/duckdb/src/execution/physical_plan/plan_create_table.cpp index 28cb05cba..b6ed77d25 100644 --- a/src/duckdb/src/execution/physical_plan/plan_create_table.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_create_table.cpp @@ -43,7 +43,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalCreateTable &op) { create_info.GetTableName()); bool replace = op.info->Base().on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT; if ((!existing_entry || replace) && !op.children.empty()) { - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); return op.schema.catalog.PlanCreateTableAs(context, *this, op, plan); } return Make(op, op.schema, std::move(op.info), op.estimated_cardinality); diff --git a/src/duckdb/src/execution/physical_plan/plan_cross_product.cpp b/src/duckdb/src/execution/physical_plan/plan_cross_product.cpp index e27b8f6d5..8b2bdf84e 100644 --- a/src/duckdb/src/execution/physical_plan/plan_cross_product.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_cross_product.cpp @@ -6,8 +6,8 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalCrossProduct &op) { D_ASSERT(op.children.size() == 2); - auto &left = CreatePlan(*op.children[0]); - auto &right = CreatePlan(*op.children[1]); + auto &left = CreatePlanRecursive(*op.children[0]); + auto &right = CreatePlanRecursive(*op.children[1]); return Make(op.types, left, right, op.estimated_cardinality); } diff --git a/src/duckdb/src/execution/physical_plan/plan_cte.cpp b/src/duckdb/src/execution/physical_plan/plan_cte.cpp index ec270e45a..57f5884e2 100644 --- a/src/duckdb/src/execution/physical_plan/plan_cte.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_cte.cpp @@ -7,24 +7,11 @@ namespace duckdb { -static bool ContainsRecursiveCTE(const LogicalOperator &op) { - if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { - return true; - } - for (auto &child : op.children) { - if (ContainsRecursiveCTE(*child)) { - return true; - } - } - return false; -} - PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalMaterializedCTE &op) { D_ASSERT(op.children.size() == 2); - auto cte_body_has_side_effects = op.children[0]->HasSideEffects(); - auto use_exchange = planning_recursive_cte_depth == 0 && !ContainsRecursiveCTE(*op.children[0]) && - !ContainsRecursiveCTE(*op.children[1]); + auto cte_body_has_side_effects = GetLogicalProperties(*op.children[0]).has_side_effects; + auto use_exchange = planning_recursive_cte_depth == 0 && !GetLogicalProperties(op).has_recursive_cte; // Create the working_table that the PhysicalCTE will use for evaluation. auto working_table = make_shared_ptr(context, op.children[0]->types); @@ -34,7 +21,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalMaterializedCTE &op) materialized_ctes[op.table_index] = vector>(); // Create the plan for the left side. This is the materialization. - auto &left = CreatePlan(*op.children[0]); + auto &left = CreatePlanRecursive(*op.children[0]); const auto cte_body_order = OrderPreservationRecursive(left); const auto preserve_cte_order = PreserveInsertionOrder(left); const auto use_batch_index = preserve_cte_order && UseBatchIndex(left); @@ -52,7 +39,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalMaterializedCTE &op) } // Initialize an empty vector to collect the scan operators. - auto &right = CreatePlan(*op.children[1]); + auto &right = CreatePlanRecursive(*op.children[1]); auto &cte = Make(op.ctename, op.table_index, right.types, left, right, op.estimated_cardinality); auto &cast_cte = cte.Cast(); diff --git a/src/duckdb/src/execution/physical_plan/plan_distinct.cpp b/src/duckdb/src/execution/physical_plan/plan_distinct.cpp index 319c98d71..24549b24c 100644 --- a/src/duckdb/src/execution/physical_plan/plan_distinct.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_distinct.cpp @@ -14,7 +14,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalDistinct &op) { D_ASSERT(op.children.size() == 1); - reference child = CreatePlan(*op.children[0]); + reference child = CreatePlanRecursive(*op.children[0]); auto &distinct_targets = op.distinct_targets; D_ASSERT(!distinct_targets.empty()); diff --git a/src/duckdb/src/execution/physical_plan/plan_explain.cpp b/src/duckdb/src/execution/physical_plan/plan_explain.cpp index 71ab0ea74..29facabfd 100644 --- a/src/duckdb/src/execution/physical_plan/plan_explain.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_explain.cpp @@ -20,7 +20,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalExplain &op) { if (!analyze && !single_plan) { logical_plan_opt = op.children[0]->ToString(context, op.format); } - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); if (analyze) { auto &explain = Make(op.types, op.format); explain.children.push_back(plan); diff --git a/src/duckdb/src/execution/physical_plan/plan_export.cpp b/src/duckdb/src/execution/physical_plan/plan_export.cpp index 7cdff2341..a23f675b0 100644 --- a/src/duckdb/src/execution/physical_plan/plan_export.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_export.cpp @@ -10,7 +10,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalExport &op) { std::move(op.exported_tables)); // Plan the underlying copy statements, if any. if (!op.children.empty()) { - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); export_op.children.push_back(plan); } return export_op; 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 1765755bd..823b8ffd9 100644 --- a/src/duckdb/src/execution/physical_plan/plan_expression_get.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_expression_get.cpp @@ -8,7 +8,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalExpressionGet &op) { D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); auto &expr_scan = Make(op.types, std::move(op.expressions), op.estimated_cardinality); expr_scan.children.push_back(plan); diff --git a/src/duckdb/src/execution/physical_plan/plan_filter.cpp b/src/duckdb/src/execution/physical_plan/plan_filter.cpp index 796e4aeb3..62a3d5d7c 100644 --- a/src/duckdb/src/execution/physical_plan/plan_filter.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_filter.cpp @@ -12,7 +12,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalFilter &op) { D_ASSERT(op.children.size() == 1); - reference plan = CreatePlan(*op.children[0]); + reference plan = CreatePlanRecursive(*op.children[0]); if (!op.expressions.empty()) { // create a filter if there is anything to filter auto &filter = Make(plan.get().GetTypes(), std::move(op.expressions), op.estimated_cardinality); diff --git a/src/duckdb/src/execution/physical_plan/plan_get.cpp b/src/duckdb/src/execution/physical_plan/plan_get.cpp index 7798cef8f..634eea199 100644 --- a/src/duckdb/src/execution/physical_plan/plan_get.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_get.cpp @@ -31,7 +31,7 @@ unique_ptr MoveTableFilters(TableFilterSet &table_filters) { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalGet &op) { auto column_ids = op.GetColumnIds(); if (!op.children.empty()) { - reference child = ResolveAndPlan(std::move(op.children[0])); + reference child = ResolveAndPlan(*op.children[0]); auto &child_types = child.get().types; // this is for table producing functions that consume subquery results diff --git a/src/duckdb/src/execution/physical_plan/plan_insert.cpp b/src/duckdb/src/execution/physical_plan/plan_insert.cpp index 2846c5d4b..09599a4bf 100644 --- a/src/duckdb/src/execution/physical_plan/plan_insert.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_insert.cpp @@ -144,7 +144,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalInsert &op) { optional_ptr plan; if (!op.children.empty()) { D_ASSERT(op.children.size() == 1); - plan = CreatePlan(*op.children[0]); + plan = CreatePlanRecursive(*op.children[0]); } dependencies.AddDependency(op.table); return op.table.catalog.PlanInsert(context, *this, op, plan); diff --git a/src/duckdb/src/execution/physical_plan/plan_limit.cpp b/src/duckdb/src/execution/physical_plan/plan_limit.cpp index 9aa6e8374..40ef4bebb 100644 --- a/src/duckdb/src/execution/physical_plan/plan_limit.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_limit.cpp @@ -171,7 +171,7 @@ static PhysicalOperator *TryCreateLimitedDistinct(PhysicalPlanGenerator &generat PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalLimit &op) { D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); auto *limit_child = &plan; 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; diff --git a/src/duckdb/src/execution/physical_plan/plan_merge_into.cpp b/src/duckdb/src/execution/physical_plan/plan_merge_into.cpp index 5dcc50b81..4cde5f4b1 100644 --- a/src/duckdb/src/execution/physical_plan/plan_merge_into.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_merge_into.cpp @@ -336,7 +336,7 @@ PhysicalOperator &Catalog::PlanMergeInto(ClientContext &context, PhysicalPlanGen PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalMergeInto &op) { // planning the child consumes its logical operators - estimate the cardinality beforehand op.estimated_cardinality = op.EstimateCardinality(context); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); D_ASSERT(op.children.size() == 1); dependencies.AddDependency(op.table); return op.table.catalog.PlanMergeInto(context, *this, op, plan); diff --git a/src/duckdb/src/execution/physical_plan/plan_order.cpp b/src/duckdb/src/execution/physical_plan/plan_order.cpp index b14860955..5bb2ede1a 100644 --- a/src/duckdb/src/execution/physical_plan/plan_order.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_order.cpp @@ -8,7 +8,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalOrder &op) { D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); if (op.orders.empty()) { return plan; } diff --git a/src/duckdb/src/execution/physical_plan/plan_pivot.cpp b/src/duckdb/src/execution/physical_plan/plan_pivot.cpp index 590c42922..9b7458a1a 100644 --- a/src/duckdb/src/execution/physical_plan/plan_pivot.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_pivot.cpp @@ -6,7 +6,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalPivot &op) { D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); return Make(std::move(op.types), plan, std::move(op.bound_pivot)); } diff --git a/src/duckdb/src/execution/physical_plan/plan_positional_join.cpp b/src/duckdb/src/execution/physical_plan/plan_positional_join.cpp index d972bf612..2bde1e3e7 100644 --- a/src/duckdb/src/execution/physical_plan/plan_positional_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_positional_join.cpp @@ -8,8 +8,8 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalPositionalJoin &op) { D_ASSERT(op.children.size() == 2); - auto &left = CreatePlan(*op.children[0]); - auto &right = CreatePlan(*op.children[1]); + auto &left = CreatePlanRecursive(*op.children[0]); + auto &right = CreatePlanRecursive(*op.children[1]); switch (left.type) { case PhysicalOperatorType::TABLE_SCAN: case PhysicalOperatorType::POSITIONAL_SCAN: diff --git a/src/duckdb/src/execution/physical_plan/plan_projection.cpp b/src/duckdb/src/execution/physical_plan/plan_projection.cpp index 03b198b1d..3e32592df 100644 --- a/src/duckdb/src/execution/physical_plan/plan_projection.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_projection.cpp @@ -7,7 +7,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalProjection &op) { D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); #ifdef DEBUG for (auto &expr : op.expressions) { diff --git a/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp b/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp index e037fd340..281e45ddf 100644 --- a/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp @@ -29,14 +29,14 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalRecursiveCTE &op) { // Add the ColumnDataCollection to the context of this PhysicalPlanGenerator recursive_cte_tables[op.table_index] = working_table; - auto &left = CreatePlan(*op.children[0]); + auto &left = CreatePlanRecursive(*op.children[0]); // If the logical operator has no key targets, then we create a normal recursive CTE operator. if (op.key_targets.empty()) { auto recurring_table = make_shared_ptr(context, op.types); recurring_cte_tables[op.table_index] = recurring_table; planning_recursive_cte_depth++; - auto &right = CreatePlan(*op.children[1]); + auto &right = CreatePlanRecursive(*op.children[1]); planning_recursive_cte_depth--; auto &cte = Make(op.ctename, op.table_index, op.types, op.union_all ? RecursiveCTEMode::UNION_ALL : RecursiveCTEMode::UNION, @@ -156,7 +156,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalRecursiveCTE &op) { } planning_recursive_cte_depth++; - auto &right = CreatePlan(*op.children[1]); + auto &right = CreatePlanRecursive(*op.children[1]); planning_recursive_cte_depth--; auto &cte = Make(op.ctename, op.table_index, op.types, op.union_all ? RecursiveCTEMode::KEY_UNION_ALL : RecursiveCTEMode::KEY_UNION, diff --git a/src/duckdb/src/execution/physical_plan/plan_sample.cpp b/src/duckdb/src/execution/physical_plan/plan_sample.cpp index 4b48c7214..dc5b19c17 100644 --- a/src/duckdb/src/execution/physical_plan/plan_sample.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_sample.cpp @@ -24,7 +24,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalSample &op) { child_cardinality = first_child.EstimateCardinality(context); } - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); if (!op.sample_options->seed.IsValid()) { auto &random_engine = RandomEngine::Get(context); op.sample_options->SetSeed(random_engine.NextSeed32()); diff --git a/src/duckdb/src/execution/physical_plan/plan_secure_view.cpp b/src/duckdb/src/execution/physical_plan/plan_secure_view.cpp index 3cba1a5f4..95628e670 100644 --- a/src/duckdb/src/execution/physical_plan/plan_secure_view.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_secure_view.cpp @@ -6,7 +6,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalSecureView &op) { D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); return Make(plan, op.view_name, op.pushed_filters, op.estimated_cardinality); } diff --git a/src/duckdb/src/execution/physical_plan/plan_set.cpp b/src/duckdb/src/execution/physical_plan/plan_set.cpp index 330093982..9bf4ef53b 100644 --- a/src/duckdb/src/execution/physical_plan/plan_set.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_set.cpp @@ -12,7 +12,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalSet &op) { } // Set a variable. - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); auto &set_variable = Make(op.name, op.estimated_cardinality); set_variable.children.push_back(plan); return set_variable; diff --git a/src/duckdb/src/execution/physical_plan/plan_set_operation.cpp b/src/duckdb/src/execution/physical_plan/plan_set_operation.cpp index 8a109ad4b..e97de7fd7 100644 --- a/src/duckdb/src/execution/physical_plan/plan_set_operation.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_set_operation.cpp @@ -72,10 +72,10 @@ static vector GetComparisonTypes(ClientContext &context, const Logi PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalSetOperation &op) { ArenaLinkedList> children(physical_plan->ArenaRef()); for (auto &child : op.children) { - children.push_back(CreatePlan(*child)); + children.push_back(CreatePlanRecursive(*child)); } - for (idx_t i = 1; i < children.size(); i++) { - if (children[i].get().GetTypes() != children[0].get().GetTypes()) { + for (auto &child : children) { + if (child.get().GetTypes() != children[0].get().GetTypes()) { throw InvalidInputException("Type mismatch for SET OPERATION"); } } 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 index dd82a013e..bc28f9be9 100644 --- a/src/duckdb/src/execution/physical_plan/plan_top_key_filter.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_top_key_filter.cpp @@ -6,7 +6,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalTopKeyFilter &op) { D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*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); diff --git a/src/duckdb/src/execution/physical_plan/plan_top_n.cpp b/src/duckdb/src/execution/physical_plan/plan_top_n.cpp index b2e3d8a9b..dcf66f093 100644 --- a/src/duckdb/src/execution/physical_plan/plan_top_n.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_top_n.cpp @@ -6,7 +6,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalTopN &op) { D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); auto &top_n = Make(context, op.types, std::move(op.orders), NumericCast(op.limit), NumericCast(op.offset), std::move(op.dynamic_filter), op.estimated_cardinality); diff --git a/src/duckdb/src/execution/physical_plan/plan_unnest.cpp b/src/duckdb/src/execution/physical_plan/plan_unnest.cpp index 448b668d6..07e35f0eb 100644 --- a/src/duckdb/src/execution/physical_plan/plan_unnest.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_unnest.cpp @@ -6,7 +6,7 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalUnnest &op) { D_ASSERT(op.children.size() == 1); - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); auto &unnest = Make(op.types, std::move(op.expressions), op.estimated_cardinality); unnest.children.push_back(plan); return unnest; diff --git a/src/duckdb/src/execution/physical_plan/plan_vacuum.cpp b/src/duckdb/src/execution/physical_plan/plan_vacuum.cpp index 4f5eec7d6..fd8a03672 100644 --- a/src/duckdb/src/execution/physical_plan/plan_vacuum.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_vacuum.cpp @@ -10,7 +10,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalVacuum &op) { auto &vacuum = Make(unique_ptr_cast(std::move(op.info)), op.table, std::move(op.column_id_map), op.estimated_cardinality); if (!op.children.empty()) { - auto &plan = CreatePlan(*op.children[0]); + auto &plan = CreatePlanRecursive(*op.children[0]); vacuum.children.push_back(plan); } return vacuum; diff --git a/src/duckdb/src/execution/physical_plan/plan_window.cpp b/src/duckdb/src/execution/physical_plan/plan_window.cpp index ea7874bee..cd48c63ad 100644 --- a/src/duckdb/src/execution/physical_plan/plan_window.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_window.cpp @@ -204,7 +204,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalWindow &op) { const auto bindings = child.GetColumnBindings(); op.estimated_cardinality = op.EstimateCardinality(context); - reference plan = CreatePlan(child); + reference plan = CreatePlanRecursive(child); #ifdef DEBUG for (auto &expr : op.expressions) { D_ASSERT(expr->IsWindow()); diff --git a/src/duckdb/src/execution/physical_plan_generator.cpp b/src/duckdb/src/execution/physical_plan_generator.cpp index 8c9d2723d..9fab4a9fa 100644 --- a/src/duckdb/src/execution/physical_plan_generator.cpp +++ b/src/duckdb/src/execution/physical_plan_generator.cpp @@ -15,6 +15,56 @@ namespace duckdb { +class PhysicalPlanGenerator::LogicalPlanProperties { +public: + explicit LogicalPlanProperties(const LogicalOperator &op) { + Collect(op); + } + + class Scope { + public: + Scope(optional_ptr &active_p, optional_ptr current) + : active(active_p), previous(active_p) { + active = current; + } + ~Scope() { + active = previous; + } + Scope(const Scope &) = delete; + Scope &operator=(const Scope &) = delete; + + private: + optional_ptr &active; + optional_ptr previous; + }; + +public: + LogicalSubtreeProperties Get(const LogicalOperator &op) const { + auto entry = properties.find(op); + D_ASSERT(entry != properties.end()); + return entry->second; + } + +private: + LogicalSubtreeProperties Collect(const LogicalOperator &op) { + LogicalSubtreeProperties result; + result.has_side_effects = op.HasLocalSideEffects(); + result.has_recursive_cte = op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE; + for (auto &child : op.children) { + if (!child) { + continue; + } + auto child_properties = Collect(*child); + result.has_side_effects |= child_properties.has_side_effects; + result.has_recursive_cte |= child_properties.has_recursive_cte; + } + properties.emplace(op, result); + return result; + } + + reference_map_t properties; +}; + PhysicalPlanGenerator::PhysicalPlanGenerator(ClientContext &context) : context(context) { } @@ -22,31 +72,31 @@ PhysicalPlanGenerator::~PhysicalPlanGenerator() { } unique_ptr PhysicalPlanGenerator::Plan(unique_ptr op) { - auto &plan = ResolveAndPlan(std::move(op)); + auto &plan = ResolveAndPlan(*op); plan.Verify(); return std::move(physical_plan); } -PhysicalOperator &PhysicalPlanGenerator::ResolveAndPlan(unique_ptr op) { +PhysicalOperator &PhysicalPlanGenerator::ResolveAndPlan(LogicalOperator &op) { auto &profiler = QueryProfiler::Get(context); // Resolve the types of each operator. { auto timer = profiler.StartTimer(); - op->ResolveOperatorTypes(); + op.ResolveOperatorTypes(); } // Resolve the column references. { auto timer = profiler.StartTimer(); ColumnBindingResolver resolver; - resolver.VisitOperator(*op); + resolver.VisitOperator(op); } // Create the main physical plan. { auto timer = profiler.StartTimer(); - physical_plan = PlanInternal(*op); + physical_plan = PlanInternal(op); } // Return a reference to the root of this plan. @@ -73,12 +123,35 @@ unique_ptr PhysicalPlanGenerator::PlanInternal(LogicalOperator &op } PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalOperator &op) { - const auto repeatable = ClassifyLogicalOperatorRepeatability(op) == LogicalOperatorRepeatability::REPEATABLE; - auto &result = CreatePlanInternal(op); - if (!repeatable) { - non_repeatable_operators.insert(result); + // Callers may have changed the logical tree since an enclosing planning call. + LogicalPlanProperties::Scope scope(logical_properties, nullptr); + return CreatePlanRecursive(op); +} + +PhysicalOperator &PhysicalPlanGenerator::CreatePlanRecursive(LogicalOperator &op) { + const auto locally_repeatable = + ClassifyLogicalOperatorLocalRepeatability(op) == LogicalOperatorRepeatability::REPEATABLE; + auto create_plan = [&]() -> PhysicalOperator & { + const auto repeatable = locally_repeatable && !GetLogicalProperties(op).has_side_effects; + auto &result = CreatePlanInternal(op); + if (!repeatable) { + non_repeatable_operators.insert(result); + } + return result; + }; + const auto needs_properties = locally_repeatable || op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE; + if (needs_properties && !logical_properties) { + LogicalPlanProperties properties(op); + LogicalPlanProperties::Scope scope(logical_properties, properties); + return create_plan(); } - return result; + return create_plan(); +} + +PhysicalPlanGenerator::LogicalSubtreeProperties +PhysicalPlanGenerator::GetLogicalProperties(const LogicalOperator &op) const { + D_ASSERT(logical_properties); + return logical_properties->Get(op); } PhysicalOperator &PhysicalPlanGenerator::CreatePlanInternal(LogicalOperator &op) { diff --git a/src/duckdb/src/function/aggregate/bignum_aggregates.cpp b/src/duckdb/src/function/aggregate/bignum_aggregates.cpp new file mode 100644 index 000000000..7b6d2a43d --- /dev/null +++ b/src/duckdb/src/function/aggregate/bignum_aggregates.cpp @@ -0,0 +1,67 @@ +#include "duckdb/function/aggregate/bignum_aggregates.hpp" + +namespace duckdb { + +void BignumAggregates::WriteBignum(const BignumIntermediate &value, VectorWriter &writer) { + // trimmed like BignumIntermediate::ToBignum, the intermediate itself is only read + auto start = value.GetStartDataPos(); + uint32_t size = value.size - start; + if (size == 0) { + // the value is all sign-extension bytes: keep one of them + start = 0; + size = 1; + } + auto &blob = writer.WriteEmptyString(Bignum::BIGNUM_HEADER_SIZE + size); + auto ptr = blob.GetDataWriteable(); + Bignum::SetHeader(ptr, size, value.is_negative); + memcpy(ptr + Bignum::BIGNUM_HEADER_SIZE, value.data + start, size); + blob.Finalize(); +} + +BignumIntermediate BignumAggregates::ImportBignum(string_t blob, ArenaAllocator &allocator) { + const auto size = blob.GetSize(); + auto header = const_data_ptr_cast(blob.GetData()); + if (size < Bignum::BIGNUM_HEADER_SIZE + 1) { + throw InvalidInputException("Invalid BIGNUM state - the blob is shorter than a header and a byte"); + } + // the header holds the data size, inverted for negative values (see Bignum::SetHeader) + uint32_t data_size = (uint32_t(header[0]) << 16) | (uint32_t(header[1]) << 8) | uint32_t(header[2]); + if ((header[0] & 0x80) == 0) { + data_size = ~data_size; + } + data_size &= 0x7FFFFF; + if (size != data_size + Bignum::BIGNUM_HEADER_SIZE) { + throw InvalidInputException("Invalid BIGNUM state - the header does not match the size of the blob"); + } + auto ptr = allocator.Allocate(size); + memcpy(ptr, blob.GetData(), size); + return BignumIntermediate(ptr, size); +} + +void BignumAggregates::WriteAvgState(const BignumAvgState &state, VectorWriter &count_writer, + VectorWriter &value_writer) { + // the state is only read: it is exported while other threads may still read it + count_writer.WriteValue(state.count); + if (state.count == 0) { + value_writer.WriteNull(); + } else { + WriteBignum(state.value, value_writer); + } +} + +void BignumAggregates::ImportAvgState(BignumAvgState &state, const VectorIterator::ValueEntry &count, + const VectorIterator::ValueEntry &value, ArenaAllocator &allocator, + const char *function_name, const char *value_field) { + if (!count.IsValid() || count.GetValue() == 0) { + // an empty state + return; + } + if (!value.IsValid()) { + throw InvalidInputException("Invalid %s state - the %s cannot be NULL when the count is not 0", function_name, + value_field); + } + state.count = count.GetValue(); + state.value = ImportBignum(value.GetValue(), allocator); +} + +} // namespace duckdb diff --git a/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp b/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp index da1df96af..4fc90abd8 100644 --- a/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp +++ b/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp @@ -1,7 +1,16 @@ +#include "duckdb/common/bignum.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/hugeint.hpp" +#include "duckdb/common/operator/add.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/bignum_decimal.hpp" #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/string_heap.hpp" #include "duckdb/common/types/uhugeint.hpp" +#include "duckdb/common/vector/flat_vector.hpp" +#include "duckdb/common/vector/vector_iterator.hpp" +#include "duckdb/common/vector/vector_writer.hpp" +#include "duckdb/function/aggregate/bignum_aggregates.hpp" #include "duckdb/function/aggregate/distributive_functions.hpp" #include "duckdb/function/aggregate/distributive_function_utils.hpp" #include "duckdb/function/aggregate_function.hpp" @@ -54,10 +63,15 @@ struct DecimalAvgOperation { template static void Combine(const STATE &source, STATE &target, AggregateInputData &) { + // the counts of imported states can be anything, the count of rows of a table cannot overflow + uint64_t count; + if (!TryAddOperator::Operation(target.count, source.count, count)) { + throw OutOfRangeException("Overflow in aggregate state combine"); + } if (!Hugeint::TryAddInPlace(target.sum, source.sum)) { OutOfRangeException::Throw("decimal_average: intermediate sum overflowed HUGEINT range during combine"); } - target.count += source.count; + target.count = count; } // Overload for hugeint_t result: direct assignment. @@ -105,6 +119,80 @@ struct DecimalAvgOperation { } }; +//===--------------------------------------------------------------------===// +// The bignum_t tier: decimals wider than 38 digits +// +// The state is the shared BIGNUM average accumulator (an exact sum and a non-NULL row count); the sum is divided once +// at the end with the rounding of the fixed-size tiers (half to even). The sum has no bound, so this tier cannot +// overflow. +//===--------------------------------------------------------------------===// + +struct WideDecimalAvgOperation : BignumAvgOperation { + template + static void Finalize(STATE &state, RESULT &target, AggregateFinalizeData &finalize_data) { + // the state is only read: it is exported while other threads may still read it + if (state.count == 0) { + finalize_data.ReturnNull(); + return; + } + StringHeap heap; + BignumArithmeticState arithmetic; + const string count_blob = DecimalHelper::FromInteger(uhugeint_t(state.count)); + const bignum_t count_value {string_t(count_blob)}; + const BignumIntermediate divisor(count_value); + // the sum is divided once and rounded half to even, like in the fixed-size tiers + const auto quotient = DecimalHelper::DivideAndRound(state.value, divisor, + DecimalRounding::HALF_TO_EVEN, heap, arithmetic); + // the average of values of the width fits the width, but an imported state can carry any sum + const auto &result_type = finalize_data.result.GetType(); + if (!DecimalHelper::FitsWidth(bignum_t(quotient), DecimalType::GetWidth(result_type))) { + throw OutOfRangeException("decimal_average: the result does not fit in %s", result_type.ToString()); + } + // the result vector owns a copy of the quotient, the scratch heap is released with the finalize + target = bignum_t(finalize_data.ReturnString(quotient)); + } +}; + +//! The states are exported as STRUCT(sum BIGNUM, count UBIGINT), the sum is NULL for an empty state +static AggregateStateLayout WideDecimalAvgStateLayout(AggregateLayoutInput &input) { + return AggregateStateLayout(LogicalType::STRUCT({{"sum", LogicalType::BIGNUM}, {"count", LogicalType::UBIGINT}}), + AlignValue(sizeof(BignumAvgState))); +} + +static void WideDecimalAvgExportState(Vector &state_vector, AggregateFinalizeInputData &, Vector &result, idx_t count, + idx_t offset) { + auto states = state_vector.Values(); + auto writer = FlatVector::Writer>(result, count, offset); + for (idx_t i = 0; i < count; i++) { + writer.WriteValue([&](auto &sum_writer, auto &count_writer) { + BignumAggregates::WriteAvgState(*states[i].GetValue(), count_writer, sum_writer); + }); + } +} + +static void WideDecimalAvgImportState(AggregateImportInputData &input) { + auto entries = input.input_vec.Values>(); + for (idx_t i = 0; i < input.input_vec.size(); i++) { + auto &state = *reinterpret_cast(input.dest_buffer + i * input.layout.total_state_size); + BignumAvgOperation::Initialize(state); + const auto entry = entries[i]; + if (!entry.IsValid()) { + // an empty state + continue; + } + BignumAggregates::ImportAvgState(state, entry.GetChildValue<1>(), entry.GetChildValue<0>(), input.allocator, + "decimal_average", "sum"); + } +} + +static AggregateFunction MakeWideDecimalAvgFunction(const LogicalType &type) { + auto function = + AggregateFunction::UnaryAggregate(type, type); + function.SetFallible(); // the finalize throws when the average of an imported state does not fit the width + function.SetStateExportCallbacks(WideDecimalAvgStateLayout, WideDecimalAvgExportState, WideDecimalAvgImportState); + return function; +} + //===--------------------------------------------------------------------===// // Registration //===--------------------------------------------------------------------===// @@ -159,8 +247,9 @@ static unique_ptr BindDecimalAverage(BindAggregateFunctionInput &i MakeDecimalAvgFunction(LogicalType::DECIMAL(Decimal::MAX_WIDTH_INT128, scale), return_type)); break; case PhysicalType::VARCHAR: - throw NotImplementedException("decimal_average over DECIMAL types wider than %d digits is not supported yet", - Decimal::MAX_WIDTH_INT128); + // decimals wider than 38 digits sum their BIGNUM blobs + function.ReplaceImplementation(MakeWideDecimalAvgFunction(return_type)); + break; default: throw InternalException("decimal_average: unexpected physical type"); } diff --git a/src/duckdb/src/function/aggregate/distributive/minmax.cpp b/src/duckdb/src/function/aggregate/distributive/minmax.cpp index bbdcdd700..7e9647fd0 100644 --- a/src/duckdb/src/function/aggregate/distributive/minmax.cpp +++ b/src/duckdb/src/function/aggregate/distributive/minmax.cpp @@ -468,6 +468,28 @@ class MinMaxNState { static T GetValue(T val) { return val; } + + void ExportSlot(Vector &entries, idx_t entry_idx, idx_t slot, bool nulls_last) const { + VAL_TYPE::Assign(entries, entry_idx, heap.GetSlot(slot).value, nulls_last); + } + + struct ImportData { + ImportData(const Vector &entries, idx_t count, bool nulls_last) + : extra_state(VAL_TYPE::CreateExtraState(count)) { + VAL_TYPE::PrepareData(entries, extra_state, format, nulls_last); + } + + typename VAL_TYPE::EXTRA_STATE extra_state; + UnifiedVectorFormat format; + }; + + void ImportSlot(ArenaAllocator &allocator, const ImportData &entries, idx_t entry_idx, bool reject_nulls) { + const auto idx = entries.format.sel->get_index(entry_idx); + if (reject_nulls && !entries.format.validity.RowIsValid(idx)) { + throw InvalidInputException("Invalid min/max state - the entries cannot be NULL"); + } + heap.AppendSlot(allocator, VAL_TYPE::Create(entries.format, idx)); + } }; template @@ -480,7 +502,7 @@ void MinMaxNUpdate(Vector inputs[], AggregateInputData &aggr_input, idx_t input_ UnifiedVectorFormat n_format; UnifiedVectorFormat state_format; - auto val_extra_state = STATE::VAL_TYPE::CreateExtraState(); + auto val_extra_state = STATE::VAL_TYPE::CreateExtraState(count); STATE::VAL_TYPE::PrepareData(val_vector, val_extra_state, val_format, true); @@ -528,10 +550,11 @@ void SpecializeMinMaxNFunction(BoundAggregateFunction &function) { function.GetCallbacks().SetStateInitCallback( AggregateFunction::StateInitialize); function.GetCallbacks().SetStateCombineCallback(AggregateFunction::StateCombine); - function.GetCallbacks().SetStateDestructorCallback(AggregateFunction::StateDestroy); function.GetCallbacks().SetStateFinalizeCallback(MinMaxNOperation::Finalize); function.GetCallbacks().SetStateUpdateCallback(MinMaxNUpdate); + function.SetExportAggregateStateCallback(MinMaxNOperation::ExportState); + function.SetImportAggregateStateCallback(MinMaxNOperation::ImportState); } template @@ -600,17 +623,32 @@ unique_ptr MinMaxNBind(BindAggregateFunctionInput &input) { // Specialize the function based on the input types SpecializeMinMaxNFunction(val_type, function); + function.GetArguments()[0] = arguments[0]->GetReturnType(); + if (arguments[1]->HasParameter()) { + // n is constant per execution: bind again once its value is known + throw ParameterNotResolvedException(); + } + if (!arguments[1]->IsFoldable()) { + MinMaxNOperation::BindPerRowN(function); + } function.SetReturnType(LogicalType::LIST(arguments[0]->GetReturnType())); return nullptr; } +AggregateStateLayout MinMaxNGetStateType(AggregateLayoutInput &input) { + // EXPORT_STATE rewrites the return type, so derive the entry type from the (bind-resolved) argument instead + return MinMaxNOperation::GetStateType(input, input.function.GetArguments()[0]); +} + template AggregateFunction GetMinMaxNFunction() { AggregateFunction fun({}, LogicalType::LIST(LogicalType::ANY), nullptr, nullptr, nullptr, nullptr, nullptr, FunctionNullHandling::DEFAULT_NULL_HANDLING, nullptr, MinMaxNBind, nullptr); fun.GetSignature().AddParameter("arg", LogicalTypeId::ANY).AddParameter("n", LogicalType::BIGINT); fun.SetUnbindCallback(MinMaxUnbind); + fun.SetStructStateExport(MinMaxNGetStateType); + fun.SetCombineSourceRetention(AggregateCombineSourceRetention::NEVER_RETAINS); fun.SetFallible(); // the update callback rejects NULL and out-of-range n values at runtime return fun; } diff --git a/src/duckdb/src/function/aggregate_function.cpp b/src/duckdb/src/function/aggregate_function.cpp index c3a635f47..d1ccdca11 100644 --- a/src/duckdb/src/function/aggregate_function.cpp +++ b/src/duckdb/src/function/aggregate_function.cpp @@ -48,6 +48,10 @@ AggregateInputData::AggregateInputData(const AggregateObject &aggr, ArenaAllocat allocator_p, combine_type_p) { } +bool AggregateExecutor::CombineNeverRetainsSource(const AggregateInputData &aggr_input_data) { + return aggr_input_data.function.GetCombineSourceRetention() == AggregateCombineSourceRetention::NEVER_RETAINS; +} + AggregateFinalizeInputData::AggregateFinalizeInputData(const BoundAggregateFunction &function_p, optional_ptr bind_data_p, ArenaAllocator &allocator_p, @@ -84,7 +88,8 @@ void AggregateFinalizeInputData::InitializeLocalState() { bool AggregateFunctionProperties::operator==(const AggregateFunctionProperties &rhs) const { return FunctionProperties::operator==(rhs) && order_dependent == rhs.order_dependent && distinct_dependent == rhs.distinct_dependent && single_value_identity == rhs.single_value_identity && - is_holistic == rhs.is_holistic && combine_source_retention == rhs.combine_source_retention; + is_holistic == rhs.is_holistic && combine_source_retention == rhs.combine_source_retention && + can_stream == rhs.can_stream; } bool AggregateFunctionProperties::operator!=(const AggregateFunctionProperties &rhs) const { return !(*this == rhs); diff --git a/src/duckdb/src/function/aggregate_state_serialization.cpp b/src/duckdb/src/function/aggregate_state_serialization.cpp index 1d60d600a..1fede63d9 100644 --- a/src/duckdb/src/function/aggregate_state_serialization.cpp +++ b/src/duckdb/src/function/aggregate_state_serialization.cpp @@ -336,12 +336,13 @@ static void DeserializeField(const LogicalType &type, const AggregateStateField } // namespace void AggregateStateSerialization::DeserializeStates(const BoundAggregateFunction &aggr, + optional_ptr bind_data, const AggregateStateLayout &layout, const Vector &input_vec, idx_t count, data_ptr_t dest_buffer, ArenaAllocator &allocator, StateMemoryOwnership ownership) { if (aggr.HasImportAggregateStateCallback()) { // the aggregate explicitly deserializes its own states, copying all variable size data - AggregateImportInputData import_input(layout, input_vec, dest_buffer, allocator); + AggregateImportInputData import_input(layout, input_vec, dest_buffer, allocator, bind_data); aggr.GetImportAggregateStateCallback()(import_input); return; } diff --git a/src/duckdb/src/function/built_in_functions.cpp b/src/duckdb/src/function/built_in_functions.cpp index eb345dc51..2393e3e47 100644 --- a/src/duckdb/src/function/built_in_functions.cpp +++ b/src/duckdb/src/function/built_in_functions.cpp @@ -134,6 +134,9 @@ void BuiltinFunctions::RegisterExtensionOverloads() { // do not insert auto loading placeholders when generating extension entries return; #endif + if (!DBConfig::GetConfig(catalog.GetDatabase()).options.register_extension_overloads) { + return; + } ScalarFunctionSet current_set; for (auto &entry : EXTENSION_FUNCTION_OVERLOADS) { if (entry.type != CatalogType::SCALAR_FUNCTION_ENTRY) { diff --git a/src/duckdb/src/function/builtin_encodings.cpp b/src/duckdb/src/function/builtin_encodings.cpp index 32661f004..ac75f2122 100644 --- a/src/duckdb/src/function/builtin_encodings.cpp +++ b/src/duckdb/src/function/builtin_encodings.cpp @@ -55,9 +55,12 @@ void DecodeLatin1ToUTF8(const char *input, idx_t input_size, bool is_last, char written = out; } +template uint16_t LoadUTF16(const char *input, idx_t pos) { - return static_cast(static_cast(input[pos]) | - (static_cast(input[pos + 1]) << 8)); + const auto first = static_cast(input[pos]); + const auto second = static_cast(input[pos + 1]); + return BIG_ENDIAN_ORDER ? static_cast((first << 8) | second) + : static_cast(first | (second << 8)); } void EncodeUTF8ToLatin1(const char *input, idx_t input_size, char *output, idx_t &written) { @@ -90,12 +93,13 @@ void EncodeUTF8ToLatin1(const char *input, idx_t input_size, char *output, idx_t written = out; } +template void EncodeUTF8ToUTF16(const char *input, idx_t input_size, char *output, idx_t &written) { idx_t out = 0; idx_t pos = 0; auto store = [&](uint16_t unit) { - output[out++] = static_cast(unit & 0xFF); - output[out++] = static_cast(unit >> 8); + output[out++] = static_cast(BIG_ENDIAN_ORDER ? unit >> 8 : unit & 0xFF); + output[out++] = static_cast(BIG_ENDIAN_ORDER ? unit & 0xFF : unit >> 8); }; while (pos < input_size) { const auto lead = static_cast(input[pos]); @@ -135,14 +139,15 @@ void EncodeUTF8ToUTF16(const char *input, idx_t input_size, char *output, idx_t written = out; } +template void DecodeUTF16ToUTF8(const char *input, idx_t input_size, bool is_last, char *output, idx_t &consumed, idx_t &written) { 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) { + // Narrow 4 little-endian ASCII code units at a time + while (!BIG_ENDIAN_ORDER && pos + 8 <= input_size) { uint64_t word; memcpy(&word, input + pos, sizeof(word)); const uint64_t high_bits = word & 0xFF80FF80FF80FF80ULL; @@ -171,7 +176,7 @@ void DecodeUTF16ToUTF8(const char *input, idx_t input_size, bool is_last, char * } break; } - const uint16_t ch = LoadUTF16(input, pos); + const uint16_t ch = LoadUTF16(input, pos); if (ch >= 0xD800 && ch <= 0xDFFF) { if (ch >= 0xDC00) { // low surrogate without a preceding high surrogate @@ -184,7 +189,7 @@ void DecodeUTF16ToUTF8(const char *input, idx_t input_size, bool is_last, char * // the low surrogate follows in the next buffer break; } - const uint16_t low = LoadUTF16(input, pos + 2); + const uint16_t low = LoadUTF16(input, pos + 2); if (low < 0xDC00 || low > 0xDFFF) { throw InvalidInputException("Input is not valid UTF-16"); } @@ -212,6 +217,25 @@ void DecodeUTF16ToUTF8(const char *input, idx_t input_size, bool is_last, char * written = out; } +void DecodeUTF16WithBOMToUTF8(const char *input, idx_t input_size, bool is_last, char *output, idx_t &consumed, + idx_t &written) { + // A byte order mark picks the byte order and is dropped, without one utf-16 is little-endian + const uint16_t mark = input_size >= 2 ? LoadUTF16(input, 0) : 0; + if (mark == 0xFEFF) { + DecodeUTF16ToUTF8(input + 2, input_size - 2, is_last, output, consumed, written); + } else if (mark == 0xFFFE) { + DecodeUTF16ToUTF8(input + 2, input_size - 2, is_last, output, consumed, written); + } else { + DecodeUTF16ToUTF8(input, input_size, is_last, output, consumed, written); + return; + } + consumed += 2; +} + +Value ByteOrderMark(const string &mark, const string &encoding) { + return Value::STRUCT({{"mark", Value::BLOB_RAW(mark)}, {"encoding", Value(encoding)}}); +} + } // namespace void BuiltinFunctions::RegisterEncodingFunctions() { @@ -231,13 +255,31 @@ void BuiltinFunctions::RegisterEncodingFunctions() { }; decode_t utf16_decode = [](const char *input, idx_t input_size, bool is_last, char *output, idx_t &consumed, idx_t &written) { - DecodeUTF16ToUTF8(input, input_size, is_last, output, consumed, written); + DecodeUTF16WithBOMToUTF8(input, input_size, is_last, output, consumed, written); + }; + decode_t utf16_le_decode = [](const char *input, idx_t input_size, bool is_last, char *output, idx_t &consumed, + idx_t &written) { + DecodeUTF16ToUTF8(input, input_size, is_last, output, consumed, written); + }; + encode_t utf16_le_encode = [](const char *input, idx_t input_size, char *output, idx_t &written) { + EncodeUTF8ToUTF16(input, input_size, output, written); + }; + decode_t utf16_be_decode = [](const char *input, idx_t input_size, bool is_last, char *output, idx_t &consumed, + idx_t &written) { + DecodeUTF16ToUTF8(input, input_size, is_last, output, consumed, written); }; - encode_t utf16_encode = [](const char *input, idx_t input_size, char *output, idx_t &written) { - EncodeUTF8ToUTF16(input, input_size, output, written); + encode_t utf16_be_encode = [](const char *input, idx_t input_size, char *output, idx_t &written) { + EncodeUTF8ToUTF16(input, input_size, output, written); }; - for (auto &set : {EncodingFunction::Create("latin-1", latin1_decode, latin1_encode, 1, 2), - EncodingFunction::Create("utf-16", utf16_decode, utf16_encode, 4, 2)}) { + auto utf16 = EncodingFunction::Create("utf-16", utf16_decode, utf16_le_encode, 4, 2); + // A stream is decoded with a fixed byte order, picked by the byte order mark at its start + auto byte_order_marks = Value::LIST({ByteOrderMark("\xFE\xFF", "utf-16be"), ByteOrderMark("", "utf-16le")}); + utf16.ApplyToFunctions([&](ScalarFunction &function) { + function.GetProperties().SetProperty(EncodingFunction::BYTE_ORDER_MARKS_PROPERTY, byte_order_marks); + }); + for (auto &set : {EncodingFunction::Create("latin-1", latin1_decode, latin1_encode, 1, 2), utf16, + EncodingFunction::Create("utf-16le", utf16_le_decode, utf16_le_encode, 4, 2), + EncodingFunction::Create("utf-16be", utf16_be_decode, utf16_be_encode, 4, 2)}) { CreateScalarFunctionInfo info(set); EncodingFunction::SetSchema(info); info.internal = true; diff --git a/src/duckdb/src/function/cast/cast_statistics.cpp b/src/duckdb/src/function/cast/cast_statistics.cpp index c5de33e71..d945f7000 100644 --- a/src/duckdb/src/function/cast/cast_statistics.cpp +++ b/src/duckdb/src/function/cast/cast_statistics.cpp @@ -274,6 +274,27 @@ static unique_ptr StatisticsPropagateArrayToList(const BaseStati return result.ToUnique(); } +static unique_ptr StatisticsPropagateListToList(const BaseStatistics &input, const LogicalType &source, + const LogicalType &target) { + D_ASSERT(source.id() == LogicalTypeId::LIST && target.id() == LogicalTypeId::LIST); + if (input.GetStatsType() != StatisticsType::LIST_STATS) { + return nullptr; + } + if (source == target) { + return input.Copy().ToUnique(); + } + // casting the elements keeps the length of the lists + auto result = ListStats::CreateUnknown(target); + result.CopyValidity(input); + ListStats::SetLengthData(result, ListStats::GetLengthData(input)); + auto child_stats = CastStatistics::TryPropagate(ListStats::GetChildStats(input), ListType::GetChildType(source), + ListType::GetChildType(target)); + if (child_stats) { + ListStats::SetChildStats(result, std::move(child_stats)); + } + return result.ToUnique(); +} + unique_ptr CastStatistics::TryPropagate(const BaseStatistics &stats, const LogicalType &source, const LogicalType &target) { if (source.id() == LogicalTypeId::VARIANT) { @@ -295,6 +316,9 @@ unique_ptr CastStatistics::TryPropagate(const BaseStatistics &st if (source.id() == LogicalTypeId::ARRAY && target.id() == LogicalTypeId::LIST) { return StatisticsPropagateArrayToList(stats, source, target); } + if (source.id() == LogicalTypeId::LIST && target.id() == LogicalTypeId::LIST) { + return StatisticsPropagateListToList(stats, source, target); + } if (!CanPropagate(source, target)) { return nullptr; } diff --git a/src/duckdb/src/function/cast/variant/to_json.cpp b/src/duckdb/src/function/cast/variant/to_json.cpp index 640b9f03e..a49c8087d 100644 --- a/src/duckdb/src/function/cast/variant/to_json.cpp +++ b/src/duckdb/src/function/cast/variant/to_json.cpp @@ -180,7 +180,8 @@ struct JSONConverter : JSONConverterBase { static yyjson_mut_val *VisitObject(const UnifiedVariantVectorData &variant, idx_t row, const VariantNestedData &nested_data, idx_t depth, yyjson_mut_doc *doc) { auto obj = yyjson_mut_obj(doc); - auto object_items = VariantVisitor::VisitObjectItems(variant, row, nested_data, depth, doc); + auto object_items = VariantVisitor::VisitObjectItems(variant, row, nested_data, depth, + VariantIterationOrder::LEXICOGRAPHIC, doc); for (auto &entry : object_items) { yyjson_mut_obj_put(obj, yyjson_mut_strncpy(doc, entry.first.c_str(), entry.first.size()), entry.second); } diff --git a/src/duckdb/src/function/function_list.cpp b/src/duckdb/src/function/function_list.cpp index 9ca5a91bd..e7be5679b 100644 --- a/src/duckdb/src/function/function_list.cpp +++ b/src/duckdb/src/function/function_list.cpp @@ -241,6 +241,7 @@ static const StaticFunctionDefinition function[] = { DUCKDB_SCALAR_FUNCTION_SET(SetvalFun), DUCKDB_SCALAR_FUNCTION_SET(SHA1Fun), DUCKDB_SCALAR_FUNCTION_SET(SHA256Fun), + DUCKDB_SCALAR_FUNCTION(ShareTransaction), DUCKDB_SCALAR_FUNCTION_ALIAS(SplitFun), DUCKDB_SCALAR_FUNCTION_SET_ALIAS(StAsbinaryFun), DUCKDB_SCALAR_FUNCTION_SET(StAstextFun), diff --git a/src/duckdb/src/function/scalar/list/list_resize.cpp b/src/duckdb/src/function/scalar/list/list_resize.cpp index 07d7ff2e7..dd7f9fdd6 100644 --- a/src/duckdb/src/function/scalar/list/list_resize.cpp +++ b/src/duckdb/src/function/scalar/list/list_resize.cpp @@ -5,6 +5,8 @@ #include "duckdb/function/scalar_function.hpp" #include "duckdb/function/built_in_functions.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" +#include "duckdb/storage/statistics/list_stats.hpp" +#include "duckdb/storage/statistics/numeric_stats.hpp" namespace duckdb { @@ -122,6 +124,22 @@ static void ListResizeResolveTypes(ResolveScalarFunctionTypesInput &input) { bound_function.SetReturnType(list_type); } +//! The resized lists have the requested size, which is zero if it is NULL +static unique_ptr ListResizeStats(ClientContext &context, FunctionStatisticsInput &input) { + auto &return_type = input.expr.GetReturnType(); + auto &size_stats = input.child_stats[1]; + if (return_type.id() != LogicalTypeId::LIST || size_stats.GetType().id() != LogicalTypeId::UBIGINT || + size_stats.GetStatsType() != StatisticsType::NUMERIC_STATS || !NumericStats::HasMinMax(size_stats)) { + return nullptr; + } + auto min_size = NumericStats::GetMin(size_stats); + auto max_size = NumericStats::GetMax(size_stats); + auto result = ListStats::CreateUnknown(return_type); + result.CopyValidity(input.child_stats[0]); + ListStats::SetLengthBounds(result, size_stats.CanHaveNull() ? 0 : min_size, max_size); + return result.ToUnique(); +} + ScalarFunctionSet ListResizeFun::GetFunctions() { ScalarFunction simple_fun({}, LogicalType::LIST(LogicalTypeId::ANY), ListResizeFunction, VariableReturnBindData::Bind); @@ -131,6 +149,7 @@ ScalarFunctionSet ListResizeFun::GetFunctions() { simple_fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); simple_fun.SetFallible(); simple_fun.SetResolveTypesCallback(ListResizeResolveTypes); + simple_fun.SetStatisticsCallback(ListResizeStats); ScalarFunction default_value_fun({}, LogicalType::LIST(LogicalTypeId::ANY), ListResizeFunction, VariableReturnBindData::Bind); default_value_fun.GetSignature() @@ -140,6 +159,7 @@ ScalarFunctionSet ListResizeFun::GetFunctions() { default_value_fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); default_value_fun.SetFallible(); default_value_fun.SetResolveTypesCallback(ListResizeResolveTypes); + default_value_fun.SetStatisticsCallback(ListResizeStats); ScalarFunctionSet list_resize_set("list_resize"); list_resize_set.AddFunction(simple_fun); list_resize_set.AddFunction(default_value_fun); diff --git a/src/duckdb/src/function/scalar/list/list_select.cpp b/src/duckdb/src/function/scalar/list/list_select.cpp index f12bb84a8..b8f0bfcd7 100644 --- a/src/duckdb/src/function/scalar/list/list_select.cpp +++ b/src/duckdb/src/function/scalar/list/list_select.cpp @@ -5,6 +5,7 @@ #include "duckdb/planner/expression/bound_parameter_expression.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/function/scalar/list_functions.hpp" +#include "duckdb/storage/statistics/list_stats.hpp" namespace duckdb { @@ -168,6 +169,31 @@ void ListSelectFunction(const DataChunk &args, ExpressionState &state, Vector &r } } +//! A selected list has an element for each index (list_select) or for each true mask entry (list_where) +template +unique_ptr ListSelectStats(ClientContext &context, FunctionStatisticsInput &input) { + auto &value_stats = input.child_stats[0]; + auto &selection_stats = input.child_stats[1]; + auto &return_type = input.expr.GetReturnType(); + if (value_stats.GetStatsType() != StatisticsType::LIST_STATS || + selection_stats.GetStatsType() != StatisticsType::LIST_STATS || value_stats.GetType() != return_type) { + return nullptr; + } + auto result = ListStats::CreateUnknown(return_type); + result.CopyValidity(value_stats); + if (selection_stats.CanHaveNull()) { + result.SetHasNull(); + } + // entries that are out of range are NULL + auto child_stats = ListStats::GetChildStats(value_stats).Copy(); + child_stats.SetHasNull(); + ListStats::SetChildStats(result, child_stats.ToUnique()); + auto max_length = ListStats::MaxListLength(selection_stats); + auto min_length = SELECT_EVERY_ENTRY ? ListStats::MinListLength(selection_stats) : optional_idx(0); + ListStats::SetLengthBounds(result, min_length, max_length); + return result.ToUnique(); +} + } // namespace ScalarFunction ListWhereFun::GetFunction() { @@ -178,6 +204,7 @@ ScalarFunction ListWhereFun::GetFunction() { .AddParameter("mask_list", LogicalType::LIST(LogicalType::BOOLEAN)); // throws if the selection list contains NULL values fun.SetFallible(); + fun.SetStatisticsCallback(ListSelectStats); return fun; } @@ -189,6 +216,7 @@ ScalarFunction ListSelectFun::GetFunction() { .AddParameter("index_list", LogicalType::LIST(LogicalType::BIGINT)); // throws if the selection list contains NULL values fun.SetFallible(); + fun.SetStatisticsCallback(ListSelectStats); return fun; } diff --git a/src/duckdb/src/function/scalar/operator/arithmetic.cpp b/src/duckdb/src/function/scalar/operator/arithmetic.cpp index 55cded9ed..06d93cc6f 100644 --- a/src/duckdb/src/function/scalar/operator/arithmetic.cpp +++ b/src/duckdb/src/function/scalar/operator/arithmetic.cpp @@ -27,6 +27,7 @@ #include "duckdb/function/scalar/operator_functions.hpp" #include "duckdb/function/scalar/string_functions.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/optimizer/statistics_propagator.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/storage/statistics/base_statistics.hpp" #include "duckdb/storage/statistics/numeric_stats.hpp" @@ -608,6 +609,22 @@ static void BignumNegate(DataChunk &args, ExpressionState &state, Vector &result }); } +//! TIMESTAMP[_SEC/_MS/_NS] +/- INTERVAL is not monotonic in the timestamp in general (calendar-month +//! arithmetic clamps the day but keeps the time), but a constant interval without a month component is +//! a fixed duration, which keeps the result strictly increasing in the timestamp argument. +static unique_ptr BindTimestampIntervalArithmetic(BindScalarFunctionInput &input) { + auto &function = input.GetBoundFunction(); + const idx_t interval_idx = function.GetArguments()[0].id() == LogicalTypeId::INTERVAL ? 0 : 1; + auto interval = input.TryGetConstant(interval_idx); + if (!interval || interval->IsNull() || interval->GetValue().months != 0) { + return nullptr; + } + function.SetArgProperties(1 - interval_idx, ArgProperties().StrictlyIncreasing()); + // The smallest finite timestamp sorts below -infinity, so bounds may only be derived from finite ranges. + function.SetStatisticsCallback(StatisticsPropagator::PropagateFiniteMonotoneBounds); + return nullptr; +} + ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const LogicalType &right_type) { const auto inc = ArgProperties().StrictlyIncreasing(); const auto unset = ArgProperties(); @@ -723,32 +740,36 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi ScalarFunction function("+", {left_type, right_type}, LogicalType::TIMESTAMP, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: adding months clamps the day but keeps the time, e.g. + // not monotonic in general: adding months clamps the day but keeps the time, e.g. // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } else if (right_type.id() == LogicalTypeId::TIMESTAMP_SEC) { ScalarFunction function( "+", {left_type, right_type}, LogicalType::TIMESTAMP, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: adding months clamps the day but keeps the time, e.g. + // not monotonic in general: adding months clamps the day but keeps the time, e.g. // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } else if (right_type.id() == LogicalTypeId::TIMESTAMP_MS) { ScalarFunction function( "+", {left_type, right_type}, LogicalType::TIMESTAMP, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: adding months clamps the day but keeps the time, e.g. + // not monotonic in general: adding months clamps the day but keeps the time, e.g. // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } else if (right_type.id() == LogicalTypeId::TIMESTAMP_NS) { ScalarFunction function( "+", {left_type, right_type}, LogicalType::TIMESTAMP_NS, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: adding months clamps the day but keeps the time, e.g. + // not monotonic in general: adding months clamps the day but keeps the time, e.g. // '2000-01-30 23:00' + INTERVAL '1 month' > '2000-01-31 01:00' + INTERVAL '1 month' + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } break; @@ -785,7 +806,8 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi "+", {left_type, right_type}, LogicalType::TIMESTAMP, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: see INTERVAL + TIMESTAMP_SEC + // not monotonic in general: see INTERVAL + TIMESTAMP_SEC + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } break; @@ -795,7 +817,8 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi "+", {left_type, right_type}, LogicalType::TIMESTAMP, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: see INTERVAL + TIMESTAMP_MS + // not monotonic in general: see INTERVAL + TIMESTAMP_MS + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } break; @@ -804,7 +827,8 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi ScalarFunction function("+", {left_type, right_type}, LogicalType::TIMESTAMP, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: see INTERVAL + TIMESTAMP + // not monotonic in general: see INTERVAL + TIMESTAMP + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } break; @@ -814,7 +838,8 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi "+", {left_type, right_type}, LogicalType::TIMESTAMP_NS, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: see INTERVAL + TIMESTAMP + // not monotonic in general: see INTERVAL + TIMESTAMP + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } break; @@ -1078,9 +1103,9 @@ ScalarFunction SubtractFunction::GetFunction(const LogicalType &left_type, const "-", {left_type, right_type}, LogicalType::TIMESTAMP, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: subtracting months clamps the day but keeps the time, e.g. + // not monotonic in general: subtracting months clamps the day but keeps the time, e.g. // '2000-03-30 23:00' - INTERVAL '1 month' > '2000-03-31 01:00' - INTERVAL '1 month' - + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } break; @@ -1090,9 +1115,9 @@ ScalarFunction SubtractFunction::GetFunction(const LogicalType &left_type, const "-", {left_type, right_type}, LogicalType::TIMESTAMP, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: subtracting months clamps the day but keeps the time, e.g. + // not monotonic in general: subtracting months clamps the day but keeps the time, e.g. // '2000-03-30 23:00' - INTERVAL '1 month' > '2000-03-31 01:00' - INTERVAL '1 month' - + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } break; @@ -1102,9 +1127,9 @@ ScalarFunction SubtractFunction::GetFunction(const LogicalType &left_type, const "-", {left_type, right_type}, LogicalType::TIMESTAMP, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: subtracting months clamps the day but keeps the time, e.g. + // not monotonic in general: subtracting months clamps the day but keeps the time, e.g. // '2000-03-30 23:00' - INTERVAL '1 month' > '2000-03-31 01:00' - INTERVAL '1 month' - + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } break; @@ -1114,9 +1139,9 @@ ScalarFunction SubtractFunction::GetFunction(const LogicalType &left_type, const "-", {left_type, right_type}, LogicalType::TIMESTAMP_NS, ScalarFunction::BinaryFunction); function.SetFallible(); - // not monotonic: subtracting months clamps the day but keeps the time, e.g. + // not monotonic in general: subtracting months clamps the day but keeps the time, e.g. // '2000-03-30 23:00' - INTERVAL '1 month' > '2000-03-31 01:00' - INTERVAL '1 month' - + function.SetBindCallback(BindTimestampIntervalArithmetic); return function; } break; diff --git a/src/duckdb/src/function/scalar/string/concat.cpp b/src/duckdb/src/function/scalar/string/concat.cpp index 02984ec56..f0e3d562d 100644 --- a/src/duckdb/src/function/scalar/string/concat.cpp +++ b/src/duckdb/src/function/scalar/string/concat.cpp @@ -364,6 +364,19 @@ unique_ptr ListConcatStats(ClientContext &context, FunctionStati return stats; } +//! The concat function and operator concatenate lists if their arguments are lists +unique_ptr ConcatStats(ClientContext &context, FunctionStatisticsInput &input) { + if (input.expr.GetReturnType().id() != LogicalTypeId::LIST) { + return nullptr; + } + for (auto &child : input.child_stats) { + if (child.GetStatsType() != StatisticsType::LIST_STATS) { + return nullptr; + } + } + return ListConcatStats(context, input); +} + } // namespace ScalarFunction ListConcatFun::GetFunction() { @@ -392,6 +405,7 @@ ScalarFunction ConcatFun::GetFunction() { concat.SetResolveTypesCallback(ConcatFunctionResolveTypes); concat.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); concat.SetInitStateCallback(InitConcatState); + concat.SetStatisticsCallback(ConcatStats); return concat; } @@ -399,6 +413,7 @@ ScalarFunction ConcatOperatorFun::GetFunction() { ScalarFunction concat_op = ScalarFunction("||", {}, LogicalType::ANY, ConcatFunction, BindConcatOperator); concat_op.GetSignature().AddParameter("arg1", LogicalType::ANY).AddParameter("arg2", LogicalType::ANY); concat_op.SetResolveTypesCallback(ConcatOperatorResolveTypes); + concat_op.SetStatisticsCallback(ConcatStats); return concat_op; } diff --git a/src/duckdb/src/function/scalar/system/aggregate_export.cpp b/src/duckdb/src/function/scalar/system/aggregate_export.cpp index f56078049..438d04474 100644 --- a/src/duckdb/src/function/scalar/system/aggregate_export.cpp +++ b/src/duckdb/src/function/scalar/system/aggregate_export.cpp @@ -145,8 +145,8 @@ void AggregateStateFinalize(DataChunk &input, ExpressionState &state_p, Vector & state_vec_writer.WriteValue(state_ptr); } - AggregateStateSerialization::DeserializeStates(bind_data.aggr, layout, input.data[0], count, - local_state.state_buffer.get(), local_state.allocator, + AggregateStateSerialization::DeserializeStates(bind_data.aggr, bind_data.bind_data.get(), layout, input.data[0], + count, local_state.state_buffer.get(), local_state.allocator, StateMemoryOwnership::BORROWED); AggregateFinalizeInputData aggr_input_data(bind_data.aggr, bind_data.bind_data.get(), local_state.allocator); @@ -197,11 +197,11 @@ void AggregateStateCombine(DataChunk &input, ExpressionState &state_p, Vector &r } // Deserialize both inputs — null rows are skipped by LoadOp, keeping the initialized empty state - AggregateStateSerialization::DeserializeStates(bind_data.aggr, layout, input.data[0], count, - local_state.state_buffer0.get(), local_state.allocator, + AggregateStateSerialization::DeserializeStates(bind_data.aggr, bind_data.bind_data.get(), layout, input.data[0], + count, local_state.state_buffer0.get(), local_state.allocator, StateMemoryOwnership::BORROWED); - AggregateStateSerialization::DeserializeStates(bind_data.aggr, layout, input.data[1], count, - local_state.state_buffer1.get(), local_state.allocator, + AggregateStateSerialization::DeserializeStates(bind_data.aggr, bind_data.bind_data.get(), layout, input.data[1], + count, local_state.state_buffer1.get(), local_state.allocator, StateMemoryOwnership::BORROWED); AggregateInputData aggr_input_data(bind_data.aggr, bind_data.bind_data.get(), local_state.allocator, @@ -555,8 +555,9 @@ void CombineAggrUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx } auto &source_allocator = scratch ? *scratch : aggr_input_data.allocator; try { - AggregateStateSerialization::DeserializeStates(underlying_aggr, layout, inputs[0], count, temp_state_buf.get(), - source_allocator, StateMemoryOwnership::BORROWED); + AggregateStateSerialization::DeserializeStates(underlying_aggr, bind_data.bind_data.get(), layout, inputs[0], + count, temp_state_buf.get(), source_allocator, + StateMemoryOwnership::BORROWED); AggregateInputData combine_input(bind_data.aggr, bind_data.bind_data.get(), aggr_input_data.allocator, AggregateCombineType::ALLOW_DESTRUCTIVE); if (input_count == 2) { @@ -941,21 +942,19 @@ void ExportAggregateFunction::GetSortedStateOrders(const LogicalType &state_type ParseOrderBys(order_entry->second, StructType::GetChildTypes(buffer_struct).size(), orders); } -bool ExportAggregateFunction::TryGetCombinedStateLayout(const BoundAggregateFunction &function, - optional_ptr bind_data, - AggregateStateLayout &layout) { +unique_ptr +ExportAggregateFunction::TryGetCombinedStateSerializer(const BoundAggregateFunction &function, + optional_ptr bind_data) { if (!bind_data || function.GetStateCombineCallback() != CombineAggrStateCombine) { - return false; + return nullptr; } auto &combine_data = bind_data->Cast(); auto &aggr = combine_data.aggr; - // states with explicit export / import callbacks are not described by their field layout alone - if (!aggr.HasGetStateTypeCallback() || aggr.HasExportAggregateStateCallback() || - aggr.HasImportAggregateStateCallback()) { - return false; + if (!aggr.HasGetStateTypeCallback()) { + return nullptr; } - layout = aggr.GetStateType(combine_data.bind_data.get()); - return true; + return make_uniq(aggr.GetStateType(combine_data.bind_data.get()), aggr, + combine_data.bind_data.get()); } void ExportAggregateFunction::SetStateExport(BoundAggregateExpression &aggregate, LogicalType state_layout) { diff --git a/src/duckdb/src/function/scalar/system/share_transaction.cpp b/src/duckdb/src/function/scalar/system/share_transaction.cpp new file mode 100644 index 000000000..31dd04e0a --- /dev/null +++ b/src/duckdb/src/function/scalar/system/share_transaction.cpp @@ -0,0 +1,27 @@ +#include "duckdb/function/scalar/system_functions.hpp" +#include "duckdb/execution/expression_executor.hpp" +#include "duckdb/common/types/value.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/transaction/transaction_context.hpp" + +namespace duckdb { + +namespace { + +void ShareTransactionFunction(DataChunk &args, ExpressionState &state, Vector &result) { + auto context = state.GetContext().TryGetClientContext(); + if (!context) { + throw InvalidInputException("share_transaction requires a client connection"); + } + auto share_id = context->transaction.ShareTransaction(); + result.Reference(Value(share_id), count_t(args.size())); +} + +} // namespace + +ScalarFunction ShareTransaction::GetFunction() { + return ScalarFunction({}, LogicalType::VARCHAR, ShareTransactionFunction, nullptr, nullptr, nullptr, + LogicalType(LogicalTypeId::INVALID), FunctionStability::VOLATILE); +} + +} // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_columns.cpp b/src/duckdb/src/function/table/system/duckdb_columns.cpp index 300ca954d..cf2122bc1 100644 --- a/src/duckdb/src/function/table/system/duckdb_columns.cpp +++ b/src/duckdb/src/function/table/system/duckdb_columns.cpp @@ -75,13 +75,13 @@ static unique_ptr DuckDBColumnsBind(ClientContext &context, TableF return_types.emplace_back(LogicalType::INTEGER); names.emplace_back("numeric_precision"); - return_types.emplace_back(LogicalType::INTEGER); + return_types.emplace_back(LogicalType::BIGINT); names.emplace_back("numeric_precision_radix"); return_types.emplace_back(LogicalType::INTEGER); names.emplace_back("numeric_scale"); - return_types.emplace_back(LogicalType::INTEGER); + return_types.emplace_back(LogicalType::BIGINT); names.emplace_back("tags"); return_types.emplace_back(LogicalType::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR)); @@ -289,11 +289,11 @@ void ColumnHelper::WriteColumns(idx_t start_col, idx_t end_col, DataChunk &outpu auto &data_type_id = output.data[13]; // character_maximum_length, INTEGER auto &character_maximum_length = output.data[14]; - // numeric_precision, INTEGER + // numeric_precision, BIGINT auto &numeric_precision_col = output.data[15]; // numeric_precision_radix, INTEGER auto &numeric_precision_radix_col = output.data[16]; - // numeric_scale, INTEGER + // numeric_scale, BIGINT auto &numeric_scale_col = output.data[17]; // tags, MAP(VARCHAR, VARCHAR) auto &tags = output.data[18]; @@ -326,43 +326,43 @@ void ColumnHelper::WriteColumns(idx_t start_col, idx_t end_col, DataChunk &outpu Value numeric_precision, numeric_scale, numeric_precision_radix; switch (type.id()) { case LogicalTypeId::DECIMAL: - numeric_precision = Value::INTEGER(NumericCast(DecimalType::GetWidth(type))); - numeric_scale = Value::INTEGER(NumericCast(DecimalType::GetScale(type))); + numeric_precision = Value::BIGINT(NumericCast(DecimalType::GetWidth(type))); + numeric_scale = Value::BIGINT(NumericCast(DecimalType::GetScale(type))); numeric_precision_radix = Value::INTEGER(10); break; case LogicalTypeId::HUGEINT: - numeric_precision = Value::INTEGER(128); - numeric_scale = Value::INTEGER(0); + numeric_precision = Value::BIGINT(128); + numeric_scale = Value::BIGINT(0); numeric_precision_radix = Value::INTEGER(2); break; case LogicalTypeId::BIGINT: - numeric_precision = Value::INTEGER(64); - numeric_scale = Value::INTEGER(0); + numeric_precision = Value::BIGINT(64); + numeric_scale = Value::BIGINT(0); numeric_precision_radix = Value::INTEGER(2); break; case LogicalTypeId::INTEGER: - numeric_precision = Value::INTEGER(32); - numeric_scale = Value::INTEGER(0); + numeric_precision = Value::BIGINT(32); + numeric_scale = Value::BIGINT(0); numeric_precision_radix = Value::INTEGER(2); break; case LogicalTypeId::SMALLINT: - numeric_precision = Value::INTEGER(16); - numeric_scale = Value::INTEGER(0); + numeric_precision = Value::BIGINT(16); + numeric_scale = Value::BIGINT(0); numeric_precision_radix = Value::INTEGER(2); break; case LogicalTypeId::TINYINT: - numeric_precision = Value::INTEGER(8); - numeric_scale = Value::INTEGER(0); + numeric_precision = Value::BIGINT(8); + numeric_scale = Value::BIGINT(0); numeric_precision_radix = Value::INTEGER(2); break; case LogicalTypeId::FLOAT: - numeric_precision = Value::INTEGER(24); - numeric_scale = Value::INTEGER(0); + numeric_precision = Value::BIGINT(24); + numeric_scale = Value::BIGINT(0); numeric_precision_radix = Value::INTEGER(2); break; case LogicalTypeId::DOUBLE: - numeric_precision = Value::INTEGER(53); - numeric_scale = Value::INTEGER(0); + numeric_precision = Value::BIGINT(53); + numeric_scale = Value::BIGINT(0); numeric_precision_radix = Value::INTEGER(2); break; default: diff --git a/src/duckdb/src/function/table/table_scan.cpp b/src/duckdb/src/function/table/table_scan.cpp index 5daa6701a..448b276e4 100644 --- a/src/duckdb/src/function/table/table_scan.cpp +++ b/src/duckdb/src/function/table/table_scan.cpp @@ -1,4 +1,5 @@ #include "duckdb/function/table/table_scan.hpp" +#include "duckdb/storage/table/index_entry.hpp" #include "duckdb/function/table/native_scan_job.hpp" #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/storage/block_allocator.hpp" @@ -214,6 +215,7 @@ class DuckIndexScanState : public TableScanGlobalState { unique_ptr InitLocalState(ExecutionContext &context, TableFunctionInitInput &input) override { auto l_state = make_uniq(); + l_state->fetch_state.context = context.client; if (input.CanRemoveFilterColumns()) { l_state->all_columns.Initialize(context.client, scanned_types); } @@ -390,6 +392,17 @@ class DuckTableScanState : public TableScanGlobalState { for (auto &counter : progress) { counter.store(0, std::memory_order_relaxed); } + // add the entry first: commits up to its commit are scanned, later ones reach its deltas, + // and the scan range fixed after this covers every row of those commits + if (bind_data.index_template) { + index_build = storage.AddBuildingIndex(tx, *bind_data.index_template); + } + } + + ~DuckTableScanState() override { + if (index_build) { + storage.GetDataTableInfo()->GetIndexes().RemoveBuildingIndex(*index_build); + } } public: @@ -414,6 +427,8 @@ class DuckTableScanState : public TableScanGlobalState { //! Preallocated counters spread progress updates without registering local states vector> progress; TableScanScheduling scheduling = TableScanScheduling::UNINITIALIZED; + //! The entry of the index that this CREATE INDEX scan builds in place + shared_ptr index_build; private: void InitializeScheduling(ExecutionContext &context, TableFunctionInitInput &input) { @@ -713,7 +728,7 @@ class DuckTableScanState : public TableScanGlobalState { do { if (bind_data.is_create_index) { - storage.CreateIndexScan(l_state.scan_state, output); + storage.CreateIndexScan(l_state.scan_state, output, index_build.get()); UpdateScanProgress(l_state, l_state.scan_state); } else if (scheduling == TableScanScheduling::ORDERED) { if (!ScanWithReadAhead(context, data_p, l_state, output) && @@ -831,14 +846,22 @@ unique_ptr DuckTableScanInitGlobal(ClientContext &cont if (bind_data.partitions_to_scan) { g_state->state.scan_state.partitions_to_scan = bind_data.partitions_to_scan.get(); } + auto claim_mode = ParallelScanClaimMode::ATOMIC; + if (bind_data.order_options || bind_data.partitions_to_scan || + ClientConfig::GetConfig(context).verify_parallelism) { + claim_mode = ParallelScanClaimMode::LOCKED; + } // Check if row_number column is requested and initialize row_number_base for (idx_t i = 0; i < input.column_ids.size(); i++) { if (input.column_ids[i] == COLUMN_IDENTIFIER_ROW_NUMBER) { g_state->state.scan_state.row_number_base = 0; + claim_mode = ParallelScanClaimMode::LOCKED; break; } } + g_state->state.scan_state.claim_mode = claim_mode; + g_state->state.local_state.claim_mode = claim_mode; storage.InitializeParallelScan(context, g_state->state, input.column_indexes); g_state->InitializeScanInfo(input); if (!input.CanRemoveFilterColumns()) { @@ -1101,7 +1124,7 @@ bool TryScanIndex(const IndexReadHandle &art, const ColumnList &column_list if (!art->Scan(*scan_state, row_ids)) { return false; } - for (const auto delta : {IndexDeltaType::DELETED_ROWS_IN_USE, IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT}) { + for (const auto delta : {IndexDeltaType::DELETED_ROWS_IN_USE, IndexDeltaType::ADDED_DATA}) { auto delta_index = art.FindDelta(delta); if (delta_index && !delta_index->Scan(*scan_state, row_ids)) { return false; @@ -1174,10 +1197,14 @@ unique_ptr TableScanInitGlobal(ClientContext &context, vacuum_lock = DuckTransactionManager::Get(attached).SharedVacuumLock(); } - for (auto entry : indexes.IndexEntries()) { + auto &transaction = DuckTransaction::Get(context, storage.GetAttached()); + for (auto entry : indexes.BuiltIndexEntries()) { if (entry->GetBindState() != IndexBindState::BOUND || entry->GetIndexType() != ART::TYPE_NAME) { continue; } + if (!entry->AddedBefore(transaction.view.visibility_bound)) { + continue; + } { auto index = entry->GetReadHandle(); index_scan = TryScanIndex(index, column_list, input, filter_set, row_ids); diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index dc898f311..f2708516a 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-alpha57892" +#define DUCKDB_PATCH_VERSION "0-alpha58110" #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-alpha57892" +#define DUCKDB_VERSION "v2.1.0-alpha58110" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "a28f463cff" +#define DUCKDB_SOURCE_ID "704d4d288a" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/include/duckdb/common/base_file_system.hpp b/src/duckdb/src/include/duckdb/common/base_file_system.hpp new file mode 100644 index 000000000..d5ac29142 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/base_file_system.hpp @@ -0,0 +1,370 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/base_file_system.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/common.hpp" +#include "duckdb/common/enums/file_compression_type.hpp" +#include "duckdb/common/enums/file_glob_options.hpp" +#include "duckdb/common/enums/file_write_mode.hpp" +#include "duckdb/common/exception.hpp" +#include "duckdb/common/error_data.hpp" +#include "duckdb/common/file_buffer.hpp" +#include "duckdb/common/file_open_flags.hpp" +#include "duckdb/common/open_file_info.hpp" +#include "duckdb/common/optional.hpp" +#include "duckdb/common/optional_idx.hpp" +#include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/string.hpp" +#include "duckdb/common/types/value.hpp" +#include "duckdb/common/path.hpp" +#include "duckdb/common/unordered_map.hpp" +#include "duckdb/common/vector.hpp" + +#include + +#undef CreateDirectory +#undef MoveFile +#undef RemoveDirectory + +namespace duckdb { + +class AttachedDatabase; +class DatabaseInstance; +class FileOpener; +class BaseFileSystem; +class FileSystem; +class Logger; +class ClientContext; +class CompressedFileSystem; +class QueryContext; +class MemoryMappedFile; +struct MMapOptions; +class MultiFileList; + +enum class CreateDirectoryMode : uint8_t { + //! Create the target directory only; its parent directory must already exist. + SINGLE, + //! Create the target directory and any missing parent directories. + RECURSIVE +}; + +enum class RemoveDirectoryMode : uint8_t { + //! Remove the target only; return false if it is missing or non-empty and never remove its contents. + SINGLE, + //! Remove the target directory and all files and directories contained in it. + RECURSIVE +}; + +struct CreateDirectoryOptions { + CreateDirectoryMode mode = CreateDirectoryMode::SINGLE; +}; + +struct RemoveDirectoryOptions { + RemoveDirectoryMode mode = RemoveDirectoryMode::SINGLE; +}; + +enum class FileType { + //! Regular file + FILE_TYPE_REGULAR, + //! Directory + FILE_TYPE_DIR, + //! FIFO named pipe + FILE_TYPE_FIFO, + //! Socket + FILE_TYPE_SOCKET, + //! Symbolic link + FILE_TYPE_LINK, + //! Block device + FILE_TYPE_BLOCKDEV, + //! Character device + FILE_TYPE_CHARDEV, + //! Unknown or invalid file handle + FILE_TYPE_INVALID, +}; + +struct FileMetadata { + int64_t file_size = -1; + timestamp_t last_modification_time = timestamp_t::ninfinity(); + FileType file_type = FileType::FILE_TYPE_INVALID; + optional_idx device_id; + optional_idx file_id; + //! Optional: tag that uniquely identifies the version of the file (e.g., HTTP ETag). + //! Empty if the storage backend does not provide one. + string version_tag; + //! Time until which (inclusive) cached data may be served without revalidation. + //! Unset means the backend provides no freshness information; infinities mean always valid/invalid. + optional cache_valid_until; + + // A key-value pair of the extended file metadata, which could store any attributes. + unordered_map extended_file_info; +}; + +//! Measured network throughput for a (remote) file handle. Used to size prefetch coalescing gaps. +struct NetworkThroughputEstimate { + //! Round-trip latency + request setup, in seconds + double latency_seconds = 0; + //! Single-stream throughput, in bytes per second + double bandwidth_bytes_per_s = 0; +}; + +struct FileHandle { +public: + DUCKDB_API FileHandle(BaseFileSystem &file_system, string path, FileOpenFlags flags); + FileHandle(const FileHandle &) = delete; + DUCKDB_API virtual ~FileHandle(); + + // Read at [nr_bytes] bytes into [buffer], and return the bytes actually read. + // File offset will be changed, which advances for number of bytes read. + DUCKDB_API int64_t Read(void *buffer, idx_t nr_bytes); + DUCKDB_API int64_t Read(QueryContext context, void *buffer, idx_t nr_bytes); + DUCKDB_API int64_t Write(void *buffer, idx_t nr_bytes); + DUCKDB_API int64_t Write(QueryContext context, void *buffer, idx_t nr_bytes); + // Read at [nr_bytes] bytes into [buffer]. + // File offset will not be changed. + DUCKDB_API void Read(void *buffer, idx_t nr_bytes, idx_t location); + DUCKDB_API void Read(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location); + DUCKDB_API void Write(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location); + DUCKDB_API void Seek(idx_t location); + DUCKDB_API void Reset(); + DUCKDB_API idx_t SeekPosition(); + DUCKDB_API void Sync(); + DUCKDB_API void Truncate(int64_t new_size); + //! Abandon an incomplete write without publishing any buffered or staged data. + DUCKDB_API void AbortWrite(); + DUCKDB_API string ReadLine(); + DUCKDB_API string ReadLine(QueryContext context); + DUCKDB_API bool Trim(idx_t offset_bytes, idx_t length_bytes); + DUCKDB_API virtual idx_t GetProgress(); + DUCKDB_API virtual FileCompressionType GetFileCompressionType(); + + DUCKDB_API virtual bool CanSeek(); + DUCKDB_API FileWriteMode GetWriteMode(); + DUCKDB_API bool IsPipe(); + DUCKDB_API bool OnDiskFile(); + //! Try to obtain a network throughput estimate (Local files return false). + DUCKDB_API bool TryGetNetworkThroughput(NetworkThroughputEstimate &result); + DUCKDB_API idx_t GetFileSize(); + DUCKDB_API FileType GetType(); + DUCKDB_API FileMetadata Stats(); + + DUCKDB_API void TryAddLogger(FileOpener &opener); + + //! Closes the file handle. + DUCKDB_API virtual void Close() = 0; + + string GetPath() const { + return path; + } + + FileOpenFlags GetFlags() const { + return flags; + } + + template + TARGET &Cast() { + DynamicCastCheck(this); + return reinterpret_cast(*this); + } + template + const TARGET &Cast() const { + DynamicCastCheck(this); + return reinterpret_cast(*this); + } + +public: + BaseFileSystem &file_system; + string path; + FileOpenFlags flags; + + shared_ptr logger; + //! Whether reads/writes through this handle are counted in the query's I/O metrics. Set to false for + //! wrapper handles (e.g. compressed files) that delegate the real on-disk I/O to a child handle, so that + //! the bytes are attributed to the child handle (the actual disk I/O) and not double-counted. + bool track_io = true; +}; + +class BaseFileSystem { +public: + DUCKDB_API virtual ~BaseFileSystem(); + + DUCKDB_API virtual unique_ptr OpenFile(const string &path, FileOpenFlags flags, + optional_ptr opener); + DUCKDB_API unique_ptr OpenFile(const OpenFileInfo &path, const FileOpenFlags &flags, + optional_ptr opener); + + //! Open a memory-mapped view of [path]. Throws if not supported by this filesystem. + DUCKDB_API virtual unique_ptr MemoryMapFile(const OpenFileInfo &path, FileOpenFlags flags, + const MMapOptions &options, + optional_ptr opener); + + //! Read exactly nr_bytes from the specified location in the file. Fails if nr_bytes could not be read. This is + //! equivalent to calling SetFilePointer(location) followed by calling Read(). + DUCKDB_API virtual void Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location); + //! Write exactly nr_bytes to the specified location in the file. Fails if nr_bytes could not be written. This is + //! equivalent to calling SetFilePointer(location) followed by calling Write(). + DUCKDB_API virtual void Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location); + //! Read nr_bytes from the specified file into the buffer, moving the file pointer forward by nr_bytes. Returns the + //! amount of bytes read. + DUCKDB_API virtual int64_t Read(FileHandle &handle, void *buffer, int64_t nr_bytes); + //! Write nr_bytes from the buffer into the file, moving the file pointer forward by nr_bytes. + DUCKDB_API virtual int64_t Write(FileHandle &handle, void *buffer, int64_t nr_bytes); + //! Excise a range of the file. The OS can drop pages from the page-cache, and the file-system is free to deallocate + //! this range (sparse file support). Reads to the range will succeed but will return undefined data. + DUCKDB_API virtual bool Trim(FileHandle &handle, idx_t offset_bytes, idx_t length_bytes); + + //! Returns the file size of a file handle, returns -1 on error + DUCKDB_API virtual int64_t GetFileSize(FileHandle &handle); + //! Returns the file last modified time of a file handle, returns timespec with zero on all attributes on error + DUCKDB_API virtual timestamp_t GetLastModifiedTime(FileHandle &handle); + //! Returns a tag that uniquely identifies the version of the file, + //! used for checking cache invalidation for CachingFileSystem httpfs files + DUCKDB_API virtual string GetVersionTag(FileHandle &handle); + //! Returns the current cache freshness deadline, if provided by the file system + DUCKDB_API virtual optional GetCacheValidUntil(FileHandle &handle); + //! Returns the file type of the attached handle + DUCKDB_API virtual FileType GetFileType(FileHandle &handle); + //! Returns the file stats of the attached handle. + DUCKDB_API virtual FileMetadata Stats(FileHandle &handle); + //! Returns the stats of a file, or nullopt if the file does not exist. + DUCKDB_API virtual optional GetStatsIfExists(const OpenFileInfo &file, + optional_ptr opener); + //! Truncate a file to a maximum size of new_size, new_size should be smaller than or equal to the current size of + //! the file + DUCKDB_API virtual void Truncate(FileHandle &handle, int64_t new_size); + + //! Check if a directory exists + DUCKDB_API virtual bool DirectoryExists(const string &directory, optional_ptr opener); + //! Create a directory if it does not exist + DUCKDB_API virtual void CreateDirectory(const string &directory, optional_ptr opener); + //! Create one directory or a directory tree. Returns whether this call is known to have created the target. + DUCKDB_API virtual bool CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, + optional_ptr opener); + //! Helper function that uses DirectoryExists and CreateDirectory to ensure all directories in path are created + DUCKDB_API virtual void CreateDirectoriesRecursive(const string &path, optional_ptr opener); + //! Recursively remove a directory and all files in it + DUCKDB_API virtual void RemoveDirectory(const string &directory, optional_ptr opener); + //! Remove an empty directory or a directory tree. Returns whether the target was removed. + DUCKDB_API virtual bool RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, + optional_ptr opener); + + //! List files in a directory, invoking the callback method for each one with (filename, is_dir) + DUCKDB_API virtual bool ListFiles(const string &directory, + const std::function &callback, FileOpener *opener); + DUCKDB_API bool ListFiles(const string &directory, const std::function &callback, + optional_ptr opener); + + //! Move a file from source path to the target, StorageManager relies on this being an atomic action for ACID + //! properties + DUCKDB_API virtual void MoveFile(const string &source, const string &target, optional_ptr opener); + //! Check if a file exists + DUCKDB_API virtual bool FileExists(const string &filename, optional_ptr opener); + //! Check if path is a pipe or character device + DUCKDB_API virtual bool IsPipe(const string &filename, optional_ptr opener); + //! Remove a file from disk + DUCKDB_API virtual void RemoveFile(const string &filename, optional_ptr opener); + //! Remove a file from disk if it exists - if it does not exist, return false + DUCKDB_API virtual bool TryRemoveFile(const string &filename, optional_ptr opener); + //! Remove multiple files from disk - does not error if any file does not exist + DUCKDB_API virtual void RemoveFiles(const vector &filenames, optional_ptr opener); + //! Sync a file handle to disk + DUCKDB_API virtual void FileSync(FileHandle &handle); + //! Abandon an incomplete write represented by this file handle. + DUCKDB_API virtual void AbortFileWrite(FileHandle &handle); + //! Gets the users home directory + DUCKDB_API virtual string GetHomeDirectory(); + //! Expands a given path, including e.g. expanding the home directory of the user + DUCKDB_API virtual string ExpandPath(const string &path); + //! Path separator for path + DUCKDB_API virtual string PathSeparator(const string &path); + //! Checks if path is is an absolute path + DUCKDB_API virtual bool IsPathAbsolute(const string &path); + //! Join two paths together + DUCKDB_API string JoinPath(const string &a, const string &path); + // Join N paths together + template + string JoinPath(const string &a, const string &b, ARGS... args) { + return JoinPath(JoinPath(a, b), args...); + } + //! Convert separators in a path to the local separators (e.g. convert "/" into \\ on windows) + DUCKDB_API string ConvertSeparators(const string &path); + //! Extract the base name of a file (e.g. if the input is lib/example.dll the base name is 'example') + DUCKDB_API string ExtractBaseName(const string &path); + //! Extract the extension of a file (e.g. if the input is lib/example.dll the extension is 'dll') + DUCKDB_API string ExtractExtension(const string &path); + //! Extract the name of a file (e.g if the input is lib/example.dll the name is 'example.dll') + DUCKDB_API string ExtractName(const string &path); + + //! Runs a glob on the file system, returning a list of matching files + DUCKDB_API virtual vector Glob(const string &path, FileOpener *opener); + DUCKDB_API unique_ptr Glob(const string &path, const FileGlobInput &input, + optional_ptr opener); + + //! Whether or not a sub-system can handle a specific file path + DUCKDB_API virtual bool CanHandleFile(const string &fpath); + + //! Set the file pointer of a file handle to a specified location. Reads and writes will happen from this location + DUCKDB_API virtual void Seek(FileHandle &handle, idx_t location); + //! Reset a file to the beginning (equivalent to Seek(handle, 0) for simple files) + DUCKDB_API virtual void Reset(FileHandle &handle); + DUCKDB_API virtual idx_t SeekPosition(FileHandle &handle); + + //! If FS was manually set by the user + DUCKDB_API virtual bool IsManuallySet(); + //! Return the write ordering contract for this handle. + DUCKDB_API virtual FileWriteMode GetWriteMode(FileHandle &handle); + //! Whether or not we can seek into the file + DUCKDB_API virtual bool CanSeek(); + //! Whether or not the FS handles plain files on disk. This is relevant for certain optimizations, as random reads + //! in a file on-disk are much cheaper than e.g. random reads in a file over the network + DUCKDB_API virtual bool OnDiskFile(FileHandle &handle); + //! Try to obtain a measured network throughput estimate. Default: not supported (returns false). + //! Used for file systems + DUCKDB_API virtual bool TryGetNetworkThroughput(FileHandle &handle, NetworkThroughputEstimate &result); + + DUCKDB_API virtual unique_ptr OpenCompressedFile(QueryContext context, unique_ptr handle, + bool write); + + //! Whether this is a LocalFileSystem instance. + DUCKDB_API virtual bool IsLocalFileSystem() const; + + //! Return the name of the filesystem. Used for forming diagnosis messages. + DUCKDB_API virtual std::string GetName() const = 0; + + //! Canonicalize a path + DUCKDB_API virtual string CanonicalizePath(const string &path, optional_ptr opener); + +protected: + DUCKDB_API virtual unique_ptr OpenFileExtended(const OpenFileInfo &path, FileOpenFlags flags, + optional_ptr opener); + DUCKDB_API virtual bool SupportsOpenFileExtended() const; + + DUCKDB_API virtual bool ListFilesExtended(const string &directory, + const std::function &callback, + optional_ptr opener); + DUCKDB_API virtual bool SupportsListFilesExtended() const; + + DUCKDB_API virtual unique_ptr GlobFilesExtended(const string &path, const FileGlobInput &input, + optional_ptr opener); + DUCKDB_API virtual bool SupportsGlobExtended() const; + +public: + template + TARGET &Cast() { + DynamicCastCheck(this); + return reinterpret_cast(*this); + } + + template + const TARGET &Cast() const { + DynamicCastCheck(this); + return reinterpret_cast(*this); + } +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/bignum_limbs.hpp b/src/duckdb/src/include/duckdb/common/bignum_limbs.hpp index 84cb841a1..80c758b7a 100644 --- a/src/duckdb/src/include/duckdb/common/bignum_limbs.hpp +++ b/src/duckdb/src/include/duckdb/common/bignum_limbs.hpp @@ -11,6 +11,7 @@ #include "duckdb/common/bit_utils.hpp" #include "duckdb/common/bswap.hpp" #include "duckdb/common/typedefs.hpp" +#include "duckdb/common/uint128_arithmetic.hpp" #include @@ -39,15 +40,7 @@ struct BignumLimb { //! Divides high * 2^64 + low by a divisor larger than high, so that the quotient fits a digit; sets the remainder static inline uint64_t DivRem(uint64_t high, uint64_t low, uint64_t divisor, uint64_t &remainder) { D_ASSERT(high < divisor); -#ifdef _MSC_VER - // clang-cl has the 128-bit type but links no runtime support for dividing it - return DivRemPortable(high, low, divisor, remainder); -#else - const twodigit_t numerator = (static_cast(high) << 64) | low; - const auto quotient = static_cast(numerator / divisor); - remainder = static_cast(numerator - static_cast(quotient) * divisor); - return quotient; -#endif + return Uint128DivRem64(high, low, divisor, remainder); } #else using digit_t = uint32_t; @@ -64,18 +57,7 @@ struct BignumLimb { //! Returns the low 64 bits of a * b + add, and its high 64 bits in "high"; never overflows 128 bits static inline uint64_t MultiplyAdd(uint64_t a, uint64_t b, uint64_t add, uint64_t &high) { - // portable 32-bit split - const uint64_t a_low = a & 0xFFFFFFFFULL; - const uint64_t a_high = a >> 32; - const uint64_t b_low = b & 0xFFFFFFFFULL; - const uint64_t b_high = b >> 32; - const uint64_t p0 = a_low * b_low; - const uint64_t p1 = a_low * b_high; - const uint64_t p2 = a_high * b_low; - const uint64_t p3 = a_high * b_high; - const uint64_t middle = (p0 >> 32) + (p1 & 0xFFFFFFFFULL) + (p2 & 0xFFFFFFFFULL); - uint64_t low = (p0 & 0xFFFFFFFFULL) | (middle << 32); - high = p3 + (p1 >> 32) + (p2 >> 32) + (middle >> 32); + uint64_t low = Uint64MultiplyFull(a, b, high); low += add; high += low < add ? 1 : 0; return low; @@ -86,47 +68,6 @@ struct BignumLimb { static constexpr idx_t DIGIT_BYTES = sizeof(digit_t); static constexpr idx_t DIGIT_BITS = DIGIT_BYTES * 8; - //! DivRem in two base 2^32 steps (Hacker's Delight divlu), for compilers without 128-bit division - static inline uint64_t DivRemPortable(uint64_t high, uint64_t low, uint64_t divisor, uint64_t &remainder) { - D_ASSERT(high < divisor); - constexpr uint64_t HALF_BASE = static_cast(1) << 32; - constexpr uint64_t HALF_MASK = HALF_BASE - 1; - // normalize so that the divisor has its top bit set; the quotient is unchanged, the remainder is scaled - const idx_t shift = LeadingZeros(divisor); - if (shift > 0) { - divisor <<= shift; - high = (high << shift) | (low >> (64 - shift)); - low <<= shift; - } - const uint64_t divisor_high = divisor >> 32; - const uint64_t divisor_low = divisor & HALF_MASK; - const uint64_t low_high = low >> 32; - const uint64_t low_low = low & HALF_MASK; - // the high half of the quotient: an estimate from the top halves that is corrected down until it is exact - uint64_t q_high = high / divisor_high; - uint64_t rhat = high - q_high * divisor_high; - while (q_high >= HALF_BASE || q_high * divisor_low > ((rhat << 32) | low_high)) { - q_high--; - rhat += divisor_high; - if (rhat >= HALF_BASE) { - break; - } - } - // the partial remainder is below the divisor, so the wrapping arithmetic yields the exact value - const uint64_t middle = (high << 32) + low_high - q_high * divisor; - uint64_t q_low = middle / divisor_high; - rhat = middle - q_low * divisor_high; - while (q_low >= HALF_BASE || q_low * divisor_low > ((rhat << 32) | low_low)) { - q_low--; - rhat += divisor_high; - if (rhat >= HALF_BASE) { - break; - } - } - remainder = ((middle << 32) + low_low - q_low * divisor) >> shift; - return (q_high << 32) | q_low; - } - template static inline T ToHostOrder(T value) { #if DUCKDB_IS_BIG_ENDIAN @@ -239,11 +180,7 @@ struct BignumLimb { //! The number of leading zero bits of a non-zero limb static inline idx_t LeadingZeros(uint64_t value) { D_ASSERT(value != 0); -#if defined(__GNUC__) || defined(__clang__) - return static_cast(__builtin_clzll(value)); -#else - return CountZeros::Leading(value); -#endif + return Uint64LeadingZeros(value); } static inline idx_t LeadingZeros(uint32_t value) { D_ASSERT(value != 0); diff --git a/src/duckdb/src/include/duckdb/common/compressed_file_system.hpp b/src/duckdb/src/include/duckdb/common/compressed_file_system.hpp index 33a1b3098..1a242c28d 100644 --- a/src/duckdb/src/include/duckdb/common/compressed_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/compressed_file_system.hpp @@ -11,7 +11,7 @@ #include "duckdb/common/allocator.hpp" #include "duckdb/common/atomic.hpp" #include "duckdb/common/common.hpp" -#include "duckdb/common/file_system.hpp" +#include "duckdb/common/base_file_system.hpp" #include "duckdb/common/query_context.hpp" namespace duckdb { @@ -44,7 +44,7 @@ struct StreamWrapper { DUCKDB_API virtual void AbortWrite(); }; -class CompressedFileSystem : public FileSystem { +class CompressedFileSystem : public BaseFileSystem { public: DUCKDB_API int64_t Read(FileHandle &handle, void *buffer, int64_t nr_bytes) override; DUCKDB_API int64_t Write(FileHandle &handle, void *buffer, int64_t nr_bytes) override; diff --git a/src/duckdb/src/include/duckdb/common/enums/filter_result.hpp b/src/duckdb/src/include/duckdb/common/enums/filter_result.hpp new file mode 100644 index 000000000..98fd8e875 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/enums/filter_result.hpp @@ -0,0 +1,15 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/enums/filter_result.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +namespace duckdb { + +enum class FilterResult { UNSATISFIABLE, SUCCESS, UNSUPPORTED }; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/file_system.hpp b/src/duckdb/src/include/duckdb/common/file_system.hpp index 3772f9ec3..4f7dd7186 100644 --- a/src/duckdb/src/include/duckdb/common/file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/file_system.hpp @@ -8,401 +8,228 @@ #pragma once -#include "duckdb/common/common.hpp" -#include "duckdb/common/enums/file_compression_type.hpp" -#include "duckdb/common/enums/file_glob_options.hpp" -#include "duckdb/common/enums/file_write_mode.hpp" -#include "duckdb/common/exception.hpp" -#include "duckdb/common/error_data.hpp" -#include "duckdb/common/file_buffer.hpp" -#include "duckdb/common/file_open_flags.hpp" -#include "duckdb/common/open_file_info.hpp" -#include "duckdb/common/optional.hpp" -#include "duckdb/common/optional_idx.hpp" -#include "duckdb/common/optional_ptr.hpp" -#include "duckdb/common/string.hpp" -#include "duckdb/common/types/value.hpp" -#include "duckdb/common/path.hpp" -#include "duckdb/common/unordered_map.hpp" -#include "duckdb/common/vector.hpp" - -#include - -#undef CreateDirectory -#undef MoveFile -#undef RemoveDirectory +#include "duckdb/common/base_file_system.hpp" +#include "duckdb/common/virtual_file_system.hpp" namespace duckdb { - -class AttachedDatabase; -class DatabaseInstance; -class FileOpener; -class FileSystem; -class Logger; -class ClientContext; -class CompressedFileSystem; -class QueryContext; -class MemoryMappedFile; -struct MMapOptions; class MultiFileList; -enum class CreateDirectoryMode : uint8_t { - //! Create the target directory only; its parent directory must already exist. - SINGLE, - //! Create the target directory and any missing parent directories. - RECURSIVE -}; - -enum class RemoveDirectoryMode : uint8_t { - //! Remove the target only; return false if it is missing or non-empty and never remove its contents. - SINGLE, - //! Remove the target directory and all files and directories contained in it. - RECURSIVE -}; - -struct CreateDirectoryOptions { - CreateDirectoryMode mode = CreateDirectoryMode::SINGLE; -}; - -struct RemoveDirectoryOptions { - RemoveDirectoryMode mode = RemoveDirectoryMode::SINGLE; -}; - -enum class FileType { - //! Regular file - FILE_TYPE_REGULAR, - //! Directory - FILE_TYPE_DIR, - //! FIFO named pipe - FILE_TYPE_FIFO, - //! Socket - FILE_TYPE_SOCKET, - //! Symbolic link - FILE_TYPE_LINK, - //! Block device - FILE_TYPE_BLOCKDEV, - //! Character device - FILE_TYPE_CHARDEV, - //! Unknown or invalid file handle - FILE_TYPE_INVALID, -}; - -struct FileMetadata { - int64_t file_size = -1; - timestamp_t last_modification_time = timestamp_t::ninfinity(); - FileType file_type = FileType::FILE_TYPE_INVALID; - optional_idx device_id; - optional_idx file_id; - //! Optional: tag that uniquely identifies the version of the file (e.g., HTTP ETag). - //! Empty if the storage backend does not provide one. - string version_tag; - //! Time until which (inclusive) cached data may be served without revalidation. - //! Unset means the backend provides no freshness information; infinities mean always valid/invalid. - optional cache_valid_until; - - // A key-value pair of the extended file metadata, which could store any attributes. - unordered_map extended_file_info; -}; - -//! Measured network throughput for a (remote) file handle. Used to size prefetch coalescing gaps. -struct NetworkThroughputEstimate { - //! Round-trip latency + request setup, in seconds - double latency_seconds = 0; - //! Single-stream throughput, in bytes per second - double bandwidth_bytes_per_s = 0; -}; - -struct FileHandle { -public: - DUCKDB_API FileHandle(FileSystem &file_system, string path, FileOpenFlags flags); - FileHandle(const FileHandle &) = delete; - DUCKDB_API virtual ~FileHandle(); - - // Read at [nr_bytes] bytes into [buffer], and return the bytes actually read. - // File offset will be changed, which advances for number of bytes read. - DUCKDB_API int64_t Read(void *buffer, idx_t nr_bytes); - DUCKDB_API int64_t Read(QueryContext context, void *buffer, idx_t nr_bytes); - DUCKDB_API int64_t Write(void *buffer, idx_t nr_bytes); - DUCKDB_API int64_t Write(QueryContext context, void *buffer, idx_t nr_bytes); - // Read at [nr_bytes] bytes into [buffer]. - // File offset will not be changed. - DUCKDB_API void Read(void *buffer, idx_t nr_bytes, idx_t location); - DUCKDB_API void Read(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location); - DUCKDB_API void Write(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location); - DUCKDB_API void Seek(idx_t location); - DUCKDB_API void Reset(); - DUCKDB_API idx_t SeekPosition(); - DUCKDB_API void Sync(); - DUCKDB_API void Truncate(int64_t new_size); - //! Abandon an incomplete write without publishing any buffered or staged data. - DUCKDB_API void AbortWrite(); - DUCKDB_API string ReadLine(); - DUCKDB_API string ReadLine(QueryContext context); - DUCKDB_API bool Trim(idx_t offset_bytes, idx_t length_bytes); - DUCKDB_API virtual idx_t GetProgress(); - DUCKDB_API virtual FileCompressionType GetFileCompressionType(); - - DUCKDB_API virtual bool CanSeek(); - DUCKDB_API FileWriteMode GetWriteMode(); - DUCKDB_API bool IsPipe(); - DUCKDB_API bool OnDiskFile(); - //! Try to obtain a network throughput estimate (Local files return false). - DUCKDB_API bool TryGetNetworkThroughput(NetworkThroughputEstimate &result); - DUCKDB_API idx_t GetFileSize(); - DUCKDB_API FileType GetType(); - DUCKDB_API FileMetadata Stats(); - - DUCKDB_API void TryAddLogger(FileOpener &opener); - - //! Closes the file handle. - DUCKDB_API virtual void Close() = 0; - - string GetPath() const { - return path; - } - - FileOpenFlags GetFlags() const { - return flags; - } - - template - TARGET &Cast() { - DynamicCastCheck(this); - return reinterpret_cast(*this); - } - template - const TARGET &Cast() const { - DynamicCastCheck(this); - return reinterpret_cast(*this); - } - -public: - FileSystem &file_system; - string path; - FileOpenFlags flags; - - shared_ptr logger; - //! Whether reads/writes through this handle are counted in the query's I/O metrics. Set to false for - //! wrapper handles (e.g. compressed files) that delegate the real on-disk I/O to a child handle, so that - //! the bytes are attributed to the child handle (the actual disk I/O) and not double-counted. - bool track_io = true; -}; - +//! A file system bound to a context: it wraps a BaseFileSystem and pushes the FileOpener of that context into every +//! call after checking that the access is allowed. It is not a BaseFileSystem: code that obtains it through +//! FileSystem::GetFileSystem(context) cannot call the opener-taking BaseFileSystem methods by accident. class FileSystem { public: - DUCKDB_API virtual ~FileSystem(); + virtual ~FileSystem() = default; public: + //! The file system of a client, of a database, or the local file system of a database DUCKDB_API static FileSystem &GetFileSystem(ClientContext &context); DUCKDB_API static FileSystem &GetFileSystem(DatabaseInstance &db); DUCKDB_API static FileSystem &GetLocal(DatabaseInstance &db); DUCKDB_API static FileSystem &Get(AttachedDatabase &db); - DUCKDB_API virtual unique_ptr OpenFile(const string &path, FileOpenFlags flags, - optional_ptr opener = nullptr); - DUCKDB_API unique_ptr OpenFile(const OpenFileInfo &path, const FileOpenFlags &flags, - optional_ptr opener = nullptr); - - //! Open a memory-mapped view of [path]. Throws if not supported by this filesystem. - DUCKDB_API virtual unique_ptr MemoryMapFile(const OpenFileInfo &path, FileOpenFlags flags, - const MMapOptions &options, - optional_ptr opener = nullptr); - - //! Read exactly nr_bytes from the specified location in the file. Fails if nr_bytes could not be read. This is - //! equivalent to calling SetFilePointer(location) followed by calling Read(). - DUCKDB_API virtual void Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location); - //! Write exactly nr_bytes to the specified location in the file. Fails if nr_bytes could not be written. This is - //! equivalent to calling SetFilePointer(location) followed by calling Write(). - DUCKDB_API virtual void Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location); - //! Read nr_bytes from the specified file into the buffer, moving the file pointer forward by nr_bytes. Returns the - //! amount of bytes read. - DUCKDB_API virtual int64_t Read(FileHandle &handle, void *buffer, int64_t nr_bytes); - //! Write nr_bytes from the buffer into the file, moving the file pointer forward by nr_bytes. - DUCKDB_API virtual int64_t Write(FileHandle &handle, void *buffer, int64_t nr_bytes); - //! Excise a range of the file. The OS can drop pages from the page-cache, and the file-system is free to deallocate - //! this range (sparse file support). Reads to the range will succeed but will return undefined data. - DUCKDB_API virtual bool Trim(FileHandle &handle, idx_t offset_bytes, idx_t length_bytes); - - //! Returns the file size of a file handle, returns -1 on error - DUCKDB_API virtual int64_t GetFileSize(FileHandle &handle); - //! Returns the file last modified time of a file handle, returns timespec with zero on all attributes on error - DUCKDB_API virtual timestamp_t GetLastModifiedTime(FileHandle &handle); - //! Returns a tag that uniquely identifies the version of the file, - //! used for checking cache invalidation for CachingFileSystem httpfs files - DUCKDB_API virtual string GetVersionTag(FileHandle &handle); - //! Returns the current cache freshness deadline, if provided by the file system - DUCKDB_API virtual optional GetCacheValidUntil(FileHandle &handle); - //! Returns the file type of the attached handle - DUCKDB_API virtual FileType GetFileType(FileHandle &handle); - //! Returns the file stats of the attached handle. - DUCKDB_API virtual FileMetadata Stats(FileHandle &handle); - //! Returns the stats of a file, or nullopt if the file does not exist. - DUCKDB_API virtual optional GetStatsIfExists(const OpenFileInfo &file, - optional_ptr opener = nullptr); - //! Truncate a file to a maximum size of new_size, new_size should be smaller than or equal to the current size of - //! the file - DUCKDB_API virtual void Truncate(FileHandle &handle, int64_t new_size); - - //! Check if a directory exists - DUCKDB_API virtual bool DirectoryExists(const string &directory, optional_ptr opener = nullptr); - //! Create a directory if it does not exist - DUCKDB_API virtual void CreateDirectory(const string &directory, optional_ptr opener = nullptr); - //! Create one directory or a directory tree. Returns whether this call is known to have created the target. - DUCKDB_API virtual bool CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener = nullptr); - //! Helper function that uses DirectoryExists and CreateDirectory to ensure all directories in path are created - DUCKDB_API virtual void CreateDirectoriesRecursive(const string &path, optional_ptr opener = nullptr); - //! Recursively remove a directory and all files in it - DUCKDB_API virtual void RemoveDirectory(const string &directory, optional_ptr opener = nullptr); - //! Remove an empty directory or a directory tree. Returns whether the target was removed. - DUCKDB_API virtual bool RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener = nullptr); - - //! List files in a directory, invoking the callback method for each one with (filename, is_dir) - DUCKDB_API virtual bool ListFiles(const string &directory, - const std::function &callback, - FileOpener *opener = nullptr); - DUCKDB_API bool ListFiles(const string &directory, const std::function &callback, - optional_ptr opener = nullptr); - - //! Move a file from source path to the target, StorageManager relies on this being an atomic action for ACID - //! properties - DUCKDB_API virtual void MoveFile(const string &source, const string &target, - optional_ptr opener = nullptr); - //! Check if a file exists - DUCKDB_API virtual bool FileExists(const string &filename, optional_ptr opener = nullptr); - //! Check if path is a pipe or character device - DUCKDB_API virtual bool IsPipe(const string &filename, optional_ptr opener = nullptr); - //! Remove a file from disk - DUCKDB_API virtual void RemoveFile(const string &filename, optional_ptr opener = nullptr); - //! Remove a file from disk if it exists - if it does not exist, return false - DUCKDB_API virtual bool TryRemoveFile(const string &filename, optional_ptr opener = nullptr); - //! Remove multiple files from disk - does not error if any file does not exist - DUCKDB_API virtual void RemoveFiles(const vector &filenames, optional_ptr opener = nullptr); - //! Sync a file handle to disk - DUCKDB_API virtual void FileSync(FileHandle &handle); - //! Abandon an incomplete write represented by this file handle. - DUCKDB_API virtual void AbortFileWrite(FileHandle &handle); +public: + //! Static helpers that do not depend on a file system instance + //! Whether or not a file is remote or local, based only on file path + DUCKDB_API static bool IsRemoteFile(const string &path); + DUCKDB_API static bool IsRemoteFile(const string &path, string &extension); + //! Whether there is a glob in the string + DUCKDB_API static bool HasGlob(const string &str); + DUCKDB_API static bool IsDirectory(const OpenFileInfo &info); //! Sets the working directory DUCKDB_API static void SetWorkingDirectory(const string &path); //! Gets the working directory DUCKDB_API static string GetWorkingDirectory(); //! Gets the users home directory DUCKDB_API static string GetHomeDirectory(optional_ptr opener); - //! Gets the users home directory - DUCKDB_API virtual string GetHomeDirectory(); //! Expands a given path, including e.g. expanding the home directory of the user DUCKDB_API static string ExpandPath(const string &path, optional_ptr opener); - //! Expands a given path, including e.g. expanding the home directory of the user - DUCKDB_API virtual string ExpandPath(const string &path); - //! Returns the system-available memory in bytes. Returns DConstants::INVALID_INDEX if the system function fails. + //! Returns the system-available memory in bytes. Returns an invalid index if the system function fails. DUCKDB_API static optional_idx GetAvailableMemory(); - //! Returns the space available on the disk. Returns DConstants::INVALID_INDEX if the information was not available. + //! Returns the space available on the disk. Returns an invalid index if the information was not available. DUCKDB_API static optional_idx GetAvailableDiskSpace(const string &path); //! Returns the soft limit on open file descriptors, or an invalid index when it is unlimited or unknown. DUCKDB_API static optional_idx GetFileDescriptorLimit(); //! Returns the share of the file descriptor limit that one consumer of descriptors may hold open. DUCKDB_API static idx_t GetFileDescriptorShare(idx_t file_descriptor_limit); - //! Path separator for path - DUCKDB_API virtual string PathSeparator(const string &path); - //! Checks if path is is an absolute path - DUCKDB_API virtual bool IsPathAbsolute(const string &path); - //! Join two paths together - DUCKDB_API string JoinPath(const string &a, const string &path); - // Join N paths together - template - string JoinPath(const string &a, const string &b, ARGS... args) { - return JoinPath(JoinPath(a, b), args...); - } - //! Convert separators in a path to the local separators (e.g. convert "/" into \\ on windows) - DUCKDB_API string ConvertSeparators(const string &path); - //! Extract the base name of a file (e.g. if the input is lib/example.dll the base name is 'example') - DUCKDB_API string ExtractBaseName(const string &path); - //! Extract the extension of a file (e.g. if the input is lib/example.dll the extension is 'dll') - DUCKDB_API string ExtractExtension(const string &path); - //! Extract the name of a file (e.g if the input is lib/example.dll the name is 'example.dll') - DUCKDB_API string ExtractName(const string &path); - //! Returns the value of an environment variable - or the empty string if it is not set DUCKDB_API static string GetEnvVariable(const string &name); - //! Whether there is a glob in the string - DUCKDB_API static bool HasGlob(const string &str); - //! Runs a glob on the file system, returning a list of matching files - DUCKDB_API virtual vector Glob(const string &path, FileOpener *opener = nullptr); - DUCKDB_API unique_ptr Glob(const string &path, const FileGlobInput &input, - optional_ptr opener); +public: + DUCKDB_API void VerifyCanAccessDirectory(const string &path); + DUCKDB_API void VerifyCanAccessFile(const string &path); + void VerifyCanAccessExtension(const string &path, const FileOpenFlags &flags) { + if (flags.OpenForWriting() && !flags.EnableExtensionInstall()) { + throw PermissionException( + "File '%s' cannot be opened for writing since files ending with '.duckdb_extension' are reserved for " + "DuckDB extensions, and these can only be installed through the INSTALL command", + path); + } + } + + //! Reserved for DuckDB's extension trust domain: the loadable binary and every file that decides whether it may + //! be loaded (install provenance, trusted repositories). These can only be written through INSTALL / CREATE + //! EXTENSION REPOSITORY, which pass FILE_FLAGS_ENABLE_EXTENSION_INSTALL. + //! To add a file to the trust domain, give it a ".duckdb_extension." segment, e.g. + //! ".duckdb_extension.info" or ".duckdb_extension.repo.json". Matching is on the file name only, so a + //! directory that happens to contain the marker does not reserve the files inside it + bool IsDuckDBExtensionName(const string &path) { + // match the canonical name case-insensitively: on the default macOS and Windows file systems a + // differently-cased name refers to the same file + auto name = StringUtil::Lower(PathFileSystem(path).ExtractName(CanonicalizePath(path))); + return StringUtil::EndsWith(name, ".duckdb_extension") || StringUtil::Contains(name, ".duckdb_extension."); + } + + //! Handle-level operations + void Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) { + handle.file_system.Read(handle, buffer, nr_bytes, location); + } + int64_t Read(FileHandle &handle, void *buffer, int64_t nr_bytes) { + return handle.file_system.Read(handle, buffer, nr_bytes); + } + void Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) { + handle.file_system.Write(handle, buffer, nr_bytes, location); + } + int64_t Write(FileHandle &handle, void *buffer, int64_t nr_bytes) { + return handle.file_system.Write(handle, buffer, nr_bytes); + } + int64_t GetFileSize(FileHandle &handle) { + return handle.file_system.GetFileSize(handle); + } + timestamp_t GetLastModifiedTime(FileHandle &handle) { + return handle.file_system.GetLastModifiedTime(handle); + } + string GetVersionTag(FileHandle &handle) { + return handle.file_system.GetVersionTag(handle); + } + FileType GetFileType(FileHandle &handle) { + return handle.file_system.GetFileType(handle); + } + FileMetadata Stats(FileHandle &handle) { + return handle.file_system.Stats(handle); + } + void Truncate(FileHandle &handle, int64_t new_size) { + handle.file_system.Truncate(handle, new_size); + } + void FileSync(FileHandle &handle) { + handle.file_system.FileSync(handle); + } + + //! Path-level operations: the access is verified, then forwarded together with the opener + DUCKDB_API unique_ptr OpenFile(const string &path, const FileOpenFlags &flags); + DUCKDB_API unique_ptr OpenFile(const OpenFileInfo &file, const FileOpenFlags &flags); + DUCKDB_API unique_ptr MemoryMapFile(const OpenFileInfo &path, const FileOpenFlags &flags, + const MMapOptions &options); + + DUCKDB_API bool DirectoryExists(const string &directory); + DUCKDB_API void CreateDirectory(const string &directory); + DUCKDB_API bool CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options); + DUCKDB_API void CreateDirectoriesRecursive(const string &path); + DUCKDB_API void RemoveDirectory(const string &directory); + DUCKDB_API bool RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options); + DUCKDB_API void MoveFile(const string &source, const string &target); + DUCKDB_API bool FileExists(const string &filename); + DUCKDB_API optional GetStatsIfExists(const OpenFileInfo &file); + DUCKDB_API bool IsPipe(const string &filename); + DUCKDB_API void RemoveFile(const string &filename); + DUCKDB_API bool TryRemoveFile(const string &filename); + DUCKDB_API void RemoveFiles(const vector &filenames); + DUCKDB_API bool ListFiles(const string &directory, const std::function &callback); + DUCKDB_API bool ListFiles(const string &directory, const std::function &callback); + DUCKDB_API vector Glob(const string &path); + DUCKDB_API unique_ptr Glob(const string &path, const FileGlobInput &input); DUCKDB_API unique_ptr GlobFileList(const string &path, const FileGlobInput &input = FileGlobOptions::DISALLOW_EMPTY); DUCKDB_API vector GlobFiles(const string &pattern, const FileGlobInput &input = FileGlobOptions::DISALLOW_EMPTY); + DUCKDB_API string CanonicalizePath(const string &path); + DUCKDB_API string GetHomeDirectory(); + DUCKDB_API string ExpandPath(const string &path); - //! Whether or not a sub-system can handle a specific file path - DUCKDB_API virtual bool CanHandleFile(const string &fpath); - - //! Set the file pointer of a file handle to a specified location. Reads and writes will happen from this location - DUCKDB_API virtual void Seek(FileHandle &handle, idx_t location); - //! Reset a file to the beginning (equivalent to Seek(handle, 0) for simple files) - DUCKDB_API virtual void Reset(FileHandle &handle); - DUCKDB_API virtual idx_t SeekPosition(FileHandle &handle); - - //! If FS was manually set by the user - DUCKDB_API virtual bool IsManuallySet(); - //! Return the write ordering contract for this handle. - DUCKDB_API virtual FileWriteMode GetWriteMode(FileHandle &handle); - //! Whether or not we can seek into the file - DUCKDB_API virtual bool CanSeek(); - //! Whether or not the FS handles plain files on disk. This is relevant for certain optimizations, as random reads - //! in a file on-disk are much cheaper than e.g. random reads in a file over the network - DUCKDB_API virtual bool OnDiskFile(FileHandle &handle); - //! Try to obtain a measured network throughput estimate. Default: not supported (returns false). - //! Used for file systems - DUCKDB_API virtual bool TryGetNetworkThroughput(FileHandle &handle, NetworkThroughputEstimate &result); - - DUCKDB_API virtual unique_ptr OpenCompressedFile(QueryContext context, unique_ptr handle, - bool write); - - //! Whether this is a LocalFileSystem instance. - DUCKDB_API virtual bool IsLocalFileSystem() const; - - //! Return the name of the filesystem. Used for forming diagnosis messages. - DUCKDB_API virtual std::string GetName() const = 0; - - //! Whether or not a file is remote or local, based only on file path - DUCKDB_API static bool IsRemoteFile(const string &path); - DUCKDB_API static bool IsRemoteFile(const string &path, string &extension); - - DUCKDB_API static bool IsDirectory(const OpenFileInfo &info); - - //! Canonicalize a path - DUCKDB_API virtual string CanonicalizePath(const string &path, optional_ptr opener = nullptr); - -protected: - DUCKDB_API virtual unique_ptr OpenFileExtended(const OpenFileInfo &path, FileOpenFlags flags, - optional_ptr opener); - DUCKDB_API virtual bool SupportsOpenFileExtended() const; - - DUCKDB_API virtual bool ListFilesExtended(const string &directory, - const std::function &callback, - optional_ptr opener); - DUCKDB_API virtual bool SupportsListFilesExtended() const; + //! Path helpers that do not touch the file system + string PathSeparator(const string &path) { + return PathFileSystem(path).PathSeparator(path); + } + bool IsPathAbsolute(const string &path) { + return PathFileSystem(path).IsPathAbsolute(path); + } + //! Joining is plain string work, so it does not look up the file system of the path + DUCKDB_API string JoinPath(const string &a, const string &path); + template + string JoinPath(const string &a, const string &b, ARGS... args) { + return JoinPath(JoinPath(a, b), args...); + } + string ConvertSeparators(const string &path) { + return PathFileSystem(path).ConvertSeparators(path); + } + string ExtractBaseName(const string &path) { + return PathFileSystem(path).ExtractBaseName(path); + } + string ExtractExtension(const string &path) { + return PathFileSystem(path).ExtractExtension(path); + } + string ExtractName(const string &path) { + return PathFileSystem(path).ExtractName(path); + } - DUCKDB_API virtual unique_ptr GlobFilesExtended(const string &path, const FileGlobInput &input, - optional_ptr opener = nullptr); - DUCKDB_API virtual bool SupportsGlobExtended() const; + //! Sub-file system management + std::string GetName() const { + auto fixed_fs = GetFixedFileSystem(); + return "FileSystem - " + (fixed_fs ? fixed_fs->GetName() : GetFileSystem().GetName()); + } + void RegisterSubSystem(unique_ptr sub_fs) { + GetFileSystem().RegisterSubSystem(std::move(sub_fs)); + } + void RegisterCompressionFilesystem(unique_ptr fs); + void UnregisterSubSystem(const string &name) { + GetFileSystem().UnregisterSubSystem(name); + } + unique_ptr ExtractSubSystem(const string &name) { + return GetFileSystem().ExtractSubSystem(name); + } + void SetDisabledFileSystems(const vector &names) { + GetFileSystem().SetDisabledFileSystems(names); + } + vector GetDisabledFileSystems() { + return GetFileSystem().GetDisabledFileSystems(); + } + bool SubSystemIsDisabled(const string &name) { + return GetFileSystem().SubSystemIsDisabled(name); + } + bool IsDisabledForPath(const string &path) { + return GetFileSystem().IsDisabledForPath(path); + } + vector ListSubSystems() { + return GetFileSystem().ListSubSystems(); + } -public: template TARGET &Cast() { DynamicCastCheck(this); return reinterpret_cast(*this); } - template const TARGET &Cast() const { DynamicCastCheck(this); return reinterpret_cast(*this); } + +protected: + //! 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; + } + +private: + //! The file system that handles the path + BaseFileSystem &FindFileSystem(const string &path); + //! The file system whose path conventions apply to the path; does not verify access + BaseFileSystem &PathFileSystem(const string &path) const; + void VerifyCanAccessFileInternal(const string &path, FileType type); + unique_ptr OpenCachedFile(const OpenFileInfo &file, const FileOpenFlags &flags); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/hugeint.hpp b/src/duckdb/src/include/duckdb/common/hugeint.hpp index 1a72029db..57ef61e07 100644 --- a/src/duckdb/src/include/duckdb/common/hugeint.hpp +++ b/src/duckdb/src/include/duckdb/common/hugeint.hpp @@ -4,6 +4,7 @@ #include "duckdb/common/string.hpp" #include #include "duckdb/common/typedefs.hpp" +#include "duckdb/common/uint128_arithmetic.hpp" namespace duckdb { @@ -134,65 +135,6 @@ constexpr hugeint_t HugeintNegate(hugeint_t n) { return hugeint_t(static_cast(~static_cast(n.upper) + (n.lower == 0)), 0 - n.lower); } -constexpr int HugeintSign(hugeint_t n) { - // the sign is not decided by upper alone: upper == 0 with a non-zero lower is positive - return int(HugeintGreaterThan(n, hugeint_t(0))) - int(HugeintLessThan(n, hugeint_t(0))); -} - -constexpr hugeint_t HugeintAbs(hugeint_t n) { - return n.upper < 0 ? HugeintNegate(n) : n; -} - -constexpr hugeint_t HugeintAddOne(hugeint_t n) { - const uint64_t carry = (n.lower == UINT64_MAX) ? 1 : 0; - return hugeint_t(static_cast(static_cast(n.upper) + carry), n.lower + 1); -} - -constexpr hugeint_t HugeintSubtractOne(hugeint_t n) { - // lower wraps to UINT64_MAX, so a borrow is taken out of upper - const uint64_t borrow = (n.lower == 0) ? 1 : 0; - return hugeint_t(static_cast(static_cast(n.upper) - borrow), n.lower - 1); -} - -//! Helpers for the bit-at-a-time division, from the same uint128_t reference the -//! runtime implementation uses -constexpr uint8_t HugeintHighestBit(hugeint_t bits) { - uint8_t out = 0; - if (bits.upper) { - // bit index 64 is the lowest bit of upper - out = 64; - uint64_t up = static_cast(bits.upper); - while (up) { - up >>= 1; - out++; - } - } else { - uint64_t low = bits.lower; - while (low) { - low >>= 1; - out++; - } - } - return out; -} - -constexpr bool HugeintIsBitSet(hugeint_t lhs, uint8_t bit_position) { - if (bit_position < 64) { - return lhs.lower & (uint64_t(1) << uint64_t(bit_position)); - } - return static_cast(lhs.upper) & (uint64_t(1) << uint64_t(bit_position - 64)); -} - -//! Shift left by 1..63 bits. Called by the division loop below with amount == 1. -//! Takes no D_ASSERT: in assertion builds that macro is an unconditional function call, which -//! would make this function unusable in a constant expression. -constexpr hugeint_t HugeintLeftShift(hugeint_t lhs, uint32_t amount) { - hugeint_t result {0, 0}; - result.lower = lhs.lower << amount; - result.upper = static_cast((static_cast(lhs.upper) << amount) + (lhs.lower >> (64 - amount))); - return result; -} - constexpr hugeint_t HugeintMultiplyUnchecked(hugeint_t lhs, hugeint_t rhs) { // Unchecked multiplication uses the low 128 bits, including for negative operands. #if ((__GNUC__ >= 5) || defined(__clang__)) && defined(__SIZEOF_INT128__) @@ -258,84 +200,22 @@ struct HugeintDivModResult { hugeint_t remainder; }; -constexpr HugeintDivModResult HugeintDivMod(hugeint_t lhs, hugeint_t rhs); - -//! Precondition: lhs or rhs equals HugeintMinimum(). Only reached through HugeintDivMod. -//! Takes no D_ASSERT for the same reason as HugeintLeftShift. -constexpr HugeintDivModResult HugeintDivModMinimum(hugeint_t lhs, hugeint_t rhs) { - // rhs == MINIMUM: the quotient is 1 with remainder 0 only when lhs == MINIMUM; - // every other lhs has |lhs| < |MINIMUM|, so the quotient is 0 and the remainder is lhs - if (rhs.upper == INT64_MIN && rhs.lower == 0) { - if (lhs.upper == INT64_MIN && lhs.lower == 0) { - return HugeintDivModResult {hugeint_t(1), hugeint_t(0)}; - } - return HugeintDivModResult {hugeint_t(0), lhs}; - } - - auto shifted = HugeintDivMod(HugeintAddOne(lhs), rhs); - auto quotient = shifted.quotient; - auto remainder = shifted.remainder; - - // If the 1 mattered we need to adjust the result, otherwise the remainder - if (HugeintEquals(HugeintAddOne(HugeintAbs(remainder)), HugeintAbs(rhs))) { - quotient = HugeintSign(rhs) > 0 ? HugeintSubtractOne(quotient) : HugeintAddOne(quotient); - remainder = hugeint_t(0); - } else { - remainder = HugeintSubtractOne(remainder); - } - return HugeintDivModResult {quotient, remainder}; -} - -//! Bit-at-a-time 128-bit division, adapted from -//! https://github.com/calccrypto/uint128_t/blob/master/uint128_t.cpp +//! Signed 128-bit division truncating toward zero. Dividing by zero yields a zero quotient with lhs as the +//! remainder, and MINIMUM / -1 wraps to MINIMUM. constexpr HugeintDivModResult HugeintDivMod(hugeint_t lhs, hugeint_t rhs) { if (HugeintEquals(rhs, hugeint_t(0))) { return HugeintDivModResult {hugeint_t(0), lhs}; } - - // MINIMUM cannot be negated, so it has to be handled before any sign is stripped - if (HugeintEquals(lhs, HugeintMinimum()) || HugeintEquals(rhs, HugeintMinimum())) { - return HugeintDivModMinimum(lhs, rhs); - } - - bool lhs_negative = lhs.upper < 0; - bool rhs_negative = rhs.upper < 0; - if (lhs_negative) { - lhs = HugeintNegate(lhs); - } - if (rhs_negative) { - rhs = HugeintNegate(rhs); - } - - hugeint_t quotient {0, 0}; - hugeint_t remainder {0, 0}; - - const uint8_t highest_bit_set = HugeintHighestBit(lhs); - for (uint8_t x = highest_bit_set; x > 0; x--) { - // left-shift the current quotient and remainder by 1 - quotient = HugeintLeftShift(quotient, 1); - remainder = HugeintLeftShift(remainder, 1); - - // we get the value of the bit at position X, where position 0 is the least-significant bit - if (HugeintIsBitSet(lhs, x - 1)) { - remainder.lower += 1; - if (remainder.lower == 0) { - remainder.upper += 1; - } - } - if (HugeintGreaterThanEquals(remainder, rhs)) { - // the remainder has passed the division multiplier: subtract the divisor, - // carrying a borrow out of lower, and add one to the quotient - const int64_t borrow = remainder.lower < rhs.lower ? 1 : 0; - remainder.lower -= rhs.lower; - remainder.upper -= rhs.upper + borrow; - quotient.lower += 1; - if (quotient.lower == 0) { - quotient.upper += 1; - } - } - } - if (lhs_negative ^ rhs_negative) { + const bool lhs_negative = lhs.upper < 0; + const bool rhs_negative = rhs.upper < 0; + // MINIMUM negates to itself, and its bits read as unsigned are its magnitude 2^127 + const hugeint_t lhs_abs = lhs_negative ? HugeintNegate(lhs) : lhs; + const hugeint_t rhs_abs = rhs_negative ? HugeintNegate(rhs) : rhs; + const auto result = Uint128DivMod(static_cast(lhs_abs.upper), lhs_abs.lower, + static_cast(rhs_abs.upper), rhs_abs.lower); + hugeint_t quotient(static_cast(result.quotient_upper), result.quotient_lower); + hugeint_t remainder(static_cast(result.remainder_upper), result.remainder_lower); + if (lhs_negative != rhs_negative) { quotient = HugeintNegate(quotient); } if (lhs_negative) { diff --git a/src/duckdb/src/include/duckdb/common/in_clause.hpp b/src/duckdb/src/include/duckdb/common/in_clause.hpp new file mode 100644 index 000000000..71fa2a7c0 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/in_clause.hpp @@ -0,0 +1,19 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/in_clause.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/typedefs.hpp" + +namespace duckdb { + +//! Minimum IN child count (including the probe) for rewriting a scalar list to a hash join. +//! Scan-filter evaluation uses the same cutoff for small literal lists. +static constexpr idx_t IN_CLAUSE_REWRITE_THRESHOLD = 6; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/local_file_system.hpp b/src/duckdb/src/include/duckdb/common/local_file_system.hpp index d4f76a057..67f47fa7f 100644 --- a/src/duckdb/src/include/duckdb/common/local_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/local_file_system.hpp @@ -8,19 +8,17 @@ #pragma once -#include "duckdb/common/file_system.hpp" +#include "duckdb/common/base_file_system.hpp" #include "duckdb/common/windows_undefs.hpp" namespace duckdb { -class LocalFileSystem : public FileSystem { +class LocalFileSystem : public BaseFileSystem { public: - unique_ptr OpenFile(const string &path, FileOpenFlags flags, - optional_ptr opener = nullptr) override; + unique_ptr OpenFile(const string &path, FileOpenFlags flags, optional_ptr opener) override; unique_ptr MemoryMapFile(const OpenFileInfo &path, FileOpenFlags flags, - const MMapOptions &options, - optional_ptr opener = nullptr) override; + const MMapOptions &options, optional_ptr opener) override; //! Read exactly nr_bytes from the specified location in the file. Fails if nr_bytes could not be read. This is //! equivalent to calling SetFilePointer(location) followed by calling Read(). @@ -49,33 +47,32 @@ class LocalFileSystem : public FileSystem { FileType GetFileType(FileHandle &handle) override; //! Returns the file stats of the attached handle. FileMetadata Stats(FileHandle &handle) override; - optional GetStatsIfExists(const OpenFileInfo &file, - optional_ptr opener = nullptr) override; + optional GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) override; //! Truncate a file to a maximum size of new_size, new_size should be smaller than or equal to the current size of //! the file void Truncate(FileHandle &handle, int64_t new_size) override; //! Check if a directory exists - bool DirectoryExists(const string &directory, optional_ptr opener = nullptr) override; + bool DirectoryExists(const string &directory, optional_ptr opener) override; //! Create a directory if it does not exist - void CreateDirectory(const string &directory, optional_ptr opener = nullptr) 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; + optional_ptr opener) override; + void CreateDirectoriesRecursive(const string &path, optional_ptr opener) override; //! Recursively remove a directory and all files in it - void RemoveDirectory(const string &directory, 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; + optional_ptr opener) override; //! Move a file from source path to the target, StorageManager relies on this being an atomic action for ACID //! properties - void MoveFile(const string &source, const string &target, optional_ptr opener = nullptr) override; + void MoveFile(const string &source, const string &target, optional_ptr opener) override; //! Check if a file exists - bool FileExists(const string &filename, optional_ptr opener = nullptr) override; + bool FileExists(const string &filename, optional_ptr opener) override; //! Check if path is a pipe or character device - bool IsPipe(const string &filename, optional_ptr opener = nullptr) override; + bool IsPipe(const string &filename, optional_ptr opener) override; //! Remove a file from disk - void RemoveFile(const string &filename, optional_ptr opener = nullptr) override; + void RemoveFile(const string &filename, optional_ptr opener) override; //! Sync a file handle to disk void FileSync(FileHandle &handle) override; //! Close and remove an incomplete output file diff --git a/src/duckdb/src/include/duckdb/common/opener_file_system.hpp b/src/duckdb/src/include/duckdb/common/opener_file_system.hpp deleted file mode 100644 index e45ebaf9f..000000000 --- a/src/duckdb/src/include/duckdb/common/opener_file_system.hpp +++ /dev/null @@ -1,304 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/common/opener_file_system.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/file_system.hpp" -#include "duckdb/common/virtual_file_system.hpp" - -namespace duckdb { -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: - void VerifyNoOpener(optional_ptr opener); - void VerifyCanAccessDirectory(const string &path); - void VerifyCanAccessFile(const string &path); - void VerifyCanAccessExtension(const string &path, const FileOpenFlags &flags) { - if (flags.OpenForWriting() && !flags.EnableExtensionInstall()) { - throw PermissionException( - "File '%s' cannot be opened for writing since files ending with '.duckdb_extension' are reserved for " - "DuckDB extensions, and these can only be installed through the INSTALL command", - path); - } - } - - //! Reserved for DuckDB's extension trust domain: the loadable binary and every file that decides whether it may - //! be loaded (install provenance, trusted repositories). These can only be written through INSTALL / CREATE - //! EXTENSION REPOSITORY, which pass FILE_FLAGS_ENABLE_EXTENSION_INSTALL. - //! To add a file to the trust domain, give it a ".duckdb_extension." segment, e.g. - //! ".duckdb_extension.info" or ".duckdb_extension.repo.json". Matching is on the file name only, so a - //! directory that happens to contain the marker does not reserve the files inside it - bool IsDuckDBExtensionName(const string &path) { - // match the canonical name case-insensitively: on the default macOS and Windows file systems a - // differently-cased name refers to the same file - auto name = StringUtil::Lower(FileSystem::ExtractName(CanonicalizePath(path))); - return StringUtil::EndsWith(name, ".duckdb_extension") || StringUtil::Contains(name, ".duckdb_extension."); - } - - void Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) override { - handle.file_system.Read(handle, buffer, nr_bytes, location); - } - - void Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) override { - throw InternalException("writing on the OpenerFileSystem is undefined"); - } - - int64_t Read(FileHandle &handle, void *buffer, int64_t nr_bytes) override { - return handle.file_system.Read(handle, buffer, nr_bytes); - } - - int64_t Write(FileHandle &handle, void *buffer, int64_t nr_bytes) override { - return handle.file_system.Write(handle, buffer, nr_bytes); - } - - int64_t GetFileSize(FileHandle &handle) override { - return handle.file_system.GetFileSize(handle); - } - timestamp_t GetLastModifiedTime(FileHandle &handle) override { - return handle.file_system.GetLastModifiedTime(handle); - } - string GetVersionTag(FileHandle &handle) override { - return handle.file_system.GetVersionTag(handle); - } - FileType GetFileType(FileHandle &handle) override { - return handle.file_system.GetFileType(handle); - } - FileMetadata Stats(FileHandle &handle) override { - return handle.file_system.Stats(handle); - } - - void Truncate(FileHandle &handle, int64_t new_size) override { - handle.file_system.Truncate(handle, new_size); - } - - void FileSync(FileHandle &handle) override { - handle.file_system.FileSync(handle); - } - - bool DirectoryExists(const string &directory, optional_ptr opener) override { - VerifyNoOpener(opener); - VerifyCanAccessDirectory(directory); - return FindFileSystem(directory).DirectoryExists(directory, GetOpener()); - } - void CreateDirectory(const string &directory, optional_ptr opener) override { - CreateDirectoryExtended(directory, {CreateDirectoryMode::SINGLE}, opener); - } - bool CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener) override { - if (options.mode == CreateDirectoryMode::RECURSIVE) { - return FileSystem::CreateDirectoryExtended(directory, options, opener); - } - VerifyNoOpener(opener); - VerifyCanAccessDirectory(directory); - return FindFileSystem(directory).CreateDirectoryExtended(directory, options, GetOpener()); - } - void CreateDirectoriesRecursive(const string &path, optional_ptr opener = nullptr) override { - CreateDirectoryExtended(path, {CreateDirectoryMode::RECURSIVE}, opener); - } - - void RemoveDirectory(const string &directory, optional_ptr opener) override { - RemoveDirectoryExtended(directory, {RemoveDirectoryMode::RECURSIVE}, opener); - } - bool RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener) override { - VerifyNoOpener(opener); - VerifyCanAccessDirectory(directory); - return FindFileSystem(directory).RemoveDirectoryExtended(directory, options, GetOpener()); - } - - void MoveFile(const string &source, const string &target, optional_ptr opener) override { - VerifyNoOpener(opener); - VerifyCanAccessFile(source); - VerifyCanAccessFile(target); - if (IsDuckDBExtensionName(target) && !IsDuckDBExtensionName(source)) { - throw PermissionException( - "File '%s' cannot be moved to '%s', files ending with '.duckdb_extension' are reserved for DuckDB " - "extensions, and these can only be installed through the INSTALL command, or moved if both are " - "extensions'", - source, target); - } - FindFileSystem(source).MoveFile(source, target, GetOpener()); - } - - bool DirectoryExists(const string &directory) { - return DirectoryExists(directory, nullptr); - } - void CreateDirectory(const string &directory) { - CreateDirectory(directory, nullptr); - } - bool CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options) { - return CreateDirectoryExtended(directory, options, nullptr); - } - void RemoveDirectory(const string &directory) { - RemoveDirectory(directory, nullptr); - } - bool RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options) { - return RemoveDirectoryExtended(directory, options, nullptr); - } - void MoveFile(const string &source, const string &target) { - MoveFile(source, target, nullptr); - } - optional GetStatsIfExists(const OpenFileInfo &file) { - return GetStatsIfExists(file, nullptr); - } - bool FileExists(const string &filename) { - return FileExists(filename, nullptr); - } - bool IsPipe(const string &filename) { - return IsPipe(filename, nullptr); - } - void RemoveFile(const string &filename) { - RemoveFile(filename, nullptr); - } - bool TryRemoveFile(const string &filename) { - return TryRemoveFile(filename, nullptr); - } - void RemoveFiles(const vector &filenames) { - RemoveFiles(filenames, nullptr); - } - - string GetHomeDirectory() override { - return FileSystem::GetHomeDirectory(GetOpener()); - } - - string ExpandPath(const string &path) override { - return FileSystem::ExpandPath(path, GetOpener()); - } - - bool FileExists(const string &filename, optional_ptr opener) override { - VerifyNoOpener(opener); - VerifyCanAccessFile(filename); - return FindFileSystem(filename).FileExists(filename, GetOpener()); - } - - optional GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) override { - VerifyNoOpener(opener); - VerifyCanAccessFile(file.path); - return FindFileSystem(file.path).GetStatsIfExists(file, GetOpener()); - } - - bool IsPipe(const string &filename, optional_ptr opener) override { - VerifyNoOpener(opener); - return FindFileSystem(filename).IsPipe(filename, GetOpener()); - } - void RemoveFile(const string &filename, optional_ptr opener) override { - VerifyNoOpener(opener); - VerifyCanAccessFile(filename); - FindFileSystem(filename).RemoveFile(filename, GetOpener()); - } - - bool TryRemoveFile(const string &filename, optional_ptr opener) override { - VerifyNoOpener(opener); - VerifyCanAccessFile(filename); - 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()); - } - } - - string PathSeparator(const string &path) override { - 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 FindFileSystem(path).Glob(path, GetOpener().get()); - } - - std::string GetName() const override { - auto fixed_fs = GetFixedFileSystem(); - return "OpenerFileSystem - " + (fixed_fs ? fixed_fs->GetName() : GetFileSystem().GetName()); - } - -protected: - unique_ptr OpenFileExtended(const OpenFileInfo &file, FileOpenFlags flags, - optional_ptr opener = nullptr) override { - VerifyNoOpener(opener); - VerifyCanAccessFile(file.path); - if (IsDuckDBExtensionName(file.path)) { - VerifyCanAccessExtension(file.path, flags); - } - 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 { - return true; - } - -public: - unique_ptr MemoryMapFile(const OpenFileInfo &path, FileOpenFlags flags, - const MMapOptions &options, - optional_ptr opener = nullptr) override; - -protected: - bool ListFilesExtended(const string &directory, const std::function &callback, - optional_ptr opener) override { - VerifyNoOpener(opener); - VerifyCanAccessDirectory(directory); - return FindFileSystem(directory).ListFiles(directory, callback, GetOpener()); - } - - 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; - } - - string CanonicalizePath(const string &path_p, optional_ptr opener = nullptr) override { - VerifyNoOpener(opener); - 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); -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/operator/decimal_cast_operators.hpp b/src/duckdb/src/include/duckdb/common/operator/decimal_cast_operators.hpp index 22bfdfff0..500b808b1 100644 --- a/src/duckdb/src/include/duckdb/common/operator/decimal_cast_operators.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/decimal_cast_operators.hpp @@ -743,9 +743,18 @@ struct DecimalCastOperation { return true; } else { // positive exponent: append 0's - for (idx_t i = 0; i < idx_t(exponent); i++) { - if (!HandleDigit(state, 0)) { - return false; + if (state.result != 0) { + for (idx_t i = 0; i < idx_t(exponent); i++) { + if (NEGATIVE) { + if (state.result < DecimalCastLimits::MinimumDiv10) { + return false; + } + } else { + if (state.result > DecimalCastLimits::MaximumDiv10) { + return false; + } + } + state.result *= 10; } } // decimals moved before the decimal point by the exponent do not count towards the digit count @@ -766,9 +775,15 @@ struct DecimalCastOperation { // we just truncate the decimal return true; } + if (state.result == 0 && digit == 0) { + // leading zeros after the decimal point still advance decimal_count + state.decimal_count++; + return true; + } //! If we expect an exponent, we need to preserve the decimals //! But we don't want to overflow, so we prevent overflowing the result with this check - if (state.digit_count + state.decimal_count >= DecimalWidth::max) { + if (NEGATIVE ? state.result <= DecimalCastLimits::MinimumDiv10 + : state.result >= DecimalCastLimits::MaximumDiv10) { return true; } state.decimal_count++; diff --git a/src/duckdb/src/include/duckdb/common/pipe_file_system.hpp b/src/duckdb/src/include/duckdb/common/pipe_file_system.hpp index e300435a2..68d9223d0 100644 --- a/src/duckdb/src/include/duckdb/common/pipe_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/pipe_file_system.hpp @@ -8,11 +8,11 @@ #pragma once -#include "duckdb/common/file_system.hpp" +#include "duckdb/common/base_file_system.hpp" namespace duckdb { -class PipeFileSystem : public FileSystem { +class PipeFileSystem : public BaseFileSystem { public: static unique_ptr OpenPipe(QueryContext context, unique_ptr handle); diff --git a/src/duckdb/src/include/duckdb/common/serializer/buffered_file_reader.hpp b/src/duckdb/src/include/duckdb/common/serializer/buffered_file_reader.hpp index e17b52cfd..5295bd547 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/buffered_file_reader.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/buffered_file_reader.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/file_system.hpp" #include "duckdb/common/serializer/buffered_file_writer.hpp" #include "duckdb/common/serializer/read_stream.hpp" @@ -15,8 +16,7 @@ namespace duckdb { class BufferedFileReader : public ReadStream { public: - BufferedFileReader(FileSystem &fs, const char *path, FileLockType lock_type = FileLockType::READ_LOCK, - optional_ptr opener = nullptr); + BufferedFileReader(FileSystem &fs, const char *path, FileLockType lock_type = FileLockType::READ_LOCK); BufferedFileReader(FileSystem &fs, unique_ptr handle); FileSystem &fs; diff --git a/src/duckdb/src/include/duckdb/common/types.hpp b/src/duckdb/src/include/duckdb/common/types.hpp index 5b5d6246f..0bc4f80ca 100644 --- a/src/duckdb/src/include/duckdb/common/types.hpp +++ b/src/duckdb/src/include/duckdb/common/types.hpp @@ -314,7 +314,7 @@ struct LogicalTypeInfo { return; } auto previous = ref_count.fetch_add(1, std::memory_order_relaxed); - D_ASSERT(previous < std::numeric_limits::max()); + D_ASSERT(previous < (std::numeric_limits::max)()); (void)previous; } inline void Release() const { diff --git a/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp b/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp index f9bad23ca..d16961eb6 100644 --- a/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp +++ b/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp @@ -104,6 +104,9 @@ struct DecimalHelper { RoundState &state, bignum_t &result) { return TryRound(value, drop_digits, restore_digits, ROUNDING, width, state, result); } + //! Divides a value by a positive divisor and rounds the quotient as requested, the result lives in the heap + DUCKDB_API static string_t DivideAndRound(const BignumIntermediate &source, const BignumIntermediate &divisor, + DecimalRounding rounding, StringHeap &heap, BignumArithmeticState &state); //! Rescales an unscaled value to target_scale (rounding half away from zero), the result is the BIGNUM blob of the //! rescaled value DUCKDB_API static string Rescale(const bignum_t &value, uint32_t source_scale, uint32_t target_scale, diff --git a/src/duckdb/src/include/duckdb/common/types/date.hpp b/src/duckdb/src/include/duckdb/common/types/date.hpp index 412291757..f3a76863d 100644 --- a/src/duckdb/src/include/duckdb/common/types/date.hpp +++ b/src/duckdb/src/include/duckdb/common/types/date.hpp @@ -110,7 +110,9 @@ class Date { static const int8_t MONTH_PER_DAY_OF_YEAR[365]; static const int8_t LEAP_MONTH_PER_DAY_OF_YEAR[366]; - // min date is 5877642-06-25 (BC) (-2^31+2) + // min well-behaved date is 5877642-06-25 (BC) (-2^31+2): the day below it, 5877642-06-24 (BC), is the + // -infinity sentinel (-2^31+1), and the smallest representable date is 5877642-06-23 (BC) (-2^31), + // which sorts below -infinity constexpr static const int32_t DATE_MIN_YEAR = -5877641; constexpr static const int32_t DATE_MIN_MONTH = 6; constexpr static const int32_t DATE_MIN_DAY = 25; 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 4c4082a27..7b17d9800 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 @@ -534,10 +534,11 @@ struct VariantBuilder { //===--------------------------------------------------------------------===// // Emit (source: a VariantNode-like cursor) //===--------------------------------------------------------------------===// -//! Collect the (non-missing) object children of a node in lexicographic key order +//! Collect the (non-missing) object children of a node - the key order of an object is not significant, so the +//! children are emitted in the order they are stored template auto CollectObjectChildren(const NODE &it) { - auto object = it.GetObjectChildren(VariantIterationOrder::LEXICOGRAPHIC); + auto object = it.GetObjectChildren(VariantIterationOrder::INTERNAL); using EntryT = std::decay_t; vector children; for (auto &entry : object) { 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 2b783106f..1ca672ed0 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp @@ -254,10 +254,12 @@ class VariantVisitor { } } + //! Visits the children of an object. The key order of an object is not significant, so converters that produce + //! output the user sees (text, JSON, values) ask for LEXICOGRAPHIC order to be independent of the stored order template static child_list_t VisitObjectItems(const UnifiedVariantVectorData &variant, idx_t row, const VariantNestedData &object_data, idx_t depth, - Args &&...args) { + VariantIterationOrder order, Args &&...args) { child_list_t object_items; for (idx_t i = 0; i < object_data.child_count; i++) { auto values_index = variant.GetValuesIndex(row, object_data.children_idx + i); @@ -268,11 +270,13 @@ class VariantVisitor { object_items.emplace_back(key.GetString(), std::move(val)); } - std::stable_sort( - object_items.begin(), object_items.end(), - [](const std::pair &lhs, const std::pair &rhs) { - return lhs.first.GetIdentifierName() < rhs.first.GetIdentifierName(); - }); + if (order == VariantIterationOrder::LEXICOGRAPHIC) { + std::stable_sort( + object_items.begin(), object_items.end(), + [](const std::pair &lhs, const std::pair &rhs) { + return lhs.first.GetIdentifierName() < rhs.first.GetIdentifierName(); + }); + } return object_items; } diff --git a/src/duckdb/src/include/duckdb/common/uint128_arithmetic.hpp b/src/duckdb/src/include/duckdb/common/uint128_arithmetic.hpp new file mode 100644 index 000000000..691768833 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/uint128_arithmetic.hpp @@ -0,0 +1,164 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/uint128_arithmetic.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include + +namespace duckdb { + +//! Result of an unsigned 128-bit division, split into 64-bit halves +struct Uint128DivModResult { + uint64_t quotient_upper; + uint64_t quotient_lower; + uint64_t remainder_upper; + uint64_t remainder_lower; +}; + +//! The number of leading zero bits of a non-zero value +constexpr uint32_t Uint64LeadingZeros(uint64_t value) { +#if defined(__GNUC__) || defined(__clang__) + return static_cast(__builtin_clzll(value)); +#else + uint32_t count = 0; + for (uint32_t step = 32; step > 0; step >>= 1) { + if (!(value >> (64 - step))) { + value <<= step; + count += step; + } + } + return count; +#endif +} + +//! Returns the low 64 bits of a * b and sets high to its high 64 bits +constexpr uint64_t Uint64MultiplyFull(uint64_t a, uint64_t b, uint64_t &high) { +#if ((__GNUC__ >= 5) || defined(__clang__)) && defined(__SIZEOF_INT128__) + const auto product = static_cast<__uint128_t>(a) * b; + high = static_cast(product >> 64); + return static_cast(product); +#else + constexpr uint64_t HALF_MASK = 0xFFFFFFFFULL; + const uint64_t low_low = (a & HALF_MASK) * (b & HALF_MASK); + const uint64_t low_high = (a & HALF_MASK) * (b >> 32); + const uint64_t high_low = (a >> 32) * (b & HALF_MASK); + const uint64_t high_high = (a >> 32) * (b >> 32); + const uint64_t middle = (low_low >> 32) + (low_high & HALF_MASK) + (high_low & HALF_MASK); + high = high_high + (low_high >> 32) + (high_low >> 32) + (middle >> 32); + return (low_low & HALF_MASK) | (middle << 32); +#endif +} + +//! Divides high * 2^64 + low by a divisor larger than high, so that the quotient fits 64 bits; sets the remainder. +//! Two base 2^32 steps (Hacker's Delight divlu). +// no D_ASSERT: must stay usable in constant expressions +constexpr uint64_t Uint128DivRem64Portable(uint64_t high, uint64_t low, uint64_t divisor, uint64_t &remainder) { + constexpr uint64_t HALF_BASE = static_cast(1) << 32; + constexpr uint64_t HALF_MASK = HALF_BASE - 1; + // normalize so that the divisor has its top bit set; the quotient is unchanged, the remainder is scaled + const uint32_t shift = Uint64LeadingZeros(divisor); + if (shift > 0) { + divisor <<= shift; + high = (high << shift) | (low >> (64 - shift)); + low <<= shift; + } + const uint64_t divisor_high = divisor >> 32; + const uint64_t divisor_low = divisor & HALF_MASK; + const uint64_t low_high = low >> 32; + const uint64_t low_low = low & HALF_MASK; + // the high half of the quotient: an estimate from the top halves that is corrected down until it is exact + uint64_t q_high = high / divisor_high; + uint64_t rhat = high - q_high * divisor_high; + while (q_high >= HALF_BASE || q_high * divisor_low > ((rhat << 32) | low_high)) { + q_high--; + rhat += divisor_high; + if (rhat >= HALF_BASE) { + break; + } + } + // the partial remainder is below the divisor, so the wrapping arithmetic yields the exact value + const uint64_t middle = (high << 32) + low_high - q_high * divisor; + uint64_t q_low = middle / divisor_high; + rhat = middle - q_low * divisor_high; + while (q_low >= HALF_BASE || q_low * divisor_low > ((rhat << 32) | low_low)) { + q_low--; + rhat += divisor_high; + if (rhat >= HALF_BASE) { + break; + } + } + remainder = ((middle << 32) + low_low - q_low * divisor) >> shift; + return (q_high << 32) | q_low; +} + +//! Divides high * 2^64 + low by a divisor larger than high, so that the quotient fits 64 bits; sets the remainder +constexpr uint64_t Uint128DivRem64(uint64_t high, uint64_t low, uint64_t divisor, uint64_t &remainder) { + // clang-cl has the 128-bit type but links no runtime support for dividing it +#if ((__GNUC__ >= 5) || defined(__clang__)) && defined(__SIZEOF_INT128__) && !defined(_MSC_VER) + const auto quotient = static_cast(((static_cast<__uint128_t>(high) << 64) | low) / divisor); + remainder = low - quotient * divisor; + return quotient; +#else + return Uint128DivRem64Portable(high, low, divisor, remainder); +#endif +} + +//! Unsigned 128-bit division by a divisor of at least 2^64, so that the quotient fits 64 bits (Hacker's Delight +//! divDouble): the quotient is estimated from the normalized top bits of the divisor and corrected by at most one. +constexpr Uint128DivModResult Uint128DivModLargeDivisor(uint64_t lhs_upper, uint64_t lhs_lower, uint64_t rhs_upper, + uint64_t rhs_lower) { + if (lhs_upper < rhs_upper) { + return Uint128DivModResult {0, 0, lhs_upper, lhs_lower}; + } + const uint32_t shift = Uint64LeadingZeros(rhs_upper); + const uint64_t divisor_top = shift == 0 ? rhs_upper : (rhs_upper << shift) | (rhs_lower >> (64 - shift)); + // halving keeps the high half of the dividend below the normalized divisor, as the 128-by-64-bit step requires + uint64_t unused_remainder = 0; + const uint64_t estimate = + Uint128DivRem64(lhs_upper >> 1, (lhs_upper << 63) | (lhs_lower >> 1), divisor_top, unused_remainder); + uint64_t quotient = estimate >> (63 - shift); + if (quotient != 0) { + quotient--; + } + // the quotient does not exceed the exact one, so the product fits 128 bits and the remainder is non-negative + uint64_t product_upper = 0; + const uint64_t product_lower = Uint64MultiplyFull(quotient, rhs_lower, product_upper); + product_upper += quotient * rhs_upper; + uint64_t remainder_lower = lhs_lower - product_lower; + uint64_t remainder_upper = lhs_upper - product_upper - (lhs_lower < product_lower ? 1 : 0); + if (remainder_upper > rhs_upper || (remainder_upper == rhs_upper && remainder_lower >= rhs_lower)) { + const uint64_t borrow = remainder_lower < rhs_lower ? 1 : 0; + remainder_lower -= rhs_lower; + remainder_upper -= rhs_upper + borrow; + quotient++; + } + return Uint128DivModResult {0, quotient, remainder_upper, remainder_lower}; +} + +//! Unsigned division of a 128-bit dividend by a non-zero 64-bit divisor +constexpr Uint128DivModResult Uint128DivModSmallDivisor(uint64_t lhs_upper, uint64_t lhs_lower, uint64_t divisor) { + if (lhs_upper == 0) { + return Uint128DivModResult {0, lhs_lower / divisor, 0, lhs_lower % divisor}; + } + // the high step leaves a remainder below the divisor, as the low step requires + const uint64_t quotient_upper = lhs_upper / divisor; + uint64_t remainder = 0; + const uint64_t quotient_lower = Uint128DivRem64(lhs_upper % divisor, lhs_lower, divisor, remainder); + return Uint128DivModResult {quotient_upper, quotient_lower, 0, remainder}; +} + +//! Unsigned 128-bit division. Precondition: the divisor is not zero. +constexpr Uint128DivModResult Uint128DivMod(uint64_t lhs_upper, uint64_t lhs_lower, uint64_t rhs_upper, + uint64_t rhs_lower) { + if (rhs_upper != 0) { + return Uint128DivModLargeDivisor(lhs_upper, lhs_lower, rhs_upper, rhs_lower); + } + return Uint128DivModSmallDivisor(lhs_upper, lhs_lower, rhs_lower); +} + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/vector_operations/aggregate_executor.hpp b/src/duckdb/src/include/duckdb/common/vector_operations/aggregate_executor.hpp index f7f577c30..959707b7f 100644 --- a/src/duckdb/src/include/duckdb/common/vector_operations/aggregate_executor.hpp +++ b/src/duckdb/src/include/duckdb/common/vector_operations/aggregate_executor.hpp @@ -935,6 +935,10 @@ class AggregateExecutor { return *reinterpret_cast(storage); } + AggregateInputData &GetInput() { + return aggr_input_data; + } + void Initialize() { D_ASSERT(!initialized); InitializeState(Get()); @@ -955,34 +959,56 @@ class AggregateExecutor { bool initialized = false; }; + //! Whether the aggregate's combine never leaves the target referencing the source's memory + DUCKDB_API static bool CombineNeverRetainsSource(const AggregateInputData &aggr_input_data); + template static void GenericRepeatedCombine(const STATE_TYPE &source, STATE_TYPE &target, AggregateInputData &aggr_input_data, idx_t multiplicity) { AggregateInputData combine_input(aggr_input_data.function, aggr_input_data.bind_data, aggr_input_data.allocator, AggregateCombineType::PRESERVE_INPUT); + // if the final combine copies what the target keeps, each intermediate state gets a scratch arena, which is + // reset when the state is replaced + const bool scratch = CombineNeverRetainsSource(aggr_input_data); + auto &underlying_allocator = aggr_input_data.allocator.GetUnderlyingAllocator(); + ArenaAllocator result_arena(underlying_allocator); + ArenaAllocator power_arena_a(underlying_allocator); + ArenaAllocator power_arena_b(underlying_allocator); + AggregateInputData result_input(aggr_input_data.function, aggr_input_data.bind_data, + scratch ? result_arena : aggr_input_data.allocator, + AggregateCombineType::PRESERVE_INPUT); + AggregateInputData power_input_a(aggr_input_data.function, aggr_input_data.bind_data, + scratch ? power_arena_a : aggr_input_data.allocator, + AggregateCombineType::PRESERVE_INPUT); + AggregateInputData power_input_b(aggr_input_data.function, aggr_input_data.bind_data, + scratch ? power_arena_b : aggr_input_data.allocator, + AggregateCombineType::PRESERVE_INPUT); - AggregateStateGuard result(combine_input); - AggregateStateGuard power_a(combine_input); - AggregateStateGuard power_b(combine_input); + AggregateStateGuard result(result_input); + AggregateStateGuard power_a(power_input_a); + AggregateStateGuard power_b(power_input_b); result.Initialize(); power_a.Initialize(); - OP::template Combine(source, power_a.Get(), combine_input); + OP::template Combine(source, power_a.Get(), power_input_a); auto power = &power_a; auto next_power = &power_b; while (multiplicity > 0) { if (multiplicity & 1) { - OP::template Combine(power->Get(), result.Get(), combine_input); + OP::template Combine(power->Get(), result.Get(), result_input); } multiplicity >>= 1; if (multiplicity == 0) { break; } next_power->Initialize(); - OP::template Combine(power->Get(), next_power->Get(), combine_input); - OP::template Combine(power->Get(), next_power->Get(), combine_input); + OP::template Combine(power->Get(), next_power->Get(), next_power->GetInput()); + OP::template Combine(power->Get(), next_power->Get(), next_power->GetInput()); power->Destroy(); + if (scratch) { + power->GetInput().allocator.Reset(); + } std::swap(power, next_power); } OP::template Combine(result.Get(), target, combine_input); 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 2ce661973..cef8b5dc6 100644 --- a/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp @@ -8,7 +8,7 @@ #pragma once -#include "duckdb/common/file_system.hpp" +#include "duckdb/common/base_file_system.hpp" #include "duckdb/common/map.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/common/mutex.hpp" @@ -20,11 +20,11 @@ class ClientContext; //! 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. +//! compression. It is not a BaseFileSystem itself: the files it opens belong to the file system that handled them. class VirtualFileSystem { public: DUCKDB_API VirtualFileSystem(); - DUCKDB_API explicit VirtualFileSystem(unique_ptr &&inner_file_system); + DUCKDB_API explicit VirtualFileSystem(unique_ptr &&inner_file_system); DUCKDB_API ~VirtualFileSystem(); //! The root file system of a database @@ -39,12 +39,12 @@ class VirtualFileSystem { 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 BaseFileSystem &FindFileSystem(const string &path, optional_ptr opener); - DUCKDB_API void RegisterSubSystem(unique_ptr fs); + 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 unique_ptr ExtractSubSystem(const string &name); DUCKDB_API vector ListSubSystems(); DUCKDB_API void SetDisabledFileSystems(const vector &names); @@ -53,24 +53,24 @@ class VirtualFileSystem { 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 BaseFileSystem &GetDefaultFileSystem(); DUCKDB_API std::string GetName() const; private: - FileSystem &FindFileSystem(shared_ptr ®istry, const string &path, - optional_ptr file_opener); - optional_ptr FindFileSystemInternal(FileSystemRegistry ®istry, const string &path); + BaseFileSystem &FindFileSystem(shared_ptr ®istry, const string &path, + optional_ptr file_opener); + optional_ptr FindFileSystemInternal(FileSystemRegistry ®istry, const string &path); // Return nullptr if compression is not involved, throw exception if compression is requested but no usable // filesystem gets registered. - optional_ptr FindCompressionFileSystem(FileSystemRegistry ®istry, - const FileCompressionType &compression, const string &path, - bool for_writing); + optional_ptr FindCompressionFileSystem(FileSystemRegistry ®istry, + const FileCompressionType &compression, const string &path, + bool for_writing); private: mutex registry_lock; shared_ptr file_system_registry; - vector> unregistered_file_systems; + vector> unregistered_file_systems; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/aggregate_state_spilling.hpp b/src/duckdb/src/include/duckdb/execution/aggregate_state_spilling.hpp index 4cb4c6315..02dc2d9a7 100644 --- a/src/duckdb/src/include/duckdb/execution/aggregate_state_spilling.hpp +++ b/src/duckdb/src/include/duckdb/execution/aggregate_state_spilling.hpp @@ -10,7 +10,7 @@ #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/common/types/row/partitioned_tuple_data.hpp" -#include "duckdb/function/aggregate_state_layout.hpp" +#include "duckdb/function/aggregate_state_serialization.hpp" #include @@ -21,7 +21,8 @@ class ClientContext; //! The immutable spill metadata of an aggregate layout: its state export layouts and the types //! of the spillable columnar representation (the group columns and hash, then one column per state) struct AggregateStateSpillPlan { - vector state_layouts; + //! Per aggregate: for combine_aggr, the serializer of the aggregate it combines + vector serializers; vector exported_types; }; 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 90262448f..216ce2b47 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/art.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/art.hpp @@ -95,7 +95,7 @@ class ART : public BoundIndex { void RemovalMerge(BoundIndex &source_index) DUCKDB_EXCLUDES(lock); //! Simple merge: scan source ART and insert each (key, rowid) into this ART. //! Returns error data if constraint violation. - // FIXME: This is only used in MergeCheckpointDeltas, and even then it is used in lieu of the existing + // FIXME: This is only used to merge deltas, and even then it is used in lieu of the existing // MergeIndexes which don't support deprecated leaf chains. Once support for that is added, this simpler insert // merge may be removed. ErrorData InsertMerge(IndexLock &state, BoundIndex &source_index, IndexAppendMode append_mode) @@ -162,7 +162,7 @@ class ART : public BoundIndex { protected: unique_ptr CreateEmptyCopy(IndexConstraintType constraint_type) const override; - ErrorData MergeCheckpointDelta(IndexDeltaType type, BoundIndex &delta_index) override; + ErrorData MergeDelta(IndexDeltaType type, BoundIndex &delta_index, IndexAppendMode append_mode) override; public: //! ART key generation. diff --git a/src/duckdb/src/include/duckdb/execution/index/art/art_builder.hpp b/src/duckdb/src/include/duckdb/execution/index/art/art_builder.hpp index 21e00d1c8..f9021e5d4 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/art_builder.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/art_builder.hpp @@ -21,9 +21,10 @@ class ARTBuilder { } public: - //! Initialize the ART builder by passing a reference to the root node. + //! Initialize the ART builder with the root, which the first entry writes into. void Init(NodePtr &node_ptr, const idx_t end) { - s.emplace(node_ptr, 0, end, 0); + root_ptr = node_ptr; + s.emplace(NodePtr(), 0, 0, end, 0); } //! Build the ART starting at the first entry in the stack. ARTConflictType Build(); @@ -31,15 +32,23 @@ class ARTBuilder { private: struct NodeEntry { NodeEntry() = delete; - NodeEntry(NodePtr &node_ptr, const idx_t start, const idx_t end, const idx_t depth) - : node_ptr(node_ptr), start(start), end(end), depth(depth) {}; + NodeEntry(const NodePtr parent_ptr, const uint8_t byte, const idx_t start, const idx_t end, const idx_t depth) + : parent_ptr(parent_ptr), byte(byte), start(start), end(end), depth(depth) {}; - NodePtr &node_ptr; + //! The parent node, or an empty NodePtr for the root entry. + NodePtr parent_ptr; + //! The byte of the parent's empty child that receives this entry's subtree. + uint8_t byte; idx_t start; idx_t end; idx_t depth; }; +private: + //! Write the subtree's NodePtr into the entry's empty child, or into the root. + void SetChild(const NodeEntry &entry, const NodePtr node_ptr); + +private: //! The arena holds any temporary memory allocated during the Build phase. ArenaAllocator &arena; //! The ART holding the node memory. @@ -48,6 +57,8 @@ class ARTBuilder { const unsafe_vector &keys; //! The row IDs matching the keys. const unsafe_vector &row_ids; + //! The root of the ART. + optional_ptr root_ptr; //! The stack. While merging, NodeEntry elements are pushed onto of the stack. stack s; }; diff --git a/src/duckdb/src/include/duckdb/execution/index/art/node.hpp b/src/duckdb/src/include/duckdb/execution/index/art/node.hpp index c225d6fef..a2f50304d 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/node.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/node.hpp @@ -156,13 +156,15 @@ class NodePtr : public IndexPointer { //! Get the child node at byte, if it exists. OptionalNodePtr GetChildNode(const ART &art, const uint8_t byte) const; //! Get the child at byte, if it exists. The caller must retain handle while using the reference. - static unsafe_optional_ptr GetChildMutable(NodeHandle &handle, const uint8_t byte); + //! If unsafe, also returns empty children (for a Node256, any byte). + static unsafe_optional_ptr GetChildMutable(NodeHandle &handle, const uint8_t byte, + const bool unsafe = false); //! Get the first child node >= byte, if it exists, and update byte. OptionalNodePtr GetNextChildNode(const ART &art, uint8_t &byte) const; //! Get the immutable child at byte. const unsafe_optional_ptr GetChild(ART &art, const uint8_t byte) const; //! Get the child at byte. - unsafe_optional_ptr GetChildMutableUnsafe(ART &art, const uint8_t byte, const bool unsafe = false) const; + unsafe_optional_ptr GetChildMutableUnsafe(ART &art, const uint8_t byte) const; //! Get the first immutable child greater than or equal to the byte. const unsafe_optional_ptr GetNextChild(ART &art, uint8_t &byte) const; //! Returns true, if the byte exists, else false. diff --git a/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp b/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp index e6e0122b9..770e1129b 100644 --- a/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp @@ -50,11 +50,8 @@ class IndexAppendInfo { }; //! Identifies the logical purpose of a delta owned by an index entry. -enum class IndexDeltaType : uint8_t { - DELETED_ROWS_IN_USE, - ADDED_DATA_DURING_CHECKPOINT, - REMOVED_DATA_DURING_CHECKPOINT -}; +//! ADDED_DATA and REMOVED_DATA hold the changes made during a checkpoint or while CREATE INDEX builds the index. +enum class IndexDeltaType : uint8_t { DELETED_ROWS_IN_USE, ADDED_DATA, REMOVED_DATA }; //! The index is an abstract base class that serves as the basis for indexes class BoundIndex : public Index { @@ -167,7 +164,7 @@ class BoundIndex : public Index { //! Obtains a lock and calls Vacuum while holding that lock. void Vacuum() DUCKDB_EXCLUDES(lock); - //! Whether or not the index supports the creation of delta indexes + //! Whether or not the index supports delta indexes, used by checkpoints and online index builds virtual bool SupportsDeltaIndexes() const; //! Returns the in-memory usage of the index. The index lock must be held @@ -221,8 +218,8 @@ class BoundIndex : public Index { //! Creates an empty physical copy with the requested constraint type. virtual unique_ptr CreateEmptyCopy(IndexConstraintType constraint_type) const; - //! Merges a checkpoint delta into this index. - virtual ErrorData MergeCheckpointDelta(IndexDeltaType type, BoundIndex &delta_index); + //! Merges a delta into this index, using the append mode for added rows + virtual ErrorData MergeDelta(IndexDeltaType type, BoundIndex &delta_index, IndexAppendMode append_mode); //! Lock used for any changes to the index mutable annotated_mutex lock; 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 391ace8c1..6d15e26e7 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,8 +77,10 @@ class CSVEncoder { DataChunk decode_input; //! The maximum number of input bytes that make up one character idx_t minimum_input_window = 1; + //! The (mark, encoding) pairs that pick the decoder from the start of the file + vector> byte_order_marks; //! 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; + static constexpr idx_t MAX_DECODE_SLICE = idx_t(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; @@ -87,6 +89,10 @@ 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); + //! Binds the streaming overload of the encoding's scalar function as the decoder + shared_ptr BindDecoder(ClientContext &context, ScalarFunctionCatalogEntry &entry); + //! Binds the decoder of the encoding picked by the byte order mark at the start of the file + void DetectByteOrder(); //! 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); diff --git a/src/duckdb/src/include/duckdb/execution/operator/helper/physical_limit.hpp b/src/duckdb/src/include/duckdb/execution/operator/helper/physical_limit.hpp index ba626b0aa..88cd4cc8a 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/helper/physical_limit.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/helper/physical_limit.hpp @@ -69,6 +69,9 @@ class PhysicalLimit : public PhysicalOperator { public: static void SetInitialLimits(const BoundLimitNode &limit_val, const BoundLimitNode &offset_val, optional_idx &limit, optional_idx &offset); + //! Evaluates the LIMIT and OFFSET expressions that are not resolved yet + static void ResolveLimits(ExecutionContext &context, DataChunk &input, optional_idx &limit, optional_idx &offset, + const BoundLimitNode &limit_val, const BoundLimitNode &offset_val); static bool ComputeOffset(ExecutionContext &context, DataChunk &input, optional_idx &limit, optional_idx &offset, idx_t current_offset, idx_t &max_element, const BoundLimitNode &limit_val, const BoundLimitNode &offset_val); diff --git a/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp b/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp index 85c956722..2ee521fd7 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp @@ -39,21 +39,22 @@ enum class JoinFilterPushdownMode : uint8_t { struct JoinFilterPushdownColumn { JoinFilterPushdownColumn() = default; - JoinFilterPushdownColumn(const JoinFilterPushdownColumn &other) - : join_filter_idx(other.join_filter_idx), probe_column_index(other.probe_column_index), - storage_type(other.storage_type), mode(other.mode), - input_expression(other.input_expression ? other.input_expression->Copy() : nullptr) { - } - JoinFilterPushdownColumn &operator=(const JoinFilterPushdownColumn &other) { - if (this != &other) { - JoinFilterPushdownColumn copy(other); - *this = std::move(copy); - } - return *this; - } + JoinFilterPushdownColumn(const JoinFilterPushdownColumn &other) = delete; + JoinFilterPushdownColumn &operator=(const JoinFilterPushdownColumn &other) = delete; JoinFilterPushdownColumn(JoinFilterPushdownColumn &&other) = default; JoinFilterPushdownColumn &operator=(JoinFilterPushdownColumn &&other) = default; + //! Clone the owned expression only when changing a column or retaining it in a target. + JoinFilterPushdownColumn Copy() const { + JoinFilterPushdownColumn result; + result.join_filter_idx = join_filter_idx; + result.probe_column_index = probe_column_index; + result.storage_type = storage_type; + result.mode = mode; + result.input_expression = input_expression ? input_expression->Copy() : nullptr; + return result; + } + //! Index into JoinFilterPushdownInfo::join_condition for this pushed column idx_t join_filter_idx = DConstants::INVALID_INDEX; //! The probe column index to which this filter should be applied 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 47cb0394d..fd7664a31 100644 --- a/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp +++ b/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp @@ -209,13 +209,24 @@ class PhysicalPlanGenerator { bool extract_filters = true); private: + struct LogicalSubtreeProperties { + bool has_side_effects = false; + bool has_recursive_cte = false; + }; + class LogicalPlanProperties; + ClientContext &context; unique_ptr physical_plan; reference_set_t non_repeatable_operators; + //! Properties of the logical input before conversion consumes its expressions. + optional_ptr logical_properties; private: + LogicalSubtreeProperties GetLogicalProperties(const LogicalOperator &op) const; + //! Reuses properties for existing logical children. Use CreatePlan for new or replaced subtrees. + PhysicalOperator &CreatePlanRecursive(LogicalOperator &op); PhysicalOperator &CreatePlanInternal(LogicalOperator &op); - PhysicalOperator &ResolveAndPlan(unique_ptr logical); + PhysicalOperator &ResolveAndPlan(LogicalOperator &logical); unique_ptr PlanInternal(LogicalOperator &logical); bool PreserveInsertionOrder(PhysicalOperator &plan); bool UseBatchIndex(PhysicalOperator &plan); diff --git a/src/duckdb/src/include/duckdb/function/aggregate/bignum_aggregates.hpp b/src/duckdb/src/include/duckdb/function/aggregate/bignum_aggregates.hpp new file mode 100644 index 000000000..39378abb5 --- /dev/null +++ b/src/duckdb/src/include/duckdb/function/aggregate/bignum_aggregates.hpp @@ -0,0 +1,91 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/function/aggregate/bignum_aggregates.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/bignum.hpp" +#include "duckdb/common/exception.hpp" +#include "duckdb/common/operator/add.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/vector/vector_iterator.hpp" +#include "duckdb/common/vector/vector_writer.hpp" +#include "duckdb/function/aggregate_state.hpp" + +namespace duckdb { + +//! The state of an average over BIGNUM values: an exact sum and the count of the summed rows, 0 for an empty state +struct BignumAvgState { + uint64_t count; + BignumIntermediate value; +}; + +//! The BIGNUM accumulators of aggregate states: exported as (trimmed) BIGNUM blobs, imported as copies in the arena +struct BignumAggregates { + //! Writes the value as a BIGNUM blob through the writer of the result vector + DUCKDB_API static void WriteBignum(const BignumIntermediate &value, VectorWriter &writer); + //! Copies an imported BIGNUM blob into the arena and returns the intermediate over the copy + DUCKDB_API static BignumIntermediate ImportBignum(string_t blob, ArenaAllocator &allocator); + //! Writes an exported average state: the count, and the sum as a BIGNUM blob (NULL for an empty state) + DUCKDB_API static void WriteAvgState(const BignumAvgState &state, VectorWriter &count_writer, + VectorWriter &value_writer); + //! Fills an initialized average state from its exported count and sum; the sum may only be NULL when the count + //! is 0. value_field names the sum field of the exported state in error messages + DUCKDB_API static void ImportAvgState(BignumAvgState &state, const VectorIterator::ValueEntry &count, + const VectorIterator::ValueEntry &value, ArenaAllocator &allocator, + const char *function_name, const char *value_field); +}; + +//! Accumulates BIGNUM values into a BignumAvgState; the aggregates derive from it and add their own Finalize +struct BignumAvgOperation { + static bool IgnoreNull() { + return true; + } + + template + static void Initialize(STATE &state) { + state.count = 0; + state.value = BignumIntermediate(); + } + + template + static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) { + if (state.count == 0) { + state.value.Initialize(unary_input.input.allocator); + } + state.count++; + const BignumIntermediate rhs(input); + state.value.AddInPlace(unary_input.input.allocator, rhs); + } + + template + static void ConstantOperation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input, + idx_t count) { + for (idx_t i = 0; i < count; i++) { + Operation(state, input, unary_input); + } + } + + template + static void Combine(const STATE &source, STATE &target, AggregateInputData &input) { + if (source.count == 0) { + return; + } + // the counts of imported states can be anything, the count of rows of a table cannot overflow + uint64_t count; + if (!TryAddOperator::Operation(target.count, source.count, count)) { + throw OutOfRangeException("Overflow in aggregate state combine"); + } + if (target.count == 0) { + target.value.Initialize(input.allocator); + } + target.count = count; + target.value.AddInPlace(input.allocator, source.value); + } +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/aggregate/minmax_n_helpers.hpp b/src/duckdb/src/include/duckdb/function/aggregate/minmax_n_helpers.hpp index bc0ad1539..2e34883e5 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate/minmax_n_helpers.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate/minmax_n_helpers.hpp @@ -11,6 +11,7 @@ #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/common/vector/string_vector.hpp" +#include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/common/enums/order_type.hpp" #include "duckdb/function/aggregate_function.hpp" #include "duckdb/function/create_sort_key.hpp" @@ -110,6 +111,36 @@ struct HeapEntry { } }; +//! Grows a heap's slot array towards its capacity: doubling, then straight to the capacity once it exceeds +//! capacity / grow_to_capacity_divisor. A larger divisor abandons fewer arrays in heaps that fill up, but +//! over-allocates more in heaps that stay small. +template +ENTRY *GrowHeap(ArenaAllocator &allocator, ENTRY *heap, idx_t &allocated_capacity, const idx_t capacity, + const idx_t required, const idx_t grow_to_capacity_divisor) { + D_ASSERT(allocated_capacity < required && required <= capacity); + const auto old_allocated_capacity = allocated_capacity; + if (allocated_capacity == 0) { + allocated_capacity = 1; + } else if (allocated_capacity > capacity / grow_to_capacity_divisor) { + allocated_capacity = capacity; + } else { + if (!TryMultiplyOperator::Operation(allocated_capacity, static_cast(2), allocated_capacity)) { + throw OutOfRangeException("Overflow of 'allocated_capacity' in GrowHeap"); + } + } + allocated_capacity = MaxValue(allocated_capacity, required); + + const auto old_size = old_allocated_capacity * sizeof(ENTRY); + idx_t new_size; + if (!TryMultiplyOperator::Operation(allocated_capacity, static_cast(sizeof(ENTRY)), new_size)) { + throw OutOfRangeException("Overflow of 'new_size' in GrowHeap"); + } + auto ptr = heap ? allocator.ReallocateAligned(reinterpret_cast(heap), old_size, new_size) + : allocator.AllocateAligned(new_size); + memset(ptr + old_size, 0, new_size - old_size); + return reinterpret_cast(ptr); +} + template class UnaryAggregateHeap { public: @@ -121,9 +152,8 @@ class UnaryAggregateHeap { void Initialize(ArenaAllocator &allocator, const idx_t capacity_p) { capacity = capacity_p; - auto ptr = allocator.AllocateAligned(capacity * sizeof(HeapEntry)); - memset(ptr, 0, capacity * sizeof(HeapEntry)); - heap = reinterpret_cast *>(ptr); + allocated_capacity = 0; + heap = nullptr; size = 0; } @@ -142,6 +172,9 @@ class UnaryAggregateHeap { // If the heap is not full, insert the value into a new slot if (size < capacity) { + if (size == allocated_capacity) { + heap = GrowHeap(allocator, heap, allocated_capacity, capacity, size + 1, GROW_TO_CAPACITY_DIVISOR); + } heap[size++].Assign(allocator, value); std::push_heap(heap, heap + size, Compare); } @@ -161,6 +194,29 @@ class UnaryAggregateHeap { } } + //! Appends a slot without restoring the heap order + void AppendSlot(ArenaAllocator &allocator, const T &value) { + D_ASSERT(size < capacity); + if (size == allocated_capacity) { + heap = GrowHeap(allocator, heap, allocated_capacity, capacity, size + 1, GROW_TO_CAPACITY_DIVISOR); + } + heap[size++].Assign(allocator, value); + } + + //! Pre-allocates exactly n slots (the state import knows the final size up front) + void Reserve(ArenaAllocator &allocator, idx_t n) { + if (n > allocated_capacity) { + heap = GrowHeap(allocator, heap, allocated_capacity, capacity, n, GROW_TO_CAPACITY_DIVISOR); + } + } + + //! Restores the heap order after AppendSlot - a valid heap keeps its slot order + void RestoreHeap() { + if (!std::is_heap(heap, heap + size, Compare)) { + std::make_heap(heap, heap + size, Compare); + } + } + //! Slot indexes in the order the heap would sort to, leaving the heap intact for later reads and inserts. The //! indexes in heap order form the same heap, so sorting them as a heap yields the same order, ties included. void SortedSlots(vector &order) const { @@ -185,9 +241,13 @@ class UnaryAggregateHeap { return T_COMPARATOR::Operation(left.value, right.value); } - idx_t capacity; - HeapEntry *heap; - idx_t size; + //! Take all n slots once the heap holds more than n / 32: fewer abandoned arrays in heaps that fill up + static constexpr idx_t GROW_TO_CAPACITY_DIVISOR = 32; + + idx_t capacity = 0; + idx_t allocated_capacity = 0; + HeapEntry *heap = nullptr; + idx_t size = 0; }; struct List { @@ -230,7 +290,7 @@ class BinaryAggregateHeap { // If the heap is not full, insert the value into a new slot if (size < capacity) { if (size == allocated_capacity) { - Grow(allocator); + heap = GrowHeap(allocator, heap, allocated_capacity, capacity, size + 1, GROW_TO_CAPACITY_DIVISOR); } heap[size].first.Assign(allocator, key); heap[size].second.Assign(allocator, value); @@ -254,6 +314,31 @@ class BinaryAggregateHeap { } } + //! Appends a slot without restoring the heap order + void AppendSlot(ArenaAllocator &allocator, const K &key, const V &value) { + D_ASSERT(size < capacity); + if (size == allocated_capacity) { + heap = GrowHeap(allocator, heap, allocated_capacity, capacity, size + 1, GROW_TO_CAPACITY_DIVISOR); + } + heap[size].first.Assign(allocator, key); + heap[size].second.Assign(allocator, value); + size++; + } + + //! Pre-allocates exactly n slots (the state import knows the final size up front) + void Reserve(ArenaAllocator &allocator, idx_t n) { + if (n > allocated_capacity) { + heap = GrowHeap(allocator, heap, allocated_capacity, capacity, n, GROW_TO_CAPACITY_DIVISOR); + } + } + + //! Restores the heap order after AppendSlot - a valid heap keeps its slot order + void RestoreHeap() { + if (!std::is_heap(heap, heap + size, Compare)) { + std::make_heap(heap, heap + size, Compare); + } + } + //! Slot indexes in the order the heap would sort to, leaving the heap intact for later reads and inserts. The //! indexes in heap order form the same heap, so sorting them as a heap yields the same order, ties included. void SortedSlots(vector &order) const { @@ -274,34 +359,13 @@ class BinaryAggregateHeap { } private: - void Grow(ArenaAllocator &allocator) { - D_ASSERT(allocated_capacity < capacity); - const auto old_allocated_capacity = allocated_capacity; - if (allocated_capacity == 0) { - allocated_capacity = 1; - } else if (allocated_capacity > capacity / 2) { - allocated_capacity = capacity; - } else { - if (!TryMultiplyOperator::Operation(allocated_capacity, static_cast(2), allocated_capacity)) { - throw OutOfRangeException("Overflow of 'allocated_capacity' in BinaryAggregateHeap::Grow"); - } - } - - const auto old_size = old_allocated_capacity * sizeof(STORAGE_TYPE); - idx_t new_size; - if (!TryMultiplyOperator::Operation(allocated_capacity, static_cast(sizeof(STORAGE_TYPE)), new_size)) { - throw OutOfRangeException("Overflow of 'new_size' in BinaryAggregateHeap::Grow"); - } - auto ptr = heap ? allocator.ReallocateAligned(reinterpret_cast(heap), old_size, new_size) - : allocator.AllocateAligned(new_size); - memset(ptr + old_size, 0, new_size - old_size); - heap = reinterpret_cast(ptr); - } - static bool Compare(const STORAGE_TYPE &left, const STORAGE_TYPE &right) { return K_COMPARATOR::Operation(left.first.value, right.first.value); } + //! Take all n slots past n / 2; an earlier jump makes sparse arg_max heaps several times larger + static constexpr idx_t GROW_TO_CAPACITY_DIVISOR = 2; + idx_t capacity = 0; idx_t allocated_capacity = 0; STORAGE_TYPE *heap = nullptr; @@ -349,7 +413,7 @@ struct MinMaxFixedValue { } // Nothing to do here - static EXTRA_STATE CreateExtraState() { + static EXTRA_STATE CreateExtraState(idx_t count) { return false; } @@ -371,7 +435,7 @@ struct MinMaxStringValue { } // Nothing to do here - static EXTRA_STATE CreateExtraState() { + static EXTRA_STATE CreateExtraState(idx_t count) { return false; } @@ -395,8 +459,8 @@ struct MinMaxFallbackValue { CreateSortKeyHelpers::DecodeSortKey(value, vector, idx, modifiers); } - static EXTRA_STATE CreateExtraState() { - return Vector(LogicalTypeId::BLOB); + static EXTRA_STATE CreateExtraState(idx_t count) { + return Vector(LogicalType::BLOB, MaxValue(count, 1)); } static void PrepareData(const Vector &input, EXTRA_STATE &extra_state, UnifiedVectorFormat &format, @@ -404,7 +468,6 @@ struct MinMaxFallbackValue { auto order_by_null_type = nulls_last ? OrderByNullType::NULLS_LAST : OrderByNullType::NULLS_FIRST; const OrderModifiers modifiers(OrderType::ASCENDING, order_by_null_type); CreateSortKeyHelpers::CreateSortKeyWithValidity(input, extra_state, modifiers); - input.Flatten(); extra_state.ToUnifiedFormat(format); } }; @@ -444,7 +507,7 @@ struct MinMaxFixedValueOrNull { FlatVector::GetDataMutable(vector)[idx] = value.value; } - static EXTRA_STATE CreateExtraState() { + static EXTRA_STATE CreateExtraState(idx_t count) { return false; } @@ -533,13 +596,117 @@ struct MinMaxNOperation { result.Verify(); } + static bool IgnoreNull() { + return true; + } + + //! Exported state: STRUCT(n, entries LIST(entry)) - the heap slots in heap order, NULL if no value was added + static AggregateStateLayout GetStateType(AggregateLayoutInput &input, const LogicalType &entry_type) { + child_list_t children; + children.emplace_back("n", LogicalType::BIGINT); + children.emplace_back("entries", LogicalType::LIST(entry_type)); + AggregateStateLayout layout; + layout.type = LogicalType::STRUCT(std::move(children)); + layout.total_state_size = AlignValue(input.function.GetStateSize(input.bind_data.get())); + layout.spill_opaque_arena_memory = true; + return layout; + } + + //! States with different n values cannot be combined, so a per-row n cannot export its states. It also cannot + //! stream: the streaming window (unlike WINDOW) would never check the n of later rows. + static void BindPerRowN(BoundAggregateFunction &function) { + function.GetCallbacks().get_state_type = nullptr; + function.SetCanStream(false); + } + template - static void Destroy(STATE &state, AggregateInputData &aggr_input_data) { - state.~STATE(); + static void ExportState(Vector &state_vector, AggregateFinalizeInputData &input_data, Vector &result, idx_t count, + idx_t offset) { + const bool nulls_last = + input_data.bind_data ? input_data.bind_data->Cast().nulls_last : true; + auto states = state_vector.Values(); + auto &fields = StructVector::GetEntries(result); + auto &entry_lists = fields[1]; + + idx_t entry_count = ListVector::GetListSize(entry_lists); + for (idx_t i = 0; i < count; i++) { + auto &state = *states[i].GetValue(); + entry_count += state.is_initialized ? state.heap.Size() : 0; + } + ListVector::Reserve(entry_lists, entry_count); + auto &entries = ListVector::GetChildMutable(entry_lists); + + auto n_writer = FlatVector::Writer(fields[0], count, offset); + auto list_writer = FlatVector::Writer(entry_lists, count, offset); + idx_t entry_idx = ListVector::GetListSize(entry_lists); + for (idx_t i = 0; i < count; i++) { + auto &state = *states[i].GetValue(); + if (!state.is_initialized || state.heap.IsEmpty()) { + // children of a NULL struct must also be NULL + n_writer.WriteNull(); + list_writer.WriteNull(); + FlatVector::SetNull(result, offset + i, true); + continue; + } + n_writer.WriteValue(UnsafeNumericCast(state.heap.Capacity())); + list_writer.WriteValue(list_entry_t(entry_idx, state.heap.Size())); + for (idx_t slot = 0; slot < state.heap.Size(); slot++) { + state.ExportSlot(entries, entry_idx++, slot, nulls_last); + } + } + ListVector::SetListSize(entry_lists, entry_idx); + FlatVector::SetSize(result, offset + count); } - static bool IgnoreNull() { - return true; + template + static void ImportState(AggregateImportInputData &input) { + bool nulls_last = true; + bool reject_nulls = true; + if (input.bind_data) { + auto &bind_data = input.bind_data->Cast(); + nulls_last = bind_data.nulls_last; + reject_nulls = bind_data.null_handling == ArgMinMaxNullHandling::IGNORE_ANY_NULL; + } + const auto count = input.input_vec.size(); + // flatten the input, so the struct and list children can be read by position + Vector input_vec(input.input_vec, 0, count); + input_vec.Flatten(); + auto &fields = StructVector::GetEntries(input_vec); + auto n_values = fields[0].Values(); + auto entry_lists = fields[1].Values(); + const auto child_count = ListVector::GetListSize(fields[1]); + typename STATE::ImportData entries(ListVector::GetChild(fields[1]), child_count, nulls_last); + + auto input_validity = input_vec.Validity(); + for (idx_t i = 0; i < count; i++) { + auto &state = *reinterpret_cast(input.dest_buffer + i * input.layout.total_state_size); + if (!input_validity.IsValid(i)) { + continue; + } + const auto n = n_values[i]; + const auto entry_list = entry_lists[i]; + if (!n.IsValid() || !entry_list.IsValid()) { + throw InvalidInputException("Invalid min/max/arg_min/arg_max state - n and entries cannot be NULL"); + } + if (n.GetValue() <= 0 || n.GetValue() >= MIN_MAX_N_MAX_VALUE) { + throw InvalidInputException("Invalid min/max/arg_min/arg_max state - n must be > 0 and < %d", + MIN_MAX_N_MAX_VALUE); + } + const auto &list = entry_list.GetValue(); + if (list.length > UnsafeNumericCast(n.GetValue())) { + throw InvalidInputException("Invalid min/max/arg_min/arg_max state - more entries than n"); + } + if (list.length == 0) { + // an empty heap exports as NULL, so it imports as an empty state too + continue; + } + state.Initialize(input.allocator, UnsafeNumericCast(n.GetValue())); + state.heap.Reserve(input.allocator, list.length); + for (idx_t entry_idx = list.offset; entry_idx < list.offset + list.length; entry_idx++) { + state.ImportSlot(input.allocator, entries, entry_idx, reject_nulls); + } + state.heap.RestoreHeap(); + } } }; diff --git a/src/duckdb/src/include/duckdb/function/aggregate_function.hpp b/src/duckdb/src/include/duckdb/function/aggregate_function.hpp index ec5c2a7d9..f2974d43c 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate_function.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate_function.hpp @@ -170,14 +170,15 @@ enum class AggregateRewritePolicy : uint8_t { //! dest_buffer (state i at offset i * layout.total_state_size). struct AggregateImportInputData { AggregateImportInputData(const AggregateStateLayout &layout, const Vector &input_vec, data_ptr_t dest_buffer, - ArenaAllocator &allocator) - : layout(layout), input_vec(input_vec), dest_buffer(dest_buffer), allocator(allocator) { + ArenaAllocator &allocator, optional_ptr bind_data) + : layout(layout), input_vec(input_vec), dest_buffer(dest_buffer), allocator(allocator), bind_data(bind_data) { } const AggregateStateLayout &layout; const Vector &input_vec; data_ptr_t dest_buffer; ArenaAllocator &allocator; + optional_ptr bind_data; }; //! The counterpart of export_aggregate_state, for states a static field layout cannot describe (e.g. a hash map). @@ -365,6 +366,9 @@ class AggregateFunctionProperties : public FunctionProperties { //! Whether combining can leave the target referencing the source's memory AggregateCombineSourceRetention combine_source_retention = AggregateCombineSourceRetention::MAY_RETAIN; + //! Whether the streaming window may compute the aggregate, updating one running state with every row + bool can_stream = true; + bool operator==(const AggregateFunctionProperties &rhs) const; bool operator!=(const AggregateFunctionProperties &rhs) const; }; @@ -419,6 +423,10 @@ class BaseAggregateFunction { auto GetCombineSourceRetention() const -> AggregateCombineSourceRetention { return properties.combine_source_retention; } auto SetCombineSourceRetention(AggregateCombineSourceRetention value) -> void { properties.combine_source_retention = value; } + //! Whether the streaming window may compute the aggregate, updating one running state with every row + auto CanStream() const -> bool { return properties.can_stream; } + auto SetCanStream(bool value) -> void { properties.can_stream = value; } + // Derived properties bool CanAggregate() const { return callbacks.update || callbacks.combine || callbacks.finalize; } bool CanWindow() const { return callbacks.window || callbacks.window_batch; } diff --git a/src/duckdb/src/include/duckdb/function/aggregate_state_layout.hpp b/src/duckdb/src/include/duckdb/function/aggregate_state_layout.hpp index cd29acb51..0931f21c3 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate_state_layout.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate_state_layout.hpp @@ -532,6 +532,9 @@ struct AggregateStateLayout { unordered_map constant_parameters; //! Checks the imported states for invariants the fields cannot express (e.g. between fields) aggregate_validate_state_t validate_state = nullptr; + //! Opts a layout whose fields do not show its arena memory (e.g. a heap behind export/import callbacks) into + //! state spilling. Spilling exports the states of all aggregates of the hash table, not only this one + bool spill_opaque_arena_memory = false; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/aggregate_state_serialization.hpp b/src/duckdb/src/include/duckdb/function/aggregate_state_serialization.hpp index 4da530175..fed3833f2 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate_state_serialization.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate_state_serialization.hpp @@ -26,6 +26,19 @@ enum class StateMemoryOwnership : uint8_t { OWNED }; +//! The layout of an aggregate's exported states, with the function and bind data that (de)serialize them. The +//! function and bind data are borrowed, and must outlive the serializer. +struct AggregateStateSerializer { + AggregateStateSerializer(AggregateStateLayout layout_p, const BoundAggregateFunction &function_p, + optional_ptr bind_data_p) + : layout(std::move(layout_p)), function(function_p), bind_data(bind_data_p) { + } + + AggregateStateLayout layout; + const BoundAggregateFunction &function; + optional_ptr bind_data; +}; + //! Converts aggregate states to and from their exported logical form, through the aggregate //! state export layouts. Used by the aggregate state export functions and by state spilling. struct AggregateStateSerialization { @@ -39,9 +52,9 @@ struct AggregateStateSerialization { //! Deserialize `count` rows of `input` into consecutive packed states in `dest_buffer`. //! With OWNED ownership, all variable size state data is allocated from `allocator`; //! with BORROWED ownership, primitive string values may point into `input`. - static void DeserializeStates(const BoundAggregateFunction &aggr, const AggregateStateLayout &layout, - const Vector &input, idx_t count, data_ptr_t dest_buffer, ArenaAllocator &allocator, - StateMemoryOwnership ownership); + static void DeserializeStates(const BoundAggregateFunction &aggr, optional_ptr bind_data, + const AggregateStateLayout &layout, const Vector &input, idx_t count, + data_ptr_t dest_buffer, ArenaAllocator &allocator, StateMemoryOwnership ownership); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/encoding_function.hpp b/src/duckdb/src/include/duckdb/function/encoding_function.hpp index 97b0f6626..2422c144e 100644 --- a/src/duckdb/src/include/duckdb/function/encoding_function.hpp +++ b/src/duckdb/src/include/duckdb/function/encoding_function.hpp @@ -40,6 +40,9 @@ struct EncodingFunction { static constexpr const char *SCHEMA = "encodings"; //! Integer function property: the maximum number of input bytes that make up one character static constexpr const char *MINIMUM_INPUT_WINDOW_PROPERTY = "duckdb.encodings.minimum_input_window"; + //! LIST(STRUCT(mark BLOB, encoding VARCHAR)) function property: a stream that starts with a mark is decoded with + //! that encoding. The first matching mark wins, an empty mark matches any stream. + static constexpr const char *BYTE_ORDER_MARKS_PROPERTY = "duckdb.encodings.byte_order_marks"; //! The name of the scalar function that decodes the encoding DUCKDB_API static string FunctionName(const string &encoding_name); diff --git a/src/duckdb/src/include/duckdb/function/scalar/generic_common.hpp b/src/duckdb/src/include/duckdb/function/scalar/generic_common.hpp index cc5738bf5..e0244867b 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/generic_common.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/generic_common.hpp @@ -18,6 +18,7 @@ namespace duckdb { class BoundAggregateFunction; class BoundFunctionExpression; struct AggregateStateLayout; +struct AggregateStateSerializer; struct SortedAggregateStateOrder; struct ConstantOrNull { @@ -37,10 +38,10 @@ struct ExportAggregateFunction { static unique_ptr StateToSQL(const LogicalType &type, unique_ptr value); //! The per-key (column, modifiers) of the AGGREGATE_STATE type of an ordered aggregate static void GetSortedStateOrders(const LogicalType &state_type, vector &orders); - //! The state layout of the aggregate whose states a bound combine_aggr accumulates. Returns false for any other - //! function, and for an aggregate whose state the field layout alone does not describe - static bool TryGetCombinedStateLayout(const BoundAggregateFunction &function, - optional_ptr bind_data, AggregateStateLayout &layout); + //! The serializer of the aggregate whose states a bound combine_aggr accumulates. Returns nullptr for any other + //! function + static unique_ptr + TryGetCombinedStateSerializer(const BoundAggregateFunction &function, optional_ptr bind_data); }; } // namespace duckdb 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 e3ceb85ef..5e46fa9cf 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/system_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/system_functions.hpp @@ -75,6 +75,16 @@ struct CurrentTransactionId { static ScalarFunction GetFunction(); }; +struct ShareTransaction { + static constexpr const char *Name = "share_transaction"; + static constexpr const char *Parameters = ""; + static constexpr const char *Description = "Share the current transaction so that other connections can join it using JOIN TRANSACTION"; + static constexpr const char *Example = "share_transaction()"; + static constexpr const char *Categories = ""; + + static ScalarFunction GetFunction(); +}; + struct CurrentQueryId { static constexpr const char *Name = "current_query_id"; static constexpr const char *Parameters = ""; diff --git a/src/duckdb/src/include/duckdb/function/table/table_scan.hpp b/src/duckdb/src/include/duckdb/function/table/table_scan.hpp index 377d34827..2675b76c2 100644 --- a/src/duckdb/src/include/duckdb/function/table/table_scan.hpp +++ b/src/duckdb/src/include/duckdb/function/table/table_scan.hpp @@ -16,6 +16,7 @@ #include "duckdb/storage/table/row_group_order_options.hpp" namespace duckdb { +class BoundIndex; class DuckTableEntry; class TableCatalogEntry; @@ -31,6 +32,9 @@ struct TableScanBindData : public TableFunctionData { bool is_index_scan; //! Whether or not the table scan is for index creation. bool is_create_index; + //! An empty copy of the index to build in place (only for indexes with delta support). + //! Set during physical planning, after the logical plan is (de)serialized: not serialized or compared. + shared_ptr index_template; //! In what order to scan the row groups unique_ptr order_options; //! Subset of partition indices to scan, if null, scan all @@ -45,6 +49,7 @@ struct TableScanBindData : public TableFunctionData { auto bind_data = make_uniq(table); bind_data->is_index_scan = is_index_scan; bind_data->is_create_index = is_create_index; + bind_data->index_template = index_template; bind_data->column_ids = column_ids; bind_data->order_options = order_options ? make_uniq(*order_options) : nullptr; bind_data->partitions_to_scan = 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 cd441c1ef..3b0b1e6ca 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 @@ -127,7 +127,8 @@ struct ValueConverter { static Value VisitObject(const UnifiedVariantVectorData &variant, idx_t row, const VariantNestedData &nested_data, idx_t depth) { - auto object_children = VariantVisitor::VisitObjectItems(variant, row, nested_data, depth); + auto object_children = VariantVisitor::VisitObjectItems(variant, row, nested_data, depth, + VariantIterationOrder::LEXICOGRAPHIC); if (object_children.size() == 1 && object_children[0].first.empty()) { // an empty key can't be a STRUCT member name (it would become a TUPLE) - use a MAP instead auto &child = object_children[0].second; diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_data_source_internal.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_data_source_internal.hpp new file mode 100644 index 000000000..811ae0c99 --- /dev/null +++ b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_data_source_internal.hpp @@ -0,0 +1,142 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/main/capi_v2/capi_v2_data_source_internal.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/main/capi_v2/capi_v2_internal.hpp" +#include "duckdb/function/table_function.hpp" +#include "duckdb/planner/expression.hpp" + +namespace duckdb::capiv2 { + +//! The definition of a data source: the physical operator source of a scan. It holds the callbacks that set up the +//! scan, hand out its work to the scanning threads and produce its batches of rows. Everything that is decided at plan +//! time (binding, filter and projection pushdown, statistics, partitioning of the plan) belongs to the table function +//! that scans with it. +class CV2DataSourceInfo { +public: + duckdb_v2_data_source_init_global_callback_fn init_global_cb = nullptr; + duckdb_v2_data_source_init_local_callback_fn init_local_cb = nullptr; + duckdb_v2_data_source_exec_callback_fn exec_cb = nullptr; + duckdb_v2_data_source_progress_callback_fn progress_cb = nullptr; + duckdb_v2_data_source_partition_data_callback_fn partition_data_cb = nullptr; + duckdb_v2_data_source_claim_batch_callback_fn claim_batch_cb = nullptr; + duckdb_v2_data_source_metrics_callback_fn metrics_cb = nullptr; + //! What the callbacks of the data source receive as their user data + shared_ptr user_data; + //! The name of the function the data source scans for, which error messages refer to + Identifier name; + + //! Throws unless the configuration is complete and consistent + void Verify() const; + //! Takes `fallback` as its user data unless it has some: user data with a null pointer counts as none + void InheritUserData(const shared_ptr &fallback) { + if (!user_data || !user_data->GetData()) { + user_data = fallback; + } + } + + //! Makes the function scan with this data source. The data source must outlive every call of the function, as the + //! bind data of a call refers to it. + void ConfigureScan(TableFunction &function) const; +}; + +//! What the table function decided at plan time that changes how its scan runs +class CV2ScanOptions { +public: + //! Whether the scan only produces the columns the query reads + bool projection_pushdown = false; + //! The callback that is offered the filters of the query, and the user data it receives + duckdb_v2_table_function_filter_pushdown_callback_fn filter_pushdown_cb = nullptr; + shared_ptr user_data; + + //! Whether the scan sees the filters of the query: there is a filter pushdown callback and projection pushdown + bool ReadsFilters() const { + return filter_pushdown_cb && projection_pushdown; + } +}; + +//! The bind data of a call whose scan is a data source. Besides the user's own bind data it carries borrowed pointers +//! to the data source and the scan options, which the scan hooks that only receive the bind data (e.g. progress) reach +//! their callbacks through. +class CV2DataSourceBindData : public FunctionData { +public: + shared_ptr handle; + optional_ptr source; + optional_ptr scan; + //! The declared columns the data source produces + vector column_types; + + auto Equals(const FunctionData &other) const -> bool override { + const auto &other_data = other.Cast(); + return handle && other_data.handle && handle->Equals(*other_data.handle); + } + +protected: + void CopyTo(CV2DataSourceBindData &other) const { + other.handle = handle; + other.source = source; + other.scan = scan; + other.column_types = column_types; + } +}; + +//! A data source being built, created through a factory +class CV2DataSource { +public: + explicit CV2DataSource(DatabaseInstance &db) : db(db) { + } + +public: + //! The database it was created for: the only one it can be used on. + DatabaseInstance &db; + CV2DataSourceInfo info; +}; + +inline auto Convert(duckdb_v2_data_source_handle source) -> CV2DataSource * { + return reinterpret_cast(source); +} +inline auto Convert(CV2DataSource *source) -> duckdb_v2_data_source_handle { + return reinterpret_cast(source); +} + +//! What a filter pushdown callback is offered: at plan time by the optimizer, and when a scan starts +class CV2TableFilterPushdownInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + // The predicates the optimizer offers, borrowed from the engine for the duration of the callback. + const vector> *in_filters = nullptr; + // What the column references inside the predicates index: the scan's columns, as the function sees them. + vector in_column_ids; + + vector out_handled; +}; + +inline auto Convert(duckdb_v2_table_function_filter_pushdown_info_handle info) -> CV2TableFilterPushdownInfo * { + return reinterpret_cast(info); +} +inline auto Convert(CV2TableFilterPushdownInfo *info) -> duckdb_v2_table_function_filter_pushdown_info_handle { + return reinterpret_cast(info); +} + +//! The index the function sees for a column of the scan. A virtual column of a function wrapped in a multi-file +//! function has an index of its own past the declared columns, and the wrapper tells which virtual column that is. +auto CV2ScanColumnIndex(column_t column, optional_ptr> virtual_columns) + -> column_t; + +//! The scan hooks of a table function that scans with a data source +auto CV2DataSourceInitGlobal(ClientContext &context, TableFunctionInitInput &input) + -> unique_ptr; +auto CV2DataSourceInitLocal(ExecutionContext &context, TableFunctionInitInput &input, + GlobalTableFunctionState *global_state) -> unique_ptr; +auto CV2DataSourceExec(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void; +//! Claims the next batch for the scanning thread, for a multi-file scan that claims the batches itself +auto CV2DataSourceClaimBatch(ClientContext &context, TableFunctionInput &input) -> bool; + +} // namespace duckdb::capiv2 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 3a5dd217e..41833770e 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 @@ -482,6 +482,8 @@ class CV2Connection : public Connection { public: explicit CV2Connection(DuckDB &database) : Connection(database), context_handle(*context) { } + explicit CV2Connection(Connection &&connection) : Connection(std::move(connection)), context_handle(*context) { + } CV2ConnectionContext context_handle; }; 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 80741a7d5..3e0a94a66 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 @@ -576,6 +576,40 @@ typedef struct { DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_register_table_function) (duckdb_v2_connection_handle conn, duckdb_v2_table_function_handle function, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_bind_data) + (duckdb_v2_data_source_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_global_state) + (duckdb_v2_data_source_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_local_state) + (duckdb_v2_data_source_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_output_chunk) + (duckdb_v2_data_source_exec_info_handle info, duckdb_v2_data_chunk_handle *chunk, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_user_data) + (duckdb_v2_data_source_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_get_bind_data) + (duckdb_v2_data_source_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_get_user_data) + (duckdb_v2_data_source_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_set_global_state) + (duckdb_v2_data_source_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_set_max_threads) + (duckdb_v2_data_source_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_get_bind_data) + (duckdb_v2_data_source_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_get_global_state) + (duckdb_v2_data_source_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_get_user_data) + (duckdb_v2_data_source_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_set_local_state) + (duckdb_v2_data_source_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_progress_get_bind_data) + (duckdb_v2_data_source_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_progress_get_global_state) + (duckdb_v2_data_source_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_progress_get_user_data) + (duckdb_v2_data_source_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_progress_set_progress) + (duckdb_v2_data_source_progress_info_handle info, double progress, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_table_function) (duckdb_v2_extension_handle extension, duckdb_v2_table_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_add_result_column) @@ -587,61 +621,14 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_table_function_create) (duckdb_v2_factory_handle factory, duckdb_v2_table_function_handle *function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_table_function_destroy)(duckdb_v2_table_function_handle *function); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_bind_data) - (duckdb_v2_table_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_global_state) - (duckdb_v2_table_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_local_state) - (duckdb_v2_table_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_output_chunk) - (duckdb_v2_table_function_exec_info_handle info, duckdb_v2_data_chunk_handle *chunk, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_user_data) - (duckdb_v2_table_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_get_signature) (duckdb_v2_table_function_handle function, duckdb_v2_function_signature_handle *sig, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_get_bind_data) - (duckdb_v2_table_function_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_get_user_data) - (duckdb_v2_table_function_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_set_global_state) - (duckdb_v2_table_function_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_set_max_threads) - (duckdb_v2_table_function_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_get_bind_data) - (duckdb_v2_table_function_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_get_global_state) - (duckdb_v2_table_function_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_get_user_data) - (duckdb_v2_table_function_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_set_local_state) - (duckdb_v2_table_function_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_progress_get_bind_data) - (duckdb_v2_table_function_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_progress_get_global_state) - (duckdb_v2_table_function_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_progress_get_user_data) - (duckdb_v2_table_function_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_progress_set_progress) - (duckdb_v2_table_function_progress_info_handle info, double progress, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_bind_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_bind_callback_fn callback, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_exec_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_init_global_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_init_global_callback_fn callback, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_init_local_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_init_local_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_name) (duckdb_v2_table_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_progress_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_progress_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_user_data) (duckdb_v2_table_function_handle function, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_cast_function_create) @@ -834,55 +821,9 @@ typedef struct { (duckdb_v2_copy_from_bind_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_set_cardinality) (duckdb_v2_copy_from_bind_info_handle info, idx_t cardinality, bool is_exact, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_exec_get_bind_data) - (duckdb_v2_copy_from_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_exec_get_global_state) - (duckdb_v2_copy_from_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_exec_get_local_state) - (duckdb_v2_copy_from_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_exec_get_output_chunk) - (duckdb_v2_copy_from_exec_info_handle info, duckdb_v2_data_chunk_handle *chunk, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_exec_get_user_data) - (duckdb_v2_copy_from_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_global_get_bind_data) - (duckdb_v2_copy_from_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_global_get_user_data) - (duckdb_v2_copy_from_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_global_set_global_state) - (duckdb_v2_copy_from_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_global_set_max_threads) - (duckdb_v2_copy_from_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_local_get_bind_data) - (duckdb_v2_copy_from_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_local_get_global_state) - (duckdb_v2_copy_from_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_local_get_user_data) - (duckdb_v2_copy_from_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_local_set_local_state) - (duckdb_v2_copy_from_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_progress_get_bind_data) - (duckdb_v2_copy_from_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_progress_get_global_state) - (duckdb_v2_copy_from_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_progress_get_user_data) - (duckdb_v2_copy_from_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_progress_set_progress) - (duckdb_v2_copy_from_progress_info_handle info, double progress, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_bind_callback) (duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_bind_callback_fn callback, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_exec_callback) - (duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_init_global_callback) - (duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_init_global_callback_fn callback, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_init_local_callback) - (duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_init_local_callback_fn callback, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_progress_callback) - (duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_progress_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_function_create) (duckdb_v2_factory_handle factory, duckdb_v2_copy_function_handle *function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_copy_function_destroy)(duckdb_v2_copy_function_handle *function); @@ -969,6 +910,20 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_copy_to_set_init_callback) (duckdb_v2_copy_function_handle function, duckdb_v2_copy_to_init_callback_fn callback, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_column_count) + (duckdb_v2_data_source_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_column_index) + (duckdb_v2_data_source_exec_info_handle info, idx_t index, idx_t *column_index, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_get_column_count) + (duckdb_v2_data_source_init_global_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_get_column_index) + (duckdb_v2_data_source_init_global_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_get_column_count) + (duckdb_v2_data_source_init_local_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_get_column_index) + (duckdb_v2_data_source_init_local_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_cast_get_mode) (duckdb_v2_expression_handle expression, DUCKDB_V2_CAST_MODE *mode, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_column_ref_get_index) @@ -1013,11 +968,6 @@ typedef struct { (duckdb_v2_table_description_handle desc, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_description_is_readonly) (duckdb_v2_table_description_handle desc, bool *readonly, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_column_count) - (duckdb_v2_table_function_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_column_index) - (duckdb_v2_table_function_exec_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_filter_pushdown_accept) (duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_filter_pushdown_get_bind_data) @@ -1034,16 +984,6 @@ typedef struct { (duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_filter_pushdown_get_user_data) (duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_get_column_count) - (duckdb_v2_table_function_init_global_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_get_column_index) - (duckdb_v2_table_function_init_global_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_get_column_count) - (duckdb_v2_table_function_init_local_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_get_column_index) - (duckdb_v2_table_function_init_local_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_filter_pushdown_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_filter_pushdown_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -1075,30 +1015,30 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_attach_options_set) (duckdb_v2_attach_options_handle options, const char *key, idx_t key_length, const char *setting, idx_t setting_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_bind_data) + (duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_global_state) + (duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_local_state) + (duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_partition_column_count) + (duckdb_v2_data_source_partition_data_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_partition_column_index) + (duckdb_v2_data_source_partition_data_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_user_data) + (duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_requires_batch_index) + (duckdb_v2_data_source_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_requires_partition_columns) + (duckdb_v2_data_source_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_set_batch_index) + (duckdb_v2_data_source_partition_data_info_handle info, idx_t batch_index, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_set_partition_value) + (duckdb_v2_data_source_partition_data_info_handle info, idx_t index, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_set_default) (duckdb_v2_instance_handle instance, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_bind_data) - (duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_global_state) - (duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_local_state) - (duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_partition_column_count) - (duckdb_v2_table_function_partition_data_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_partition_column_index) - (duckdb_v2_table_function_partition_data_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_user_data) - (duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_requires_batch_index) - (duckdb_v2_table_function_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_requires_partition_columns) - (duckdb_v2_table_function_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_set_batch_index) - (duckdb_v2_table_function_partition_data_info_handle info, idx_t batch_index, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_set_partition_value) - (duckdb_v2_table_function_partition_data_info_handle info, idx_t index, duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_partitioning_get_bind_data) (duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_partitioning_get_partition_column_count) @@ -1111,9 +1051,6 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_table_function_partitioning_set_partition_info) (duckdb_v2_table_function_partitioning_info_handle info, DUCKDB_V2_TABLE_PARTITION_INFO partition_info, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_partition_data_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_partition_data_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_partitioning_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_partitioning_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -1135,6 +1072,16 @@ typedef struct { (duckdb_v2_copy_to_statistics_info_handle info, idx_t row_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_data_chunk_get_capacity) (duckdb_v2_data_chunk_handle chunk, idx_t *out_capacity, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_claim_batch_get_bind_data) + (duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_claim_batch_get_global_state) + (duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_claim_batch_get_local_state) + (duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_claim_batch_get_user_data) + (duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_claim_batch_set_claimed) + (duckdb_v2_data_source_claim_batch_info_handle info, bool claimed, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_multi_file_function) (duckdb_v2_extension_handle extension, duckdb_v2_multi_file_function_handle function, duckdb_v2_error_info_handle *err); @@ -1154,19 +1101,6 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_multi_file_function_set_single_file_function) (duckdb_v2_multi_file_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_bind_data) - (duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_global_state) - (duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_local_state) - (duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_user_data) - (duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_set_claimed) - (duckdb_v2_table_function_claim_batch_info_handle info, bool claimed, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_claim_batch_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_claim_batch_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_bind_get_arg_count) (duckdb_v2_function_bind_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); @@ -1496,20 +1430,17 @@ typedef struct { (duckdb_v2_sql_statement_handle statement, const char *name, idx_t name_length, duckdb_v2_column_data_collection_handle collection, const char *const *column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_metrics_get_bind_data) + (duckdb_v2_data_source_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_metrics_get_global_state) + (duckdb_v2_data_source_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_metrics_get_user_data) + (duckdb_v2_data_source_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_metrics_set) + (duckdb_v2_data_source_metrics_info_handle info, const char *name, idx_t name_length, uint64_t value, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_add_virtual_column) (duckdb_v2_table_function_handle function, DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_bind_data) - (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_global_state) - (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_user_data) - (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_set) - (duckdb_v2_table_function_metrics_info_handle info, const char *name, idx_t name_length, uint64_t value, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_metrics_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_metrics_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_check_statistics) (duckdb_v2_context_handle context, duckdb_v2_expression_handle expression, duckdb_v2_stats_handle stats, DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, duckdb_v2_error_info_handle *err); @@ -1713,8 +1644,42 @@ 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_data_source_create) + (duckdb_v2_factory_handle factory, duckdb_v2_data_source_handle *source, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_data_source_destroy)(duckdb_v2_data_source_handle *source); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_claim_batch_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_claim_batch_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_exec_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_exec_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_init_global_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_init_global_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_init_local_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_init_local_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_metrics_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_metrics_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_partition_data_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_partition_data_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_progress_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_progress_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_user_data) + (duckdb_v2_data_source_handle source, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_data_source) + (duckdb_v2_table_function_handle function, duckdb_v2_data_source_handle data_source, + 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_V2_ERROR(*duckdb_v2_copy_from_set_data_source) + (duckdb_v2_copy_function_handle function, duckdb_v2_data_source_handle data_source, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_create_in_transaction) + (duckdb_v2_context_handle ctx, duckdb_v2_connection_handle *out_conn, duckdb_v2_error_info_handle *err); } duckdb_ext_api_v2; //===--------------------------------------------------------------------===// @@ -1969,36 +1934,31 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_aggregate_function_set_property = duckdb_v2_aggregate_function_set_property; result.duckdb_v2_scalar_function_set_property = duckdb_v2_scalar_function_set_property; result.duckdb_v2_connection_register_table_function = duckdb_v2_connection_register_table_function; + result.duckdb_v2_data_source_exec_get_bind_data = duckdb_v2_data_source_exec_get_bind_data; + result.duckdb_v2_data_source_exec_get_global_state = duckdb_v2_data_source_exec_get_global_state; + result.duckdb_v2_data_source_exec_get_local_state = duckdb_v2_data_source_exec_get_local_state; + result.duckdb_v2_data_source_exec_get_output_chunk = duckdb_v2_data_source_exec_get_output_chunk; + result.duckdb_v2_data_source_exec_get_user_data = duckdb_v2_data_source_exec_get_user_data; + result.duckdb_v2_data_source_init_global_get_bind_data = duckdb_v2_data_source_init_global_get_bind_data; + result.duckdb_v2_data_source_init_global_get_user_data = duckdb_v2_data_source_init_global_get_user_data; + result.duckdb_v2_data_source_init_global_set_global_state = duckdb_v2_data_source_init_global_set_global_state; + result.duckdb_v2_data_source_init_global_set_max_threads = duckdb_v2_data_source_init_global_set_max_threads; + result.duckdb_v2_data_source_init_local_get_bind_data = duckdb_v2_data_source_init_local_get_bind_data; + result.duckdb_v2_data_source_init_local_get_global_state = duckdb_v2_data_source_init_local_get_global_state; + result.duckdb_v2_data_source_init_local_get_user_data = duckdb_v2_data_source_init_local_get_user_data; + result.duckdb_v2_data_source_init_local_set_local_state = duckdb_v2_data_source_init_local_set_local_state; + result.duckdb_v2_data_source_progress_get_bind_data = duckdb_v2_data_source_progress_get_bind_data; + result.duckdb_v2_data_source_progress_get_global_state = duckdb_v2_data_source_progress_get_global_state; + result.duckdb_v2_data_source_progress_get_user_data = duckdb_v2_data_source_progress_get_user_data; + result.duckdb_v2_data_source_progress_set_progress = duckdb_v2_data_source_progress_set_progress; result.duckdb_v2_extension_register_table_function = duckdb_v2_extension_register_table_function; result.duckdb_v2_table_function_bind_add_result_column = duckdb_v2_table_function_bind_add_result_column; result.duckdb_v2_table_function_bind_set_cardinality = duckdb_v2_table_function_bind_set_cardinality; result.duckdb_v2_table_function_create = duckdb_v2_table_function_create; result.duckdb_v2_table_function_destroy = duckdb_v2_table_function_destroy; - result.duckdb_v2_table_function_exec_get_bind_data = duckdb_v2_table_function_exec_get_bind_data; - result.duckdb_v2_table_function_exec_get_global_state = duckdb_v2_table_function_exec_get_global_state; - result.duckdb_v2_table_function_exec_get_local_state = duckdb_v2_table_function_exec_get_local_state; - result.duckdb_v2_table_function_exec_get_output_chunk = duckdb_v2_table_function_exec_get_output_chunk; - result.duckdb_v2_table_function_exec_get_user_data = duckdb_v2_table_function_exec_get_user_data; result.duckdb_v2_table_function_get_signature = duckdb_v2_table_function_get_signature; - result.duckdb_v2_table_function_init_global_get_bind_data = duckdb_v2_table_function_init_global_get_bind_data; - result.duckdb_v2_table_function_init_global_get_user_data = duckdb_v2_table_function_init_global_get_user_data; - result.duckdb_v2_table_function_init_global_set_global_state = - duckdb_v2_table_function_init_global_set_global_state; - result.duckdb_v2_table_function_init_global_set_max_threads = duckdb_v2_table_function_init_global_set_max_threads; - result.duckdb_v2_table_function_init_local_get_bind_data = duckdb_v2_table_function_init_local_get_bind_data; - result.duckdb_v2_table_function_init_local_get_global_state = duckdb_v2_table_function_init_local_get_global_state; - result.duckdb_v2_table_function_init_local_get_user_data = duckdb_v2_table_function_init_local_get_user_data; - result.duckdb_v2_table_function_init_local_set_local_state = duckdb_v2_table_function_init_local_set_local_state; - result.duckdb_v2_table_function_progress_get_bind_data = duckdb_v2_table_function_progress_get_bind_data; - result.duckdb_v2_table_function_progress_get_global_state = duckdb_v2_table_function_progress_get_global_state; - result.duckdb_v2_table_function_progress_get_user_data = duckdb_v2_table_function_progress_get_user_data; - result.duckdb_v2_table_function_progress_set_progress = duckdb_v2_table_function_progress_set_progress; result.duckdb_v2_table_function_set_bind_callback = duckdb_v2_table_function_set_bind_callback; - result.duckdb_v2_table_function_set_exec_callback = duckdb_v2_table_function_set_exec_callback; - result.duckdb_v2_table_function_set_init_global_callback = duckdb_v2_table_function_set_init_global_callback; - result.duckdb_v2_table_function_set_init_local_callback = duckdb_v2_table_function_set_init_local_callback; result.duckdb_v2_table_function_set_name = duckdb_v2_table_function_set_name; - result.duckdb_v2_table_function_set_progress_callback = duckdb_v2_table_function_set_progress_callback; result.duckdb_v2_table_function_set_user_data = duckdb_v2_table_function_set_user_data; result.duckdb_v2_cast_function_create = duckdb_v2_cast_function_create; result.duckdb_v2_cast_function_destroy = duckdb_v2_cast_function_destroy; @@ -2087,28 +2047,7 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_copy_from_bind_get_user_data = duckdb_v2_copy_from_bind_get_user_data; result.duckdb_v2_copy_from_bind_set_bind_data = duckdb_v2_copy_from_bind_set_bind_data; result.duckdb_v2_copy_from_bind_set_cardinality = duckdb_v2_copy_from_bind_set_cardinality; - result.duckdb_v2_copy_from_exec_get_bind_data = duckdb_v2_copy_from_exec_get_bind_data; - result.duckdb_v2_copy_from_exec_get_global_state = duckdb_v2_copy_from_exec_get_global_state; - result.duckdb_v2_copy_from_exec_get_local_state = duckdb_v2_copy_from_exec_get_local_state; - result.duckdb_v2_copy_from_exec_get_output_chunk = duckdb_v2_copy_from_exec_get_output_chunk; - result.duckdb_v2_copy_from_exec_get_user_data = duckdb_v2_copy_from_exec_get_user_data; - result.duckdb_v2_copy_from_init_global_get_bind_data = duckdb_v2_copy_from_init_global_get_bind_data; - result.duckdb_v2_copy_from_init_global_get_user_data = duckdb_v2_copy_from_init_global_get_user_data; - result.duckdb_v2_copy_from_init_global_set_global_state = duckdb_v2_copy_from_init_global_set_global_state; - result.duckdb_v2_copy_from_init_global_set_max_threads = duckdb_v2_copy_from_init_global_set_max_threads; - result.duckdb_v2_copy_from_init_local_get_bind_data = duckdb_v2_copy_from_init_local_get_bind_data; - result.duckdb_v2_copy_from_init_local_get_global_state = duckdb_v2_copy_from_init_local_get_global_state; - result.duckdb_v2_copy_from_init_local_get_user_data = duckdb_v2_copy_from_init_local_get_user_data; - result.duckdb_v2_copy_from_init_local_set_local_state = duckdb_v2_copy_from_init_local_set_local_state; - result.duckdb_v2_copy_from_progress_get_bind_data = duckdb_v2_copy_from_progress_get_bind_data; - result.duckdb_v2_copy_from_progress_get_global_state = duckdb_v2_copy_from_progress_get_global_state; - result.duckdb_v2_copy_from_progress_get_user_data = duckdb_v2_copy_from_progress_get_user_data; - result.duckdb_v2_copy_from_progress_set_progress = duckdb_v2_copy_from_progress_set_progress; result.duckdb_v2_copy_from_set_bind_callback = duckdb_v2_copy_from_set_bind_callback; - result.duckdb_v2_copy_from_set_exec_callback = duckdb_v2_copy_from_set_exec_callback; - result.duckdb_v2_copy_from_set_init_global_callback = duckdb_v2_copy_from_set_init_global_callback; - result.duckdb_v2_copy_from_set_init_local_callback = duckdb_v2_copy_from_set_init_local_callback; - result.duckdb_v2_copy_from_set_progress_callback = duckdb_v2_copy_from_set_progress_callback; result.duckdb_v2_copy_function_create = duckdb_v2_copy_function_create; result.duckdb_v2_copy_function_destroy = duckdb_v2_copy_function_destroy; result.duckdb_v2_copy_function_set_name = duckdb_v2_copy_function_set_name; @@ -2147,6 +2086,12 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_copy_to_set_finalize_callback = duckdb_v2_copy_to_set_finalize_callback; result.duckdb_v2_copy_to_set_flush_callback = duckdb_v2_copy_to_set_flush_callback; result.duckdb_v2_copy_to_set_init_callback = duckdb_v2_copy_to_set_init_callback; + result.duckdb_v2_data_source_exec_get_column_count = duckdb_v2_data_source_exec_get_column_count; + result.duckdb_v2_data_source_exec_get_column_index = duckdb_v2_data_source_exec_get_column_index; + result.duckdb_v2_data_source_init_global_get_column_count = duckdb_v2_data_source_init_global_get_column_count; + result.duckdb_v2_data_source_init_global_get_column_index = duckdb_v2_data_source_init_global_get_column_index; + result.duckdb_v2_data_source_init_local_get_column_count = duckdb_v2_data_source_init_local_get_column_count; + result.duckdb_v2_data_source_init_local_get_column_index = duckdb_v2_data_source_init_local_get_column_index; result.duckdb_v2_expression_cast_get_mode = duckdb_v2_expression_cast_get_mode; result.duckdb_v2_expression_column_ref_get_index = duckdb_v2_expression_column_ref_get_index; result.duckdb_v2_expression_constant_get_value = duckdb_v2_expression_constant_get_value; @@ -2167,8 +2112,6 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_table_description_get_column_count = duckdb_v2_table_description_get_column_count; result.duckdb_v2_table_description_get_qname = duckdb_v2_table_description_get_qname; result.duckdb_v2_table_description_is_readonly = duckdb_v2_table_description_is_readonly; - result.duckdb_v2_table_function_exec_get_column_count = duckdb_v2_table_function_exec_get_column_count; - result.duckdb_v2_table_function_exec_get_column_index = duckdb_v2_table_function_exec_get_column_index; result.duckdb_v2_table_function_filter_pushdown_accept = duckdb_v2_table_function_filter_pushdown_accept; result.duckdb_v2_table_function_filter_pushdown_get_bind_data = duckdb_v2_table_function_filter_pushdown_get_bind_data; @@ -2181,12 +2124,6 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { duckdb_v2_table_function_filter_pushdown_get_filter_count; result.duckdb_v2_table_function_filter_pushdown_get_user_data = duckdb_v2_table_function_filter_pushdown_get_user_data; - result.duckdb_v2_table_function_init_global_get_column_count = - duckdb_v2_table_function_init_global_get_column_count; - result.duckdb_v2_table_function_init_global_get_column_index = - duckdb_v2_table_function_init_global_get_column_index; - result.duckdb_v2_table_function_init_local_get_column_count = duckdb_v2_table_function_init_local_get_column_count; - result.duckdb_v2_table_function_init_local_get_column_index = duckdb_v2_table_function_init_local_get_column_index; result.duckdb_v2_table_function_set_filter_pushdown_callback = duckdb_v2_table_function_set_filter_pushdown_callback; result.duckdb_v2_table_function_set_projection_pushdown = duckdb_v2_table_function_set_projection_pushdown; @@ -2201,27 +2138,23 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_attach_options_create = duckdb_v2_attach_options_create; result.duckdb_v2_attach_options_destroy = duckdb_v2_attach_options_destroy; result.duckdb_v2_attach_options_set = duckdb_v2_attach_options_set; + result.duckdb_v2_data_source_partition_data_get_bind_data = duckdb_v2_data_source_partition_data_get_bind_data; + result.duckdb_v2_data_source_partition_data_get_global_state = + duckdb_v2_data_source_partition_data_get_global_state; + result.duckdb_v2_data_source_partition_data_get_local_state = duckdb_v2_data_source_partition_data_get_local_state; + result.duckdb_v2_data_source_partition_data_get_partition_column_count = + duckdb_v2_data_source_partition_data_get_partition_column_count; + result.duckdb_v2_data_source_partition_data_get_partition_column_index = + duckdb_v2_data_source_partition_data_get_partition_column_index; + result.duckdb_v2_data_source_partition_data_get_user_data = duckdb_v2_data_source_partition_data_get_user_data; + result.duckdb_v2_data_source_partition_data_requires_batch_index = + duckdb_v2_data_source_partition_data_requires_batch_index; + result.duckdb_v2_data_source_partition_data_requires_partition_columns = + duckdb_v2_data_source_partition_data_requires_partition_columns; + result.duckdb_v2_data_source_partition_data_set_batch_index = duckdb_v2_data_source_partition_data_set_batch_index; + result.duckdb_v2_data_source_partition_data_set_partition_value = + duckdb_v2_data_source_partition_data_set_partition_value; result.duckdb_v2_instance_set_default = duckdb_v2_instance_set_default; - result.duckdb_v2_table_function_partition_data_get_bind_data = - duckdb_v2_table_function_partition_data_get_bind_data; - result.duckdb_v2_table_function_partition_data_get_global_state = - duckdb_v2_table_function_partition_data_get_global_state; - result.duckdb_v2_table_function_partition_data_get_local_state = - duckdb_v2_table_function_partition_data_get_local_state; - result.duckdb_v2_table_function_partition_data_get_partition_column_count = - duckdb_v2_table_function_partition_data_get_partition_column_count; - result.duckdb_v2_table_function_partition_data_get_partition_column_index = - duckdb_v2_table_function_partition_data_get_partition_column_index; - result.duckdb_v2_table_function_partition_data_get_user_data = - duckdb_v2_table_function_partition_data_get_user_data; - result.duckdb_v2_table_function_partition_data_requires_batch_index = - duckdb_v2_table_function_partition_data_requires_batch_index; - result.duckdb_v2_table_function_partition_data_requires_partition_columns = - duckdb_v2_table_function_partition_data_requires_partition_columns; - result.duckdb_v2_table_function_partition_data_set_batch_index = - duckdb_v2_table_function_partition_data_set_batch_index; - result.duckdb_v2_table_function_partition_data_set_partition_value = - duckdb_v2_table_function_partition_data_set_partition_value; result.duckdb_v2_table_function_partitioning_get_bind_data = duckdb_v2_table_function_partitioning_get_bind_data; result.duckdb_v2_table_function_partitioning_get_partition_column_count = duckdb_v2_table_function_partitioning_get_partition_column_count; @@ -2230,7 +2163,6 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_table_function_partitioning_get_user_data = duckdb_v2_table_function_partitioning_get_user_data; result.duckdb_v2_table_function_partitioning_set_partition_info = duckdb_v2_table_function_partitioning_set_partition_info; - result.duckdb_v2_table_function_set_partition_data_callback = duckdb_v2_table_function_set_partition_data_callback; result.duckdb_v2_table_function_set_partitioning_callback = duckdb_v2_table_function_set_partitioning_callback; result.duckdb_v2_validate_utf8 = duckdb_v2_validate_utf8; result.duckdb_v2_connection_register_multi_file_function = duckdb_v2_connection_register_multi_file_function; @@ -2241,6 +2173,11 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_copy_to_statistics_set_file_size = duckdb_v2_copy_to_statistics_set_file_size; result.duckdb_v2_copy_to_statistics_set_row_count = duckdb_v2_copy_to_statistics_set_row_count; result.duckdb_v2_data_chunk_get_capacity = duckdb_v2_data_chunk_get_capacity; + result.duckdb_v2_data_source_claim_batch_get_bind_data = duckdb_v2_data_source_claim_batch_get_bind_data; + result.duckdb_v2_data_source_claim_batch_get_global_state = duckdb_v2_data_source_claim_batch_get_global_state; + result.duckdb_v2_data_source_claim_batch_get_local_state = duckdb_v2_data_source_claim_batch_get_local_state; + result.duckdb_v2_data_source_claim_batch_get_user_data = duckdb_v2_data_source_claim_batch_get_user_data; + result.duckdb_v2_data_source_claim_batch_set_claimed = duckdb_v2_data_source_claim_batch_set_claimed; result.duckdb_v2_extension_register_multi_file_function = duckdb_v2_extension_register_multi_file_function; result.duckdb_v2_multi_file_function_create = duckdb_v2_multi_file_function_create; result.duckdb_v2_multi_file_function_destroy = duckdb_v2_multi_file_function_destroy; @@ -2249,13 +2186,6 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_multi_file_function_set_reader_type = duckdb_v2_multi_file_function_set_reader_type; result.duckdb_v2_multi_file_function_set_single_file_function = duckdb_v2_multi_file_function_set_single_file_function; - result.duckdb_v2_table_function_claim_batch_get_bind_data = duckdb_v2_table_function_claim_batch_get_bind_data; - result.duckdb_v2_table_function_claim_batch_get_global_state = - duckdb_v2_table_function_claim_batch_get_global_state; - result.duckdb_v2_table_function_claim_batch_get_local_state = duckdb_v2_table_function_claim_batch_get_local_state; - result.duckdb_v2_table_function_claim_batch_get_user_data = duckdb_v2_table_function_claim_batch_get_user_data; - result.duckdb_v2_table_function_claim_batch_set_claimed = duckdb_v2_table_function_claim_batch_set_claimed; - result.duckdb_v2_table_function_set_claim_batch_callback = duckdb_v2_table_function_set_claim_batch_callback; result.duckdb_v2_function_bind_get_arg_count = duckdb_v2_function_bind_get_arg_count; result.duckdb_v2_function_bind_get_arg_index = duckdb_v2_function_bind_get_arg_index; result.duckdb_v2_function_bind_get_arg_name = duckdb_v2_function_bind_get_arg_name; @@ -2396,12 +2326,11 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_query_metrics_node_get_metric_value = duckdb_v2_query_metrics_node_get_metric_value; result.duckdb_v2_query_metrics_node_get_name = duckdb_v2_query_metrics_node_get_name; result.duckdb_v2_statement_add_collection = duckdb_v2_statement_add_collection; + result.duckdb_v2_data_source_metrics_get_bind_data = duckdb_v2_data_source_metrics_get_bind_data; + result.duckdb_v2_data_source_metrics_get_global_state = duckdb_v2_data_source_metrics_get_global_state; + result.duckdb_v2_data_source_metrics_get_user_data = duckdb_v2_data_source_metrics_get_user_data; + result.duckdb_v2_data_source_metrics_set = duckdb_v2_data_source_metrics_set; result.duckdb_v2_table_function_add_virtual_column = duckdb_v2_table_function_add_virtual_column; - result.duckdb_v2_table_function_metrics_get_bind_data = duckdb_v2_table_function_metrics_get_bind_data; - result.duckdb_v2_table_function_metrics_get_global_state = duckdb_v2_table_function_metrics_get_global_state; - result.duckdb_v2_table_function_metrics_get_user_data = duckdb_v2_table_function_metrics_get_user_data; - result.duckdb_v2_table_function_metrics_set = duckdb_v2_table_function_metrics_set; - result.duckdb_v2_table_function_set_metrics_callback = duckdb_v2_table_function_set_metrics_callback; result.duckdb_v2_expression_check_statistics = duckdb_v2_expression_check_statistics; result.duckdb_v2_stats_create = duckdb_v2_stats_create; result.duckdb_v2_stats_destroy = duckdb_v2_stats_destroy; @@ -2484,7 +2413,20 @@ 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_data_source_create = duckdb_v2_data_source_create; + result.duckdb_v2_data_source_destroy = duckdb_v2_data_source_destroy; + result.duckdb_v2_data_source_set_claim_batch_callback = duckdb_v2_data_source_set_claim_batch_callback; + result.duckdb_v2_data_source_set_exec_callback = duckdb_v2_data_source_set_exec_callback; + result.duckdb_v2_data_source_set_init_global_callback = duckdb_v2_data_source_set_init_global_callback; + result.duckdb_v2_data_source_set_init_local_callback = duckdb_v2_data_source_set_init_local_callback; + result.duckdb_v2_data_source_set_metrics_callback = duckdb_v2_data_source_set_metrics_callback; + result.duckdb_v2_data_source_set_partition_data_callback = duckdb_v2_data_source_set_partition_data_callback; + result.duckdb_v2_data_source_set_progress_callback = duckdb_v2_data_source_set_progress_callback; + result.duckdb_v2_data_source_set_user_data = duckdb_v2_data_source_set_user_data; + result.duckdb_v2_table_function_set_data_source = duckdb_v2_table_function_set_data_source; result.duckdb_v2_value_variant_to_value = duckdb_v2_value_variant_to_value; + result.duckdb_v2_copy_from_set_data_source = duckdb_v2_copy_from_set_data_source; + result.duckdb_v2_connection_create_in_transaction = duckdb_v2_connection_create_in_transaction; return result; } diff --git a/src/duckdb/src/include/duckdb/main/client_context.hpp b/src/duckdb/src/include/duckdb/main/client_context.hpp index 8a80ff006..4f08257fb 100644 --- a/src/duckdb/src/include/duckdb/main/client_context.hpp +++ b/src/duckdb/src/include/duckdb/main/client_context.hpp @@ -213,6 +213,8 @@ class ClientContext : public enable_shared_from_this { //! Destroy the client context DUCKDB_API void Destroy(); + //! Ends the active query and leaves a shared transaction with a rollback vote, if the context participates in one + DUCKDB_API void LeaveSharedTransaction(); //! Get the table info of a specific table, or nullptr if it cannot be found. DUCKDB_API unique_ptr TableInfo(const Identifier &database_name, const Identifier &schema_name, diff --git a/src/duckdb/src/include/duckdb/main/config.hpp b/src/duckdb/src/include/duckdb/main/config.hpp index 4ad567636..97fd67348 100644 --- a/src/duckdb/src/include/duckdb/main/config.hpp +++ b/src/duckdb/src/include/duckdb/main/config.hpp @@ -91,6 +91,8 @@ struct DBConfigOptions { idx_t checkpoint_wal_size = 1 << 24; //! Whether extensions should be loaded on start-up bool load_extensions = true; + //! Whether to register autoloading placeholders for extension function overloads + bool register_extension_overloads = true; //! Where automatic installs go when neither autoinstall_extension_repository nor custom_extension_repository is //! set; empty means the core repository. The local_extension_repository capability sets it to its build's //! repository diff --git a/src/duckdb/src/include/duckdb/main/connection.hpp b/src/duckdb/src/include/duckdb/main/connection.hpp index 838e9a048..77a8a42f7 100644 --- a/src/duckdb/src/include/duckdb/main/connection.hpp +++ b/src/duckdb/src/include/duckdb/main/connection.hpp @@ -42,6 +42,11 @@ class Connection { //! Creates an internal connection that runs on behalf of `caller`: it follows the interrupts and the query //! deadline of caller's base client DUCKDB_API static Connection CreateInternal(ClientContext &caller); + //! Creates a connection that runs in the transaction active on `context`, e.g. the one a bind callback runs in. + //! It sees and can modify everything the transaction can, and follows the interrupts of `context`. It cannot + //! start, commit or roll back a transaction, and the transaction cannot commit while the connection is open: an + //! error of one of its statements invalidates the transaction as one of `context` would. + DUCKDB_API static Connection CreateInTransaction(ClientContext &context); // disable copy constructors Connection(const Connection &other) = delete; Connection &operator=(const Connection &) = delete; 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 04417b1cd..077cfe031 100644 --- a/src/duckdb/src/include/duckdb/main/database_file_opener.hpp +++ b/src/duckdb/src/include/duckdb/main/database_file_opener.hpp @@ -10,7 +10,7 @@ #include "duckdb/common/file_opener.hpp" #include "duckdb/common/local_file_system.hpp" -#include "duckdb/common/opener_file_system.hpp" +#include "duckdb/common/file_system.hpp" #include "duckdb/main/config.hpp" #include "duckdb/main/context.hpp" #include "duckdb/main/database.hpp" @@ -53,7 +53,7 @@ class DatabaseFileOpener : public FileOpener { Context &context; }; -class DatabaseFileSystem : public OpenerFileSystem { +class DatabaseFileSystem : public FileSystem { public: explicit DatabaseFileSystem(DatabaseInstance &db_p) : db(db_p), database_opener(db_p) { } @@ -70,7 +70,7 @@ class DatabaseFileSystem : public OpenerFileSystem { mutable DatabaseFileOpener database_opener; }; -class LocalDatabaseFileSystem : public OpenerFileSystem { +class LocalDatabaseFileSystem : public FileSystem { public: explicit LocalDatabaseFileSystem(DatabaseInstance &db_p); @@ -80,11 +80,11 @@ class LocalDatabaseFileSystem : public OpenerFileSystem { 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; + optional_ptr GetFixedFileSystem() const override; VirtualFileSystem &file_system; //! Only set if the default file system is not local - unique_ptr owned_file_system; + unique_ptr owned_file_system; mutable DatabaseFileOpener database_opener; }; 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 c1cf51a38..d300b2724 100644 --- a/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/file_system.hpp" #include "duckdb/common/enums/on_create_conflict.hpp" #include "duckdb/common/enums/on_entry_not_found.hpp" #include "duckdb/main/extension_install_info.hpp" @@ -38,7 +39,7 @@ class ExtensionRepositoryManager { public: //! The file extension used for the stored repository definitions //! Repository files carry a ".duckdb_extension." segment so that they are covered by the write protection in - //! OpenerFileSystem::IsDuckDBExtensionName: they hold the pinned keys that decide which extensions may be loaded, + //! FileSystem::IsDuckDBExtensionName: they hold the pinned keys that decide which extensions may be loaded, //! so they must not be writable through anything but CREATE EXTENSION REPOSITORY static constexpr const char *FILE_EXTENSION = ".duckdb_extension.repo.json"; //! The version of the repository file format diff --git a/src/duckdb/src/include/duckdb/optimizer/compressed_materialization.hpp b/src/duckdb/src/include/duckdb/optimizer/compressed_materialization.hpp index 81478c5e4..ea24875a9 100644 --- a/src/duckdb/src/include/duckdb/optimizer/compressed_materialization.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/compressed_materialization.hpp @@ -109,6 +109,7 @@ class CompressedMaterialization { const vector>> &ancestors, statistics_map_t &statistics_map); + //! Compress an operator after statistics propagation has resolved its input and output types. void Compress(unique_ptr &op); private: diff --git a/src/duckdb/src/include/duckdb/optimizer/cte_inlining.hpp b/src/duckdb/src/include/duckdb/optimizer/cte_inlining.hpp index 97529f6ee..8b3235abe 100644 --- a/src/duckdb/src/include/duckdb/optimizer/cte_inlining.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/cte_inlining.hpp @@ -25,6 +25,7 @@ class CTEInlining { public: explicit CTEInlining(Optimizer &optimizer); unique_ptr Optimize(unique_ptr op); + static bool IsAggregateOrWindow(const LogicalOperator &op); static bool EndsInAggregateOrDistinct(const LogicalOperator &op); private: diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp index 2fd8a94fe..ded98e6a8 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp @@ -12,6 +12,7 @@ #include "duckdb/common/unordered_map.hpp" #include "duckdb/parser/expression_map.hpp" #include "duckdb/planner/expression.hpp" +#include "duckdb/planner/filter/constant_filter_combiner.hpp" #include "duckdb/planner/joinside.hpp" #include "duckdb/storage/data_table.hpp" @@ -22,8 +23,6 @@ namespace duckdb { class LogicalGet; class Optimizer; -enum class ValueComparisonResult { PRUNE_LEFT, PRUNE_RIGHT, UNSATISFIABLE_CONDITION, PRUNE_NOTHING }; -enum class FilterResult { UNSATISFIABLE, SUCCESS, UNSUPPORTED }; enum class FilterPushdownResult { NO_PUSHDOWN, PUSHED_DOWN_PARTIALLY, PUSHED_DOWN_FULLY }; //! The FilterCombiner combines several filters and generates a logically equivalent set that is more efficient @@ -39,10 +38,7 @@ class FilterCombiner { ClientContext &context; public: - struct ExpressionValueInformation { - Value constant; - ExpressionType comparison_type; - }; + using ExpressionValueInformation = ConstantComparison; FilterResult AddFilter(unique_ptr expr); //! Splits on AND and adds each conjunct @@ -55,30 +51,43 @@ class FilterCombiner { void GenerateFilters(const std::function filter)> &callback); bool HasFilters(); + //! Whether expression equality preserves the identity of constants within this expression. + static bool CanMatchExpression(const Expression &expr); + //! A predicate that can be copied without changing evaluation effects or conflating matched operands. + static bool CanCopyFilter(const Expression &filter); + //! A safe predicate with the same truth value for keys equal under NOT DISTINCT FROM. + static bool IsKeyConstraint(const Expression &filter, const vector> &keys); + //! Derive a linear set of visible equalities and key constraints, retaining the source filters. + static void GenerateProjectionFilters(ClientContext &context, const vector> &filters, + const std::function &can_project, + const std::function)> &callback); + //! Remove exact duplicate, non-throwing, non-volatile predicates. + static void DeduplicateFilters(vector> &filters); void GenerateEquivalentFilters(const Expression &filter, const std::function filter)> &callback); //! The expression that a comparison, BETWEEN or IN filter compares with constants, or nullptr for other filters. //! Such a filter is false for NULL and has the same result for all values equal to that expression. static optional_ptr GetComparedExpression(const Expression &filter); - //! Generates the comparisons with constants that filters on one side of a join imply for the target side through - //! the equality conditions, e.g. [i = a and i = 500] => [a = 500]. Unlike GenerateEquivalentFilters, it only - //! replaces a compared expression as a whole, so values that are equal but not identical stay apart. + //! Generates key constraints implied for the target side by equality conditions, e.g. [i = a, i = 500] => [a = + //! 500]. Replaces only whole keys, including in NULL tests and Boolean combinations, preserving value equality. static void GenerateJoinFilters(const vector &conditions, const vector> &filters, JoinSide target_side, const std::function filter)> &callback); - TableFilterSet GenerateTableScanFilters(const vector &column_ids, - vector &pushdown_results); + //! Append generated filters to the scan's existing filters. + void GenerateTableScanFilters(TableFilterSet &table_filters, const vector &column_ids, + vector &pushdown_results); FilterPushdownResult TryPushdownGenericExpression(LogicalGet &get, Expression &expr); private: + void GenerateEquivalentKeyFilters(const Expression &filter, + const std::function filter)> &callback); FilterResult AddFilter(Expression &expr); FilterResult AddBoundComparisonFilter(Expression &expr); FilterResult AddTransitiveFilters(BoundFunctionExpression &comparison, bool is_root = true); unique_ptr FindTransitiveFilter(const Expression &expr); Expression &GetNode(Expression &expr); idx_t GetEquivalenceSet(Expression &expr); - FilterResult AddConstantComparison(vector &info_list, ExpressionValueInformation info); FilterPushdownResult TryPushdownConstantFilter(TableFilterSet &table_filters, const vector &column_ids, column_t column_id, vector &info_list); diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp index ce71b51d3..6eb91b320 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp @@ -33,7 +33,7 @@ class FilterPullup { // only pull up filters when there is a fork bool can_pullup = false; - // identify case the branch is a set operation (INTERSECT or EXCEPT) + // Whether a projection can carry additional columns needed by pulled filters. bool can_add_column = false; private: @@ -57,6 +57,11 @@ class FilterPullup { unique_ptr PullupInnerJoin(unique_ptr op); //! Pullup the filters on the partitions of a window unique_ptr PullupWindow(unique_ptr op); + //! Derive key constraints, retaining the original filters below the operator. + unique_ptr PullupAggregate(unique_ptr op); + unique_ptr PullupUnion(unique_ptr op); + unique_ptr ReturnConstraints(unique_ptr op, + vector> constraints); //! Pullup filter in LogicalIntersect or LogicalExcept op unique_ptr PullupSetOperation(unique_ptr op); //! Pullup filter in both sides of a join @@ -64,9 +69,6 @@ class FilterPullup { //! Finish pull up at this operator unique_ptr FinishPullup(unique_ptr op); - //! special treatment for SetOperations and projections - void ProjectSetOperation(LogicalProjection &proj); - }; // end FilterPullup } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/in_clause_rewriter.hpp b/src/duckdb/src/include/duckdb/optimizer/in_clause_rewriter.hpp index 634306e25..bfeb70cad 100644 --- a/src/duckdb/src/include/duckdb/optimizer/in_clause_rewriter.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/in_clause_rewriter.hpp @@ -11,6 +11,7 @@ #include "duckdb/planner/logical_operator_visitor.hpp" #include "duckdb/planner/logical_operator.hpp" #include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/in_clause.hpp" namespace duckdb { class ClientContext; @@ -27,8 +28,6 @@ class InClauseRewriter : public LogicalOperatorVisitor { unique_ptr root; public: - // Minimum number of values to use a hash join - static constexpr idx_t IN_CLAUSE_REWRITE_THRESHOLD = 6; static bool HasRewritableInClause(const Expression &expr); unique_ptr Rewrite(unique_ptr op); //! skips error-capture interiors (TRY, has_error) and guarded conjunction/CASE/COALESCE children: diff --git a/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp index 7604ecb97..bbe8e0aa7 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp @@ -32,7 +32,7 @@ class JoinFilterPushdownOptimizer : public LogicalOperatorVisitor { //! Equality propagation can return multiple equivalent columns per scan; single-column callers leave it disabled. //! Only the join filter pushdown continues into secure views (cross_secure_views): the other callers act on what //! they find, e.g. a target's estimated cardinality, which must not depend on a view's contents - static void GetPushdownFilterTargets(LogicalOperator &op, vector columns, + static void GetPushdownFilterTargets(LogicalOperator &op, const vector &columns, vector &targets, EqualityPropagation equality_propagation = EqualityPropagation::DISABLED, bool cross_secure_views = false); @@ -44,7 +44,7 @@ class JoinFilterPushdownOptimizer : public LogicalOperatorVisitor { void GenerateCTEFilters(LogicalMaterializedCTE &cte); void GenerateJoinFilters(LogicalComparisonJoin &join); static bool CanGenerateJoinFilters(const LogicalComparisonJoin &join); - static void GetCTEFilterTargets(LogicalOperator &op, vector columns, + static void GetCTEFilterTargets(LogicalOperator &op, const vector &columns, reference_map_t> &targets); private: diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp index f98e1400e..d000af06b 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp @@ -8,7 +8,7 @@ #pragma once #include "duckdb/common/reference_map.hpp" -#include "duckdb/optimizer/join_order/cardinality_value.hpp" +#include "duckdb/optimizer/relation_statistics/cardinality_value.hpp" #include "duckdb/optimizer/join_order/join_order_operator.hpp" #include "duckdb/optimizer/join_order/join_relation_set.hpp" #include "duckdb/optimizer/join_order/join_order_source_stats.hpp" @@ -19,10 +19,9 @@ namespace duckdb { class FilterInfo; class JoinPredicateModel; struct CardinalityEstimatorState; -struct CompositeJoinPairStats; -struct SelectivityState; struct FilterInfoWithTotalDomains; struct SelectivitySubgraph; +struct LogicalJoinStats; class CardinalityEstimator { public: @@ -31,12 +30,24 @@ class CardinalityEstimator { public: //! Initialize immutable logical statistics before estimating any relation set. - void Initialize(const vector &relations, const vector> &operators = {}, + void Initialize(vector relations, const vector> &operators = {}, const join_column_sources_t &sources = {}); //! All equivalent plans in a memo group share this estimate. CardinalityValue EstimateCardinality(JoinRelationSet &set); + //! Cost adaptation never changes the memoized raw point. + CardinalityValue EstimateCardinalityForCost(JoinRelationSet &set); + //! Project immutable region statistics, independently of the selected physical split. + optional ProjectStats(JoinRelationSet &set, const vector &bindings); private: + class ColumnProjection; + class CompositeJoinPairCaps; + struct SelectivityState; + + optional_ptr FindBoundary(JoinRelationSet &set, optional_ptr ®ion); + optional ProjectColumn(JoinRelationSet &set, ColumnBinding binding); + SemiAntiJoinCardinalityEstimate EstimateMembership(const LogicalJoinStats &boundary, JoinRelationSet &left, + JoinRelationSet &right, vector &domains); void InitEquivalentRelations(); void UpdateTotalDomains(RelationIndex relation, const RelationStats &stats, const join_column_sources_t &sources); void RestrictFilterDomains(const vector &relation_stats); @@ -61,20 +72,10 @@ class CardinalityEstimator { CardinalityValue CalculateInnerJoinSelectivity(CardinalityValue base_selectivity, FilterInfoWithTotalDomains &filter); CardinalityValue GetLeftJoinSelectivity(const JoinOrderOperator &join_operator); - bool ApplyJoinIncrement(CardinalityValue &target_selectivity, FilterInfoWithTotalDomains &edge, - reference_map_t &inner_join_pair_stats, - reference_set_t &capped_join_pairs, JoinRelationSet &scope, - optional_ptr join_pair = nullptr); - bool ApplyJoinPairCap(CardinalityValue &target_selectivity, JoinRelationSet &join_pair, - reference_map_t &inner_join_pair_stats, - reference_set_t &capped_join_pairs); - bool ApplyCompositeJoinPairCaps(CardinalityValue &target_selectivity, JoinRelationSet &scope, - reference_map_t &inner_join_pair_stats, - reference_set_t &capped_join_pairs); - double GetJoinPairCap(JoinRelationSet &join_pair); + CardinalityValue GetJoinPairCap(JoinRelationSet &join_pair); //! The number of key combinations of a join pair whose equalities cover a unique key of one of its relations, //! or 0 if they cover neither relation's key. - double GetUniqueJoinPairDomain(JoinRelationSet &join_pair); + CardinalityValue GetUniqueJoinPairDomain(JoinRelationSet &join_pair); void AddRelationStats(const FilterInfo &filter_info); bool EmptyFilter(const FilterInfo &filter_info); 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 deleted file mode 100644 index 6f1ee25fe..000000000 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_value.hpp +++ /dev/null @@ -1,130 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/optimizer/join_order/cardinality_value.hpp -// -//===----------------------------------------------------------------------===// -#pragma once - -#include "duckdb/common/common.hpp" - -#include -#include - -namespace duckdb { - -//! Retain scaled numerator and denominator products until the final division. -//! Inputs are finite nonnegative row/domain counts or selectivity factors; only accumulated products need extra range. -class CardinalityValue { -public: - explicit CardinalityValue(double value = 1) : CardinalityValue(Product(value), Product(1)) { - } - - bool IsZero() const { - 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; - } - Product quotient(numerator.significand / denominator); - quotient.exponent += numerator.exponent; - if (quotient.exponent > std::numeric_limits::max_exponent) { - // A final overflow remains infinity. Saturating here would also tie costs and can overflow when adding - // them. - return std::numeric_limits::infinity(); - } - if (quotient.exponent < std::numeric_limits::min_exponent - std::numeric_limits::digits) { - return 0; - } - return std::ldexp(quotient.significand, static_cast(quotient.exponent)); - } - - idx_t GetIndex() const { - auto value = GetDouble(); - // Keep a positive estimate from becoming an empty input in subsequent optimization. - if (value < 1) { - return IsZero() ? 0 : 1; - } - auto maximum = std::numeric_limits::max(); - return value >= static_cast(maximum) ? maximum : static_cast(value); - } - - CardinalityValue operator*(const CardinalityValue &other) const { - return CardinalityValue(numerator * other.numerator, Product(denominator * other.denominator)); - } - - CardinalityValue operator/(const CardinalityValue &other) const { - D_ASSERT(!other.IsZero()); - return CardinalityValue(numerator * other.denominator, other.numerator * denominator); - } - - CardinalityValue &operator*=(const CardinalityValue &other) { - *this = *this * other; - return *this; - } - - bool operator>(const CardinalityValue &other) const { - return numerator * other.denominator > other.numerator * denominator; - } - - bool operator<(const CardinalityValue &other) const { - return other > *this; - } - -private: - struct Product { - explicit Product(double value) { - D_ASSERT(std::isfinite(value) && value >= 0); - int value_exponent; - significand = std::frexp(value, &value_exponent); - exponent = value_exponent; - } - - Product operator*(const Product &other) const { - auto result = *this * other.significand; - if (result.significand != 0) { - result.exponent += other.exponent; - } - return result; - } - - Product operator*(double other) const { - Product result(significand * other); - if (result.significand != 0) { - result.exponent += exponent; - } - return result; - } - - bool operator>(const Product &other) const { - if (significand == 0 || other.significand == 0) { - return significand > other.significand; - } - return exponent == other.exponent ? significand > other.significand : exponent > other.exponent; - } - - double significand; - int64_t exponent; - }; - - CardinalityValue(Product numerator, Product denominator) - : numerator(numerator), denominator(denominator.significand) { - // Remove common powers of two without dividing the significands. - this->numerator.exponent -= denominator.exponent; - } - - Product numerator; - double denominator; -}; - -} // namespace duckdb 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 f4bfebbd9..c70ec0f2a 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 @@ -33,7 +33,7 @@ class CostModel { public: //! 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); + JoinRelationSet &output); //! Minimum work for either orientation, excluding nonnegative operator-specific work. double ComputeCostLowerBound(const DPJoinNode &left, const DPJoinNode &right, double output_rows); CardinalityEstimator &GetCardinalityEstimator(); diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_node.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_node.hpp index 7b5c5127f..c7cebd689 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_node.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_node.hpp @@ -8,7 +8,7 @@ #pragma once #include "duckdb/optimizer/join_order/join_relation_set.hpp" -#include "duckdb/optimizer/join_order/cardinality_value.hpp" +#include "duckdb/optimizer/relation_statistics/cardinality_value.hpp" #include "duckdb/optimizer/recursive_join_planning.hpp" 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 5134eaf74..87bafa7a6 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 @@ -29,7 +29,7 @@ class JoinOrderCandidateEvaluator { bool CanImprovePair(const JoinOrderPlanMap &plans, const DPJoinNode &left, const DPJoinNode &right, const DPJoinNode &incumbent) const; - void InitLeafPlans(JoinOrderPlanMap &plans, const vector &relation_stats); + void InitLeafPlans(JoinOrderPlanMap &plans, vector relation_stats); void InitInputPlan(JoinOrderPlanMap &plans); JoinPlanCost GetPlanCost(const DPJoinNode &node) const; //! Borrowed vectors are invalidated by graph changes or ResetConnectionCache. 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 3163afd0c..a4bc28927 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 @@ -19,8 +19,9 @@ class LogicalOperator; struct JoinColumnSource { ColumnBinding binding; + //! The provider's integer row count, before estimated scan/filter selectivity. idx_t source_cardinality; - idx_t scan_cardinality; + CardinalityValue scan_cardinality; DistinctCount domain; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_predicate.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_predicate.hpp index 5fcc4e9d5..6c72e917f 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_predicate.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_predicate.hpp @@ -45,6 +45,7 @@ class JoinPredicate { JoinPredicateClass GetPredicateClass() const; JoinType GetJoinType() const; ExpressionType GetComparisonType() const; + bool IsVolatile() const; JoinRelationSet &GetSet() const; JoinRelationSet &GetLeftSet() const; JoinRelationSet &GetRightSet() const; @@ -60,6 +61,7 @@ class JoinPredicate { bool HasValidEqualityBindings() const; bool CanBuildEqualityClosure() const; bool CanBuildSelectivityDomain() const; + bool IsResidualFilter() const; bool IsEquivalencePredicate() const; void SetEqualityClassIndex(optional_idx equality_class_index); optional_idx GetEqualityClassIndex() const; @@ -71,6 +73,7 @@ class JoinPredicate { reference filter; JoinPredicateClass predicate_class; ExpressionType comparison_type; + bool is_volatile; ColumnBinding left_equality_binding; ColumnBinding right_equality_binding; optional_idx equality_class_index; 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 88f169cc5..9280dffdb 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 @@ -24,6 +24,7 @@ struct JoinRelationSet { public: string ToString() const; bool Empty() const; + bool Contains(RelationIndex relation) const; static bool IsSubset(const JoinRelationSet &super, const JoinRelationSet &sub); static bool Intersects(const JoinRelationSet &left, const JoinRelationSet &right); 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 2b3ab5662..a0479449b 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 @@ -22,6 +22,7 @@ namespace duckdb { class QueryGraphEdges; +class CardinalityEstimator; struct GenerateJoinRelation { public: @@ -33,6 +34,8 @@ struct GenerateJoinRelation { RelationStats stats; }; +enum class PlanEstimateUpdate { KEEP, UPDATE }; + //! The QueryGraphManager manages the process of extracting the reorderable and nonreorderable operations //! from the logical plan and creating the intermediate structures needed by the plan enumerator. //! When the plan enumerator finishes, the Query Graph Manger can then recreate the logical plan. @@ -45,11 +48,14 @@ class QueryGraphManager { bool Build(JoinOrderOptimizer &optimizer, LogicalOperator &op); //! Prepare an inner-join region without mutating or enumerating its plan. bool BuildForEstimation(RelationStatsExtractor &extractor, LogicalOperator &op); - optional CombineRelationStats(const vector &bindings, - const vector &relation_stats, - idx_t root_cardinality) const; + optional ProjectStats(CardinalityEstimator &estimator, JoinRelationSet &set, + const vector &bindings) const; + //! Project a complete region through its original unary ancestors without reconstructing the join order. + optional ProjectRetainedStats(CardinalityEstimator &estimator, JoinRelationSet &set, + LogicalOperator &plan, + PlanEstimateUpdate update_estimates = PlanEstimateUpdate::KEEP); //! Reconstruct the logical plan using the plan found by the plan enumerator - GenerateJoinRelation Reconstruct(unique_ptr plan, const vector &relation_stats); + GenerateJoinRelation Reconstruct(unique_ptr plan, CardinalityEstimator &estimator); //! Plan enumerator may not find a full plan and therefore will need to create cross products to create edges. void CreateQueryGraphCrossProduct(JoinRelationSet &left, JoinRelationSet &right); //! Admit original cross-product edges when the current hyperedges cannot complete enumeration. @@ -68,9 +74,6 @@ class QueryGraphManager { const vector> &GetJoinOperators() const; private: - optional CombineRelationStats(const vector &bindings, - const vector> &inputs, - idx_t root_cardinality) const; void PreparePredicateModel(LogicalOperator &op); void GetColumnBinding(const Expression &expression, ColumnBinding &binding); void GetEquivalenceBinding(const Expression &expression, ColumnBinding &binding); @@ -84,12 +87,14 @@ class QueryGraphManager { void BuildInnerCompanionSets(); void ClearExtractedExpressions(); vector> GetPendingFilters(JoinRelationSet &root) const; + RelationStats ApplyAncestorStats(const vector> &ancestors, RelationStats stats, + PlanEstimateUpdate update_estimates); 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, + CardinalityEstimator &estimator, const vector> &pending_filters); public: @@ -107,6 +112,7 @@ class QueryGraphManager { //! Filter information including the column_bindings that join filters //! used by the cardinality estimator to estimate distinct counts vector> filters_and_bindings; + expression_set_t extracted_filter_expressions; vector> join_operators; //! Only these operator occurrences can restrict a candidate join. vector> candidate_constraints; 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 91ef7a6e0..123654639 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 @@ -31,6 +31,8 @@ class RelationStatsExtractor; struct JoinOrderExtraction { vector> filters; vector> join_operators; + //! Original FILTER expressions owned by reconstruction, including duplicate predicates. + expression_set_t extracted_filter_expressions; }; //! Represents a single relation and any metadata accompanying that relation diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/cardinality_value.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/cardinality_value.hpp new file mode 100644 index 000000000..33734780d --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/cardinality_value.hpp @@ -0,0 +1,208 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/relation_statistics/cardinality_value.hpp +// +//===----------------------------------------------------------------------===// +#pragma once + +#include "duckdb/common/common.hpp" + +#include +#include +#include + +namespace duckdb { + +//! Retain scaled numerator and denominator products until the final division. +//! Inputs are finite nonnegative row/domain counts or selectivity factors; only accumulated products need extra range. +class CardinalityValue { +public: + // Scalar inputs can widen to a scaled point; materializing a point remains explicit. + CardinalityValue(double value = 1) : CardinalityValue(Product(value), Product(1)) { // NOLINT + } + + template , int> = 0> + CardinalityValue(T value) : CardinalityValue(static_cast(value)) { // NOLINT + } + + bool IsZero() const { + return numerator.significand == 0; + } + + //! Rounded numeric equality need not make operands interchangeable in subsequent comparisons. + bool HasSameRepresentation(const CardinalityValue &other) const { + return numerator.significand == other.numerator.significand && numerator.exponent == other.numerator.exponent && + denominator == other.denominator && + std::signbit(numerator.significand) == std::signbit(other.numerator.significand); + } + + 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; + } + Product quotient(numerator.significand / denominator); + quotient.exponent += numerator.exponent; + if (quotient.exponent > std::numeric_limits::max_exponent) { + // A final overflow remains infinity. Saturating here would also tie costs and can overflow when adding + // them. + return std::numeric_limits::infinity(); + } + if (quotient.exponent < std::numeric_limits::min_exponent - std::numeric_limits::digits) { + return 0; + } + return std::ldexp(quotient.significand, static_cast(quotient.exponent)); + } + + idx_t GetIndex() const { + auto value = GetDouble(); + // Keep a positive estimate from becoming an empty input in subsequent optimization. + if (value < 1) { + return IsZero() ? 0 : 1; + } + auto maximum = std::numeric_limits::max(); + return value >= static_cast(maximum) ? maximum : static_cast(value); + } + + friend CardinalityValue operator*(const CardinalityValue &left, const CardinalityValue &right) { + return CardinalityValue(left.numerator * right.numerator, Product(left.denominator * right.denominator)); + } + + friend CardinalityValue operator/(const CardinalityValue &left, const CardinalityValue &right) { + D_ASSERT(!right.IsZero()); + return CardinalityValue(left.numerator * right.denominator, right.numerator * left.denominator); + } + + friend CardinalityValue operator+(const CardinalityValue &left, const CardinalityValue &right) { + return CardinalityValue( + (left.numerator * right.denominator).Add(right.numerator * left.denominator, Product::Operation::ADD), + Product(left.denominator * right.denominator)); + } + + //! Subtraction of nonnegative estimates, clamped at zero. + friend CardinalityValue operator-(const CardinalityValue &left, const CardinalityValue &right) { + if (!(left > right)) { + return CardinalityValue(0); + } + return CardinalityValue( + (left.numerator * right.denominator).Add(right.numerator * left.denominator, Product::Operation::SUBTRACT), + Product(left.denominator * right.denominator)); + } + + CardinalityValue &operator*=(const CardinalityValue &other) { + *this = *this * other; + return *this; + } + + CardinalityValue &operator+=(const CardinalityValue &other) { + *this = *this + other; + return *this; + } + + friend bool operator>(const CardinalityValue &left, const CardinalityValue &right) { + // Equal power-of-two denominators cancel without rounding. + if (left.denominator == 0.5 && right.denominator == 0.5) { + return left.numerator > right.numerator; + } + return left.numerator * right.denominator > right.numerator * left.denominator; + } + + friend bool operator<(const CardinalityValue &left, const CardinalityValue &right) { + return right > left; + } + + friend bool operator==(const CardinalityValue &left, const CardinalityValue &right) { + return !(left > right) && !(right > left); + } + + friend bool operator!=(const CardinalityValue &left, const CardinalityValue &right) { + return !(left == right); + } + + friend bool operator<=(const CardinalityValue &left, const CardinalityValue &right) { + return !(left > right); + } + + friend bool operator>=(const CardinalityValue &left, const CardinalityValue &right) { + return !(left < right); + } + +private: + struct Product { + enum class Operation { ADD, SUBTRACT }; + + explicit Product(double value) { + D_ASSERT(std::isfinite(value) && value >= 0); + int value_exponent; + significand = std::frexp(value, &value_exponent); + exponent = value_exponent; + } + + Product operator*(const Product &other) const { + auto result = *this * other.significand; + if (result.significand != 0) { + result.exponent += other.exponent; + } + return result; + } + + Product operator*(double other) const { + Product result(significand * other); + if (result.significand != 0) { + result.exponent += exponent; + } + return result; + } + + Product Add(const Product &other, Operation operation) const { + if (other.significand == 0) { + return *this; + } + if (significand == 0) { + D_ASSERT(operation == Operation::ADD); + return other; + } + auto common_exponent = MaxValue(exponent, other.exponent); + auto scale = [&](const Product &value) { + auto distance = common_exponent - value.exponent; + return distance > std::numeric_limits::digits + ? 0.0 + : std::ldexp(value.significand, -static_cast(distance)); + }; + Product result(scale(*this) + (operation == Operation::SUBTRACT ? -scale(other) : scale(other))); + if (result.significand != 0) { + result.exponent += common_exponent; + } + return result; + } + + bool operator>(const Product &other) const { + if (significand == 0 || other.significand == 0) { + return significand > other.significand; + } + return exponent == other.exponent ? significand > other.significand : exponent > other.exponent; + } + + double significand; + int64_t exponent; + }; + + CardinalityValue(Product numerator, Product denominator) + : numerator(numerator), denominator(denominator.significand) { + // Remove common powers of two without dividing the significands. + this->numerator.exponent -= denominator.exponent; + } + + Product numerator; + double denominator; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp index 9349fe725..c3220c1f0 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp @@ -9,10 +9,12 @@ #pragma once #include "duckdb/common/optional_idx.hpp" +#include "duckdb/common/optional.hpp" #include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/types.hpp" #include "duckdb/planner/column_binding.hpp" #include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/optimizer/relation_statistics/cardinality_value.hpp" namespace duckdb { @@ -20,10 +22,10 @@ enum class DistinctCountSource : uint8_t { CARDINALITY, MIN_MAX, HLL, EXACT }; struct DistinctCount { public: - DistinctCount(idx_t distinct_count, DistinctCountSource source); + DistinctCount(CardinalityValue distinct_count, DistinctCountSource source); public: - idx_t distinct_count; + CardinalityValue distinct_count; DistinctCountSource source; }; @@ -33,7 +35,7 @@ struct SemiAntiJoinDomainEvidence { void TightenDomainBound(idx_t bound); void MarkUnique(); void Invalidate(); - optional_idx GetSupportedDomainSize(idx_t current_domain) const; + optional GetSupportedDomainSize(CardinalityValue current_domain) const; optional_idx GetDomainBound() const; private: @@ -47,7 +49,7 @@ struct RelationColumnStats { RelationColumnStats(ColumnBinding binding, DistinctCount total_domain, DistinctCount current_domain, Identifier name, SemiAntiJoinDomainEvidence semi_anti_join_domain_evidence = SemiAntiJoinDomainEvidence()); - optional_idx GetSupportedSemiAntiDomainSize() const; + optional GetSupportedSemiAntiDomainSize() const; public: ColumnBinding binding; @@ -68,18 +70,25 @@ struct RelationStats { optional_idx FindColumn(ColumnBinding binding) const; optional_ptr GetColumnStats(ColumnBinding binding) const; bool MatchesBindings(const vector &bindings) const; + //! Reconcile the point with its structural upper bound, then cap current column domains. void CapCurrentDomainsToCardinality(); void Verify(const vector &bindings) const; + bool IsEmpty() const; + //! Raw point reconciled with its independent upper bound; no cost or display floor. + CardinalityValue GetCardinality() const; + CardinalityValue GetCardinalityForCost() const; + idx_t GetCardinalityForPlan() const; public: vector columns; - idx_t cardinality; + CardinalityValue cardinality; + //! A provider or structural upper bound, never inferred from the point estimate. + optional_idx max_cardinality; //! Cumulative estimated fraction of rows retained from the most recent statistics source. //! Aggregation and DISTINCT establish a new source. - double row_retention = 1; - //! Indexes of the columns that together identify a row of a join-order relation, e.g. the groups of an - //! aggregate. Empty when no such key is known. - vector unique_key; + CardinalityValue row_retention = 1; + //! Alternative unique keys from Distinctness, expressed as column indexes in this relation. + vector> unique_keys; bool stats_initialized = false; Identifier table_name; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp index 3c139105a..b53582e5a 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp @@ -32,16 +32,17 @@ class LogicalLimit; class LogicalProjection; class LogicalWindow; class RelationStatsExtractor; +class NodeStatistics; struct SemiAntiJoinDomain { - idx_t total_domain; - idx_t rhs_current_domain; + CardinalityValue total_domain; + CardinalityValue rhs_current_domain; ColumnBinding preserved_binding; ColumnBinding rhs_binding; }; struct SemiAntiJoinCardinalityEstimate { - double cardinality; + CardinalityValue cardinality; bool used_domain_evidence; }; @@ -57,6 +58,7 @@ class RelationStatisticsHelper { public: static RelationStats ExtractGetStats(LogicalGet &get, ClientContext &context); static RelationStats ExtractGetStats(LogicalGet &get, ClientContext &context, idx_t source_cardinality); + static RelationStats ExtractGetStats(LogicalGet &get, ClientContext &context, const NodeStatistics &source_stats); static RelationStats ExtractDelimGetStats(LogicalDelimGet &delim_get, ClientContext &context); static RelationStats ExtractDummyScanStats(LogicalDummyScan &dummy_scan, ClientContext &context); static RelationStats ExtractExpressionGetStats(LogicalExpressionGet &expression_get, ClientContext &context); @@ -71,10 +73,15 @@ class RelationStatisticsHelper { //! Reuse the caller snapshot for aggregate input refinements. static optional ExtractAggregationStats(LogicalAggregate &aggregate, const RelationStats &child_stats, - RelationStatsExtractor &extractor, - bool use_operator_cardinality = false); + RelationStatsExtractor &extractor); static optional ExtractWindowStats(LogicalWindow &window, const RelationStats &child_stats); static optional ExtractFilterStats(LogicalFilter &filter, const RelationStats &child_stats); + static optional ExtractFilterStats(LogicalFilter &filter, const RelationStats &child_stats, + const vector> &expressions); + //! Condition an input snapshot without requiring an attached logical operator or changing its layout. + static RelationStats ConditionFilterStats(const RelationStats &input, + const vector> &expressions, + const vector &bindings); static optional ExtractLimitStats(LogicalLimit &limit, const RelationStats &child_stats); static RelationStats ExtractEmptyResultStats(LogicalEmptyResult &empty); static optional ProjectOutputStats(const RelationStats &stats, LogicalOperator &op); @@ -83,30 +90,33 @@ class RelationStatisticsHelper { static void ApplySemiAntiJoinStats(LogicalComparisonJoin &join, const RelationStats &left, const RelationStats &right, RelationStats &result); static idx_t CardinalityFromDouble(double cardinality); - static idx_t EstimateDistinctCardinality(const vector &distinct_counts, idx_t input_cardinality); - static idx_t EstimateGroupCardinality(LogicalOperator &input, const RelationStats &input_stats, - vector groups, RelationStatsExtractor &extractor, - bool use_operator_cardinality = false); - static DistinctCount EstimateCurrentDomain(const DistinctCount ¤t_domain, idx_t input_cardinality, - idx_t output_cardinality); - static void ApplyCardinality(RelationStats &stats, idx_t output_cardinality); + static CardinalityValue EstimateDistinctCardinality(const vector &distinct_counts, + CardinalityValue input_cardinality); + static CardinalityValue EstimateGroupCardinality(LogicalOperator &input, const RelationStats &input_stats, + vector groups, RelationStatsExtractor &extractor); + static DistinctCount EstimateCurrentDomain(const DistinctCount ¤t_domain, CardinalityValue input_cardinality, + CardinalityValue output_cardinality); + static void ApplyCardinality(RelationStats &stats, CardinalityValue output_cardinality); + static optional_idx AddCardinalityBounds(optional_idx left, optional_idx right); + static optional_idx MultiplyCardinalityBounds(optional_idx left, optional_idx right); + static optional_idx JoinCardinalityBound(JoinType type, optional_idx left, optional_idx right); //! Share fallback policy between ordinary statistics and scaled join cardinalities. - template - static T EstimateSemiAntiJoinFallbackCardinality(const T &preserved_cardinality, idx_t rhs_cardinality, - JoinType join_type) { + static CardinalityValue EstimateSemiAntiJoinFallbackCardinality(CardinalityValue preserved_cardinality, + CardinalityValue rhs_cardinality, + JoinType join_type) { auto is_anti = join_type == JoinType::ANTI || join_type == JoinType::RIGHT_ANTI; - if (rhs_cardinality == 0) { - return is_anti ? MaxValue(T(0), preserved_cardinality) : T(0); + if (rhs_cardinality.IsZero()) { + return is_anti ? preserved_cardinality : CardinalityValue(0); } - // Retain fractional estimates while composing costs. - auto estimate = MinValue(preserved_cardinality, MaxValue(T(1), preserved_cardinality * T(DEFAULT_SELECTIVITY))); - return MaxValue(T(0), estimate); + return preserved_cardinality * CardinalityValue(DEFAULT_SELECTIVITY); } - static SemiAntiJoinCardinalityEstimate EstimateSemiAntiJoinFallback(double preserved_cardinality, - idx_t rhs_cardinality, JoinType join_type); + static SemiAntiJoinCardinalityEstimate EstimateSemiAntiJoinFallback(CardinalityValue preserved_cardinality, + CardinalityValue rhs_cardinality, + JoinType join_type); static SemiAntiJoinCardinalityEstimate - EstimateSemiAntiJoinCardinality(double preserved_cardinality, idx_t rhs_cardinality, double rhs_row_retention, - JoinType join_type, const vector &domains, bool has_residual); + EstimateSemiAntiJoinCardinality(CardinalityValue preserved_cardinality, CardinalityValue rhs_cardinality, + CardinalityValue rhs_row_retention, JoinType join_type, + const vector &domains, bool has_residual); static SemiAntiJoinCardinalityEstimate EstimateSemiAntiJoinCardinality(LogicalComparisonJoin &join, const RelationStats &left, const RelationStats &right); //! Estimate rows and groups for a matched tuple restriction with column-reference conditions. diff --git a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp index a9b8ce01c..c8677b49e 100644 --- a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp @@ -53,6 +53,7 @@ class StatisticsPropagator { StatisticsPropagator(Optimizer &optimizer, unique_ptr &root, StatisticsPropagationMode mode = StatisticsPropagationMode::FULL); + //! Propagate bottom-up, returning a subtree with resolved types (including any replacement operators). unique_ptr PropagateStatistics(unique_ptr &node_ptr); //! Propagate statistics through a standalone expression, given the statistics of the columns it references unique_ptr @@ -187,7 +188,7 @@ class StatisticsPropagator { optional_ptr right, ComparisonContext context); - //! Try to execute aggregates using only the statistics if possible + //! Try to execute aggregates using only the statistics, resolving any replacement subtree before returning. void TryExecuteAggregates(LogicalAggregate &op, unique_ptr &node_ptr); void ReplaceWithEmptyResult(unique_ptr &node); diff --git a/src/duckdb/src/include/duckdb/parser/parsed_data/transaction_info.hpp b/src/duckdb/src/include/duckdb/parser/parsed_data/transaction_info.hpp index 0e1df39ca..0f6342a15 100644 --- a/src/duckdb/src/include/duckdb/parser/parsed_data/transaction_info.hpp +++ b/src/duckdb/src/include/duckdb/parser/parsed_data/transaction_info.hpp @@ -12,7 +12,7 @@ namespace duckdb { -enum class TransactionType : uint8_t { INVALID, BEGIN_TRANSACTION, COMMIT, ROLLBACK }; +enum class TransactionType : uint8_t { INVALID, BEGIN_TRANSACTION, COMMIT, ROLLBACK, JOIN_TRANSACTION }; enum class TransactionModifierType : uint8_t { TRANSACTION_DEFAULT_MODIFIER, @@ -44,6 +44,8 @@ struct TransactionInfo : public ParseInfo { TransactionInvalidationPolicy invalidation_policy; //! If transaction fails, automatically do a ROLLBACK; bool auto_rollback; + //! The shared transaction to join (JOIN_TRANSACTION only) + string share_id; public: void Serialize(Serializer &serializer) const override; diff --git a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp index a3731a61f..7492f6f62 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp @@ -2317,10 +2317,11 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 83, 101, 116, 65, 115, 115, 105, 103, 110, 109, 101, 110, 116, 32, 60, 45, 32, 86, 97, 114, 105, 97, 98, 108, 101, 65, 115, 115, 105, 103, 110, 32, 86, 97, 114, 105, 97, 98, 108, 101, 76, 105, 115, 116, 10, 86, 97, 114, 105, 97, 98, 108, 101, 65, 115, 115, 105, 103, 110, 32, 60, 45, 32, 39, 61, 39, 32, 47, 32, 39, 84, 79, 39, 10, 86, 97, 114, 105, 97, 98, 108, 101, 76, 105, 115, 116, 32, 60, 45, 32, 76, 105, 115, 116, 40, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 41, 10, - 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 66, 101, 103, 105, 110, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 32, 47, 32, 82, 111, 108, 108, 98, 97, 99, 107, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 32, 47, 32, 67, 111, 109, 109, 105, 116, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 10, + 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 66, 101, 103, 105, 110, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 32, 47, 32, 82, 111, 108, 108, 98, 97, 99, 107, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 32, 47, 32, 67, 111, 109, 109, 105, 116, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 32, 47, 32, 74, 111, 105, 110, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 10, 66, 101, 103, 105, 110, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 32, 60, 45, 32, 83, 116, 97, 114, 116, 79, 114, 66, 101, 103, 105, 110, 32, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 63, 32, 82, 101, 97, 100, 79, 114, 87, 114, 105, 116, 101, 63, 10, 82, 111, 108, 108, 98, 97, 99, 107, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 32, 60, 45, 32, 65, 98, 111, 114, 116, 79, 114, 82, 111, 108, 108, 98, 97, 99, 107, 32, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 63, 10, 67, 111, 109, 109, 105, 116, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 32, 60, 45, 32, 67, 111, 109, 109, 105, 116, 79, 114, 69, 110, 100, 32, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 63, 10, + 74, 111, 105, 110, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 32, 60, 45, 32, 39, 74, 79, 73, 78, 39, 32, 39, 84, 82, 65, 78, 83, 65, 67, 84, 73, 79, 78, 39, 32, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 10, 83, 116, 97, 114, 116, 79, 114, 66, 101, 103, 105, 110, 32, 60, 45, 32, 39, 83, 84, 65, 82, 84, 39, 32, 47, 32, 39, 66, 69, 71, 73, 78, 39, 10, 84, 114, 97, 110, 115, 97, 99, 116, 105, 111, 110, 32, 60, 45, 32, 39, 87, 79, 82, 75, 39, 32, 47, 32, 39, 84, 82, 65, 78, 83, 65, 67, 84, 73, 79, 78, 39, 10, 82, 101, 97, 100, 79, 114, 87, 114, 105, 116, 101, 32, 60, 45, 32, 39, 82, 69, 65, 68, 39, 32, 82, 101, 97, 100, 79, 110, 108, 121, 79, 114, 82, 101, 97, 100, 87, 114, 105, 116, 101, 10, diff --git a/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp b/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp index 425b12a92..062908be6 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp @@ -1204,6 +1204,7 @@ enum class PEGRuleId : uint32_t { BeginTransaction, RollbackTransaction, CommitTransaction, + JoinTransaction, StartOrBegin, Transaction, ReadOrWrite, diff --git a/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp b/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp index 224b90be1..06e4b9845 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp @@ -2685,6 +2685,8 @@ class PEGTransformerFactory { GeneratedTransformProcess &process); static arena_ptr FinalizeCommitTransactionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeJoinTransactionTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static arena_ptr FinalizeReadOrWriteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeReadOnlyTrampoline(PEGTransformer &transformer, @@ -4574,6 +4576,7 @@ class PEGTransformerFactory { const optional &read_or_write); static unique_ptr TransformRollbackTransaction(PEGTransformer &transformer, const bool &has_result); static unique_ptr TransformCommitTransaction(PEGTransformer &transformer, const bool &has_result); + static unique_ptr TransformJoinTransaction(PEGTransformer &transformer, const string &share_id); static TransactionModifierType TransformReadOrWrite(PEGTransformer &transformer, const TransactionModifierType &read_only_or_read_write); static TransactionModifierType TransformReadOnly(PEGTransformer &transformer); diff --git a/src/duckdb/src/include/duckdb/planner/filter/constant_filter_combiner.hpp b/src/duckdb/src/include/duckdb/planner/filter/constant_filter_combiner.hpp new file mode 100644 index 000000000..c8131d088 --- /dev/null +++ b/src/duckdb/src/include/duckdb/planner/filter/constant_filter_combiner.hpp @@ -0,0 +1,69 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/planner/filter/constant_filter_combiner.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/enums/expression_type.hpp" +#include "duckdb/common/enums/filter_result.hpp" +#include "duckdb/common/types/value.hpp" +#include "duckdb/common/vector.hpp" + +namespace duckdb { + +enum class ValueComparisonResult { PRUNE_LEFT, PRUNE_RIGHT, UNSATISFIABLE_CONDITION, PRUNE_NOTHING }; + +struct ConstantComparison { + Value constant; + ExpressionType comparison_type; +}; + +//! Reduces constant comparisons on one target, independent of logical or scan-filter representation. +class ConstantFilterCombiner { +public: + static bool IsSupportedComparison(ExpressionType type); + static bool IsLowerBound(ExpressionType type) { + return type == ExpressionType::COMPARE_GREATERTHAN || type == ExpressionType::COMPARE_GREATERTHANOREQUALTO; + } + static bool IsUpperBound(ExpressionType type) { + return type == ExpressionType::COMPARE_LESSTHAN || type == ExpressionType::COMPARE_LESSTHANOREQUALTO; + } + static ValueComparisonResult Compare(const ConstantComparison &left, const ConstantComparison &right); + + static FilterResult AddComparison(vector &comparisons, ConstantComparison comparison) { + return AddComparison(comparisons, std::move(comparison), + [](ConstantComparison &, const ConstantComparison &) {}); + } + + //! MERGE transfers any caller-owned metadata from a removed comparison to its replacement. + template + static FilterResult AddComparison(vector &comparisons, T comparison, MERGE merge) { + if (comparison.constant.IsNull()) { + return FilterResult::UNSATISFIABLE; + } + for (idx_t i = 0; i < comparisons.size(); i++) { + switch (Compare(comparisons[i], comparison)) { + case ValueComparisonResult::PRUNE_LEFT: + merge(comparison, comparisons[i]); + comparisons.erase_at(i--); + break; + case ValueComparisonResult::PRUNE_RIGHT: + merge(comparisons[i], comparison); + return FilterResult::SUCCESS; + case ValueComparisonResult::UNSATISFIABLE_CONDITION: + comparisons.push_back(std::move(comparison)); + return FilterResult::UNSATISFIABLE; + default: + break; + } + } + comparisons.push_back(std::move(comparison)); + return FilterResult::SUCCESS; + } +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp b/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp index 36a755e22..d27cc96a9 100644 --- a/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp +++ b/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp @@ -57,6 +57,11 @@ class ExpressionFilter : public TableFilter { const LogicalType &column_type, SelectivityOptionalFilterType type); static bool IsSimpleFilterColumnRef(const Expression &expr); + //! Whether a literal IN can use the native single-column scan executor. + static bool IsNativeInFilter(const Expression &expr); + //! Whether a native IN is small enough to evaluate using the shared IN-list cutoff. + static bool IsSmallNativeInFilter(const Expression &expr); + static bool SupportsConstantFilterPushdown(const LogicalType &type); //! Flips comparison_type for a constant on the left static optional_ptr TryGetColumnConstantComparison(const BoundFunctionExpression &comparison, ExpressionType &comparison_type); @@ -77,8 +82,12 @@ class ExpressionFilter : public TableFilter { array_ptr input_stats); //! Check if an expression tree contains an internal function with the given name static bool ContainsInternalFunction(const Expression &expr, const string &func_name); + //! Check the full expression tree, including optional bind data, for any internal table-filter function + static bool ContainsInternalTableFilterFunction(const Expression &expr); //! Check if an expression tree is entirely optional filter semantics static bool IsOptionalExpression(const Expression &expr); + //! Whether all conjuncts are pruning-only hints with no row-filtering work. + static bool IsPruningOnlyExpression(const Expression &expr); //! Check if the root of an expression tree is an optional filter wrapper static bool IsRootOptionalExpression(const Expression &expr); //! Child of a root optional filter wrapper diff --git a/src/duckdb/src/include/duckdb/planner/logical_operator.hpp b/src/duckdb/src/include/duckdb/planner/logical_operator.hpp index fbfe46237..feffb99aa 100644 --- a/src/duckdb/src/include/duckdb/planner/logical_operator.hpp +++ b/src/duckdb/src/include/duckdb/planner/logical_operator.hpp @@ -67,7 +67,14 @@ class LogicalOperator { //! Resolve the types of the logical operator and its children void ResolveOperatorTypes(); - + //! Resolve this operator's types using its children's already resolved types. + //! Bottom-up callers must refresh any children they replace before calling this. + void ResolveOperatorTypesFromChildren(); + //! Verify the maintained types against bottom-up resolution, restoring the original type vectors even on failure. + void VerifyOperatorTypes(); + + //! Returns true if this operator itself has side effects. + bool HasLocalSideEffects() const; //! Returns true if this operator or any of its descendants has side effects //! Used to prevent inlining or elimination of side-effecting CTEs. bool HasSideEffects() const; diff --git a/src/duckdb/src/include/duckdb/planner/logical_operator_repeatability.hpp b/src/duckdb/src/include/duckdb/planner/logical_operator_repeatability.hpp index 8d7174ac8..4cbfb8b69 100644 --- a/src/duckdb/src/include/duckdb/planner/logical_operator_repeatability.hpp +++ b/src/duckdb/src/include/duckdb/planner/logical_operator_repeatability.hpp @@ -8,6 +8,9 @@ class LogicalOperator; enum class LogicalOperatorRepeatability : uint8_t { REPEATABLE, NON_REPEATABLE, UNKNOWN }; +//! Classifies this operator's type and expressions, without inspecting its children. +LogicalOperatorRepeatability ClassifyLogicalOperatorLocalRepeatability(LogicalOperator &op); +//! Also rejects operators whose descendants have side effects. LogicalOperatorRepeatability ClassifyLogicalOperatorRepeatability(LogicalOperator &op); bool LogicalSubtreeIsRepeatable(LogicalOperator &op); diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_get.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_get.hpp index 8e9065dc3..28841c8d6 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_get.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_get.hpp @@ -20,6 +20,7 @@ namespace duckdb { class TableCatalogEntry; class DynamicTableFilterSet; +class NodeStatistics; struct LogicalPlanSQLExportField; //! LogicalGet represents a scan operation from a data source @@ -104,6 +105,8 @@ class LogicalGet : public LogicalOperator { idx_t EstimateCardinality(ClientContext &context) override; //! Estimate cardinality from the source without using this operator's cached estimate. idx_t EstimateSourceCardinality(ClientContext &context); + //! Capture the source point and bound with one callback, before consuming bind data. + NodeStatistics EstimateSourceStatistics(ClientContext &context); bool TryGetStorageIndex(const ColumnIndex &column_index, StorageIndex &out_index) const; void SetScanOrder(unique_ptr options); void SetPartitionsToScan(vector partition_indices); diff --git a/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp b/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp index f87512451..8fb10a5ec 100644 --- a/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp +++ b/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/planner/table_filter.hpp" +#include "duckdb/common/enums/filter_result.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/reference_map.hpp" #include "duckdb/common/types.hpp" @@ -20,6 +21,9 @@ class TableFilterSet { public: void PushFilter(ProjectionIndex col_idx, unique_ptr filter); void PushMultiColumnFilter(unique_ptr filter); + //! Normalize a completed batch of already-admitted scan filters, preserving their expression forms. + //! On contradiction, return UNSATISFIABLE without modifying the offending column's filter. + FilterResult Finalize(); bool HasFilters() const; idx_t FilterCount() const; bool HasMultiColumnFilters() const; diff --git a/src/duckdb/src/include/duckdb/storage/block_allocator.hpp b/src/duckdb/src/include/duckdb/storage/block_allocator.hpp index d145548d4..a7d71d02f 100644 --- a/src/duckdb/src/include/duckdb/storage/block_allocator.hpp +++ b/src/duckdb/src/include/duckdb/storage/block_allocator.hpp @@ -144,8 +144,10 @@ class BlockAllocator { idx_t GetCachedPoolMemory() const; void ReturnThreadLocalBlocks() const; void FlushFallbackAllocator(idx_t deallocated) const noexcept; - //! Return bytes released to the fallback allocator, which may still need a purge. - idx_t TrimCachedMemory(idx_t memory_headroom, optional_idx pool_block_limit = optional_idx()) const noexcept + //! Purge the fallback allocator if frees are waiting for it. Idle threads do this without pressure. + void FlushDeallocated() const noexcept; + //! Trim cached backing to the headroom. Bytes released to the fallback allocator join the unflushed estimate. + void TrimCachedMemory(idx_t memory_headroom, optional_idx pool_block_limit = optional_idx()) const noexcept DUCKDB_EXCLUDES(flush_lock); idx_t FlushAllocationCache(idx_t byte_limit, ReclaimMode mode = ReclaimMode::FORCE) const noexcept DUCKDB_EXCLUDES(flush_lock); diff --git a/src/duckdb/src/include/duckdb/storage/data_table.hpp b/src/duckdb/src/include/duckdb/storage/data_table.hpp index cf51f0ef2..b3b32f096 100644 --- a/src/duckdb/src/include/duckdb/storage/data_table.hpp +++ b/src/duckdb/src/include/duckdb/storage/data_table.hpp @@ -29,6 +29,8 @@ class DistinctStatistics; class DuckTransaction; class Expression; class Index; +class BoundIndex; +class IndexEntry; class OptimisticDataWriter; class RowGroup; class RowGroupCollection; @@ -80,8 +82,10 @@ class DataTable : public enable_shared_from_this { DataTable(ClientContext &context, DataTable &parent, idx_t changed_idx, const LogicalType &target_type, const vector &bound_columns, Expression &cast_expr, optional_ptr constraint_to_verify = nullptr); - //! Constructs a DataTable as a delta on an existing data table but with one column added new constraint - DataTable(ClientContext &context, DataTable &parent, BoundConstraint &constraint); + //! Constructs a DataTable as a delta on an existing data table but with one column added new constraint. + //! Throws if the parent has more than max_index_count built indexes. + DataTable(ClientContext &context, DataTable &parent, BoundConstraint &constraint, + optional_idx max_index_count = optional_idx()); //! A reference to the database instance AttachedDatabase &db; @@ -209,9 +213,9 @@ class DataTable : public enable_shared_from_this { //! Merge a row group collection directly into this table - appending it to the end of the table without copying void MergeStorage(RowGroupCollection &data, optional_ptr commit_state); - //! Remove the row identifiers from all the indexes of the table + //! Remove the row identifiers from the indexes of the table added before the bound void RemoveFromIndexes(const QueryContext &context, Vector &row_identifiers, idx_t count, - IndexRemovalType removal_type, optional_idx checkpoint_id = optional_idx()); + IndexRemovalType removal_type, optional_idx checkpoint_id, VisibilityBound bound); void SetAsMainTable() { this->version = DataTableVersion::MAIN_TABLE; @@ -263,8 +267,8 @@ class DataTable : public enable_shared_from_this { bool ScanColumnSegmentInfo(const QueryContext &context, ColumnSegmentInfoScanState &state, vector &result); - //! Scans the next chunk for the CREATE INDEX operator - bool CreateIndexScan(TableScanState &state, DataChunk &result); + //! Scans the next chunk for the CREATE INDEX operator, as of the build commit when building in place + bool CreateIndexScan(TableScanState &state, DataChunk &result, optional_ptr build); //! Initialize constraint verification state unique_ptr InitializeConstraintState(TableCatalogEntry &table, const vector> &bound_constraints); @@ -301,8 +305,14 @@ class DataTable : public enable_shared_from_this { //! It is either empty, or initialized via its index storage information. void AddIndex(const ColumnList &columns, const vector &column_indexes, const IndexConstraintType type, IndexStorageInfo index_info, idx_t index_oid, ConstraintCheckMode check_mode); - //! AddIndex moves an index to this table's index list. + //! AddIndex moves an index to this table's index list, between commits void AddIndex(unique_ptr index, idx_t index_oid); + //! Merges the commits made during an online build into the index, then publishes it between commits + shared_ptr FinishIndexBuild(ClientContext &context, DuckTransaction &transaction, + unique_ptr index, idx_t index_oid, + ConstraintCheckMode check_mode); + //! Adds a building entry for the index, whose deltas receive later commits + shared_ptr AddBuildingIndex(DuckTransaction &transaction, const BoundIndex &index_template); //! Returns a list of the partition stats vector GetPartitionStats(ClientContext &context); @@ -327,6 +337,8 @@ class DataTable : public enable_shared_from_this { //! Rebuild all indexes after vacuuming changed rowid's (used with vacuum_rebuild_indexes setting). void RebuildIndexes(); + //! Takes the commit and append locks; throws if an ALTER replaced the table + unique_lock LockMainTableForIndex(unique_lock &table_lock); void VerifyForeignKeyConstraint(optional_ptr storage, const BoundForeignKeyConstraint &bound_foreign_key, ClientContext &context, @@ -343,7 +355,8 @@ class DataTable : public enable_shared_from_this { shared_ptr info; //! The set of physical columns stored by this DataTable vector column_definitions; - //! Lock for appending entries to the table + //! Lock for appending entries to the table. An ALTER that replaces the table holds it from its index check until + //! it marks the table ALTERED, and indexes are published under it, so no index is added after that check. mutex append_lock; //! The row groups of the table shared_ptr row_groups; diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp index ff2872967..11ee6baeb 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/file_system.hpp" #include "duckdb/common/enums/cache_validation_mode.hpp" #include "duckdb/common/file_open_flags.hpp" #include "duckdb/common/file_opener.hpp" @@ -124,7 +125,7 @@ struct CachingFileHandle { private: QueryContext context; - //! The client file system, held directly because the caching file system can be destroyed before this handle + //! The file system, held directly because the caching file system can be destroyed before this handle FileSystem &file_system; //! The DatabaseInstance DatabaseInstance &db; 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 4fe386f54..4edc8a781 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 @@ -33,6 +33,7 @@ class CachingFileHandleWrapper : public FileHandle { DUCKDB_API ~CachingFileHandleWrapper() override; DUCKDB_API void Close() override; + DUCKDB_API bool CanSeek() override; private: // CachingFileSystem is not kept within VFS as other filesystems, so sometimes it's necessary to pin it inside of @@ -42,25 +43,23 @@ class CachingFileHandleWrapper : public FileHandle { unique_ptr caching_handle; }; -//! [CachingFileSystemWrapper] is an adapter class, which wraps [CachingFileSystem] to conform to FileSystem API. +//! [CachingFileSystemWrapper] is an adapter class, which wraps [CachingFileSystem] to conform to BaseFileSystem API. //! Different from [CachingFileSystem], which owns cache content and returns a [BufferHandle] to achieve zero-copy on //! read, the wrapper class always copies requested bytes into the provided address. //! //! NOTICE: Currently only read and seek operations are supported, write operations are disabled. -class CachingFileSystemWrapper : public FileSystem, public enable_shared_from_this { +class CachingFileSystemWrapper : public BaseFileSystem, public enable_shared_from_this { public: DUCKDB_API CachingFileSystemWrapper(FileSystem &file_system, DatabaseInstance &db, CachingMode mode = CachingMode::CACHE_REMOTE_ONLY); - DUCKDB_API CachingFileSystemWrapper(FileSystem &file_system, optional_ptr file_opener, - CachingMode mode = CachingMode::CACHE_REMOTE_ONLY); DUCKDB_API ~CachingFileSystemWrapper() override; DUCKDB_API std::string GetName() const override; DUCKDB_API unique_ptr OpenFile(const string &path, FileOpenFlags flags, - optional_ptr opener = nullptr) override; + optional_ptr opener) override; DUCKDB_API unique_ptr OpenFile(const OpenFileInfo &path, FileOpenFlags flags, - optional_ptr opener = nullptr); + optional_ptr opener); DUCKDB_API void Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) override; DUCKDB_API void Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) override; @@ -74,34 +73,33 @@ class CachingFileSystemWrapper : public FileSystem, public enable_shared_from_th DUCKDB_API FileType GetFileType(FileHandle &handle) override; DUCKDB_API FileMetadata Stats(FileHandle &handle) override; DUCKDB_API optional GetStatsIfExists(const OpenFileInfo &file, - optional_ptr opener = nullptr) override; + optional_ptr opener) override; DUCKDB_API void Truncate(FileHandle &handle, int64_t new_size) override; DUCKDB_API void FileSync(FileHandle &handle) override; - DUCKDB_API bool DirectoryExists(const string &directory, optional_ptr opener = nullptr) override; - DUCKDB_API void CreateDirectory(const string &directory, optional_ptr opener = nullptr) override; + DUCKDB_API bool DirectoryExists(const string &directory, optional_ptr opener) override; + DUCKDB_API void CreateDirectory(const string &directory, optional_ptr opener) override; DUCKDB_API bool CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener = nullptr) override; - DUCKDB_API void CreateDirectoriesRecursive(const string &path, optional_ptr opener = nullptr) override; - DUCKDB_API void RemoveDirectory(const string &directory, optional_ptr opener = nullptr) override; + optional_ptr opener) override; + DUCKDB_API void CreateDirectoriesRecursive(const string &path, optional_ptr opener) override; + DUCKDB_API void RemoveDirectory(const string &directory, optional_ptr opener) override; DUCKDB_API bool RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener = nullptr) override; + optional_ptr opener) override; DUCKDB_API bool ListFiles(const string &directory, const std::function &callback, - FileOpener *opener = nullptr) override; + FileOpener *opener) override; - DUCKDB_API void MoveFile(const string &source, const string &target, - optional_ptr opener = nullptr) override; - DUCKDB_API bool FileExists(const string &filename, optional_ptr opener = nullptr) override; - DUCKDB_API bool IsPipe(const string &filename, optional_ptr opener = nullptr) override; - DUCKDB_API void RemoveFile(const string &filename, optional_ptr opener = nullptr) override; - DUCKDB_API bool TryRemoveFile(const string &filename, optional_ptr opener = nullptr) override; + DUCKDB_API void MoveFile(const string &source, const string &target, optional_ptr opener) override; + DUCKDB_API bool FileExists(const string &filename, optional_ptr opener) override; + DUCKDB_API bool IsPipe(const string &filename, optional_ptr opener) override; + DUCKDB_API void RemoveFile(const string &filename, optional_ptr opener) override; + DUCKDB_API bool TryRemoveFile(const string &filename, optional_ptr opener) override; DUCKDB_API string GetHomeDirectory() override; DUCKDB_API string ExpandPath(const string &path) override; DUCKDB_API string PathSeparator(const string &path) override; - DUCKDB_API vector Glob(const string &path, FileOpener *opener = nullptr) override; + DUCKDB_API vector Glob(const string &path, FileOpener *opener) override; DUCKDB_API bool CanHandleFile(const string &fpath) override; @@ -110,7 +108,6 @@ class CachingFileSystemWrapper : public FileSystem, public enable_shared_from_th DUCKDB_API idx_t SeekPosition(FileHandle &handle) override; DUCKDB_API bool IsManuallySet() override; - DUCKDB_API bool CanSeek() override; DUCKDB_API bool OnDiskFile(FileHandle &handle) override; DUCKDB_API unique_ptr OpenCompressedFile(QueryContext context, unique_ptr handle, @@ -130,8 +127,9 @@ class CachingFileSystemWrapper : public FileSystem, public enable_shared_from_th // Return an optional caching file handle, if certain filepath is cached. CachingFileHandle *GetCachingHandleIfPossible(FileHandle &handle); - CachingFileSystem caching_file_system; + //! The bound file system the files are opened with; it pushes its own opener FileSystem &underlying_file_system; + CachingFileSystem caching_file_system; CachingMode caching_mode; }; diff --git a/src/duckdb/src/include/duckdb/storage/index.hpp b/src/duckdb/src/include/duckdb/storage/index.hpp index c03e2a581..e8fcc560a 100644 --- a/src/duckdb/src/include/duckdb/storage/index.hpp +++ b/src/duckdb/src/include/duckdb/storage/index.hpp @@ -29,7 +29,7 @@ struct IndexCheckpointResult; //! IMMEDIATE (default): flush buffers under the index lock. //! DEFERRED: share blocks across indexes and finish flushing after releasing the lock. Return a logically equivalent //! shadow with independent backing for modified buffers; keep the live index usable until installation after flushing. -//! Concurrent changes use deltas, requiring SupportsDeltaIndexes(), CreateEmptyCopy(), and MergeCheckpointDelta(). +//! Concurrent changes use deltas, requiring SupportsDeltaIndexes(), CreateEmptyCopy(), and MergeDelta(). enum class IndexCheckpointMode : uint8_t { IMMEDIATE, DEFERRED }; //! The index is an abstract base class that serves as the basis for indexes diff --git a/src/duckdb/src/include/duckdb/storage/table/column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/column_data.hpp index 2b770f8c9..a95444b7a 100644 --- a/src/duckdb/src/include/duckdb/storage/table/column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/column_data.hpp @@ -286,10 +286,16 @@ class ColumnData : public enable_shared_from_this { protected: //! The segments holding the data of this column segment ColumnSegmentTree data; + +private: //! The lock for the updates mutable mutex update_lock; - //! The updates for this column segment + //! Created only by UpdateInternal; never reset during this column's lifetime. unique_ptr updates; + //! False permits skipping update_lock. Set before construction, even if construction throws; never cleared. + atomic updates_may_exist {false}; + +protected: //! The lock for the stats mutable mutex stats_lock; //! Total transient allocation size diff --git a/src/duckdb/src/include/duckdb/storage/table/index_entry.hpp b/src/duckdb/src/include/duckdb/storage/table/index_entry.hpp index ca481ca90..8a6d3b257 100644 --- a/src/duckdb/src/include/duckdb/storage/table/index_entry.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/index_entry.hpp @@ -37,7 +37,7 @@ using IndexRebuildScan = std::function &column_ids, using IndexRemapApply = std::function; using IndexRemapScan = std::function; -//! Owns the optional indexes used to represent transaction and checkpoint deltas for an IndexEntry. +//! Owns the optional indexes used to represent transaction, checkpoint and build deltas for an IndexEntry. class IndexDeltas { public: optional_ptr Find(IndexDeltaType type) const; @@ -46,6 +46,8 @@ class IndexDeltas { bool ShouldUse(optional_idx active_checkpoint) const; ErrorData MergeCheckpointDeltas(BoundIndex &index); void MarkWritten(optional_idx checkpoint_id); + //! Removes the delta of the given type and returns it + unique_ptr Take(IndexDeltaType type); void Reset(); private: @@ -110,17 +112,27 @@ class IndexWriteHandle { unique_ptr lock; }; +//! The deltas taken from a building index entry, merged outside the commit lock +struct IndexBuildDeltas { + unique_ptr added; + unique_ptr removed; + //! The number of appended and removed rows + idx_t changed_rows = 0; +}; + //! IndexEntry contains an atomic in addition to the index to ensure correct binding. //! The IndexEntry provides a stable logical identity which refers to an interchangeable snapshot of an index. class IndexEntry : public enable_shared_from_this { public: IndexEntry(unique_ptr index, idx_t index_oid, ConstraintCheckMode check_mode); + //! Creates the entry of an index that is being built, from an empty copy of the template + IndexEntry(const BoundIndex &index_template, transaction_t build_commit, transaction_t build_transaction); //! Append a chunk to the physical index, buffering it while the index is unbound. void Append(DataChunk &chunk, Vector &row_ids); - //! Appends a chunk using delete and checkpoint indexes where required. + //! Appends a chunk using delete indexes and deltas where required. ErrorData Append(DataChunk &chunk, Vector &row_ids, const shared_ptr &delete_entry, IndexAppendMode append_mode, optional_idx active_checkpoint); - //! Reverts an append to the physical index or its checkpoint delta. + //! Reverts an append to the physical index or its delta. void RevertAppend(DataChunk &chunk, Vector &row_ids); //! Appends deleted rows to the bound physical index if it enforces uniqueness. void AppendToDeleteIndexes(DataChunk &chunk, Vector &row_ids); @@ -179,6 +191,12 @@ class IndexEntry : public enable_shared_from_this { void MergeCheckpointDeltas(optional_idx checkpoint_id); //! Adds the required transaction-local delete and append indexes. void InitializeLocalIndexes(TableIndexList &delete_indexes, TableIndexList &append_indexes) const; + //! Takes the deltas of a building entry; later commits create new ones + IndexBuildDeltas TakeBuildDeltas(); + //! Merges taken deltas into the built index, checking its constraint + static void MergeBuildDeltas(BoundIndex &index, const IndexBuildDeltas &deltas); + //! Installs the built index, making it visible to readers + void FinishBuild(unique_ptr index, idx_t index_oid, ConstraintCheckMode check_mode); //! Adds only the transaction-local delete index. void InitializeLocalDeleteIndex(TableIndexList &delete_indexes) const; @@ -202,6 +220,25 @@ class IndexEntry : public enable_shared_from_this { idx_t GetIndexOid() const { return index_oid; } + bool IsBuilding() const { + return building; + } + //! Whether changes go to the deltas instead of the index: during a checkpoint or a build + bool UseDeltas(optional_idx active_checkpoint) const { + return building || deltas.ShouldUse(active_checkpoint); + } + //! The transaction building the index + transaction_t GetBuildTransaction() const { + return build_transaction; + } + //! The last commit before the index was added to the index list + transaction_t GetLastCommit() const { + return last_commit; + } + //! Whether the index was added before the bound: every delete the build skipped precedes it + bool AddedBefore(VisibilityBound bound) const { + return last_commit < bound; + } private: template @@ -211,20 +248,32 @@ class IndexEntry : public enable_shared_from_this { void InitializeLocalIndexesInternal(TableIndexList &delete_indexes, optional_ptr append_indexes) const; + //! Records an error of a building entry, rethrowing errors that invalidate the database + void RecordBuildError(std::exception &ex); //! Replace the physical index, this assumes an exclusive lock on the index is being held. void InstallShadowInternal(unique_ptr shadow_index); private: atomic bind_state; - //! The OID of this index. - const idx_t index_oid; + //! The OID of this index (set when a build finishes) + atomic index_oid; + //! The commit an online build scanned through (0 if not built online) + const transaction_t last_commit; //! Phase-fair lock protecting the physical index and all delta indexes owned by this entry. mutable StorageLock lock; //! The physical index owned by this stable logical entry. unique_ptr owned_index; //! Whether the enforced constraint is deferred. Derived from the catalog constraint, not serialized. - const ConstraintCheckMode check_mode; + atomic check_mode; IndexDeltas deltas; + //! Whether the index is being built: commits write to its deltas and readers skip it + atomic building; + //! The transaction building the index (0 if not built in place) + const transaction_t build_transaction; + //! The rows appended or removed since the last TakeBuildDeltas() + idx_t build_changed_rows = 0; + //! The first error a commit hit while writing the deltas of a building entry: fails the build, not the commit + ErrorData build_error; }; template diff --git a/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp b/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp index 5f7be108f..eb48fba80 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp @@ -159,8 +159,10 @@ class RowGroupCollection { optional_ptr commit_state); bool IsPersistent() const; + //! Removes the rows from the indexes added before the bound. void RemoveFromIndexes(const QueryContext &context, TableIndexList &indexes, Vector &row_identifiers, idx_t count, - IndexRemovalType removal_type, optional_idx active_checkpoint = optional_idx()); + IndexRemovalType removal_type, optional_idx active_checkpoint = optional_idx(), + VisibilityBound bound = VisibilityBound::IncludingUncommitted()); //! Delete the given rows - optionally collects the ids of the rows that were deleted (excluding duplicates) idx_t Delete(TransactionData transaction, DuckTableEntry &table_entry, row_t *ids, idx_t count, @@ -256,6 +258,11 @@ class RowGroupCollection { } private: + optional_idx NextParallelScanAtomic(ClientContext &context, ParallelCollectionScanState &state, + CollectionScanState &scan_state, bool initialize_columns); + optional_idx NextParallelScanLocked(ClientContext &context, ParallelCollectionScanState &state, + CollectionScanState &scan_state, bool initialize_columns); + optional_ptr> NextUpdateRowGroup(RowGroupSegmentTree &row_groups, row_t *ids, idx_t &pos, idx_t count) const; 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 7ad2bdc6d..2322fe957 100644 --- a/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp @@ -442,6 +442,9 @@ class TableScanState { vector column_ids; }; +//! How workers claim assignments from a collection. +enum class ParallelScanClaimMode { LOCKED, ATOMIC }; + struct ParallelCollectionScanState { ParallelCollectionScanState(); void AssignRowGroup(optional_ptr> row_group); @@ -460,6 +463,12 @@ struct ParallelCollectionScanState { atomic skipped_rows; optional_idx row_number_base; mutex lock; + //! Fixed during initialization; ordered, partitioned and row-number scans require LOCKED. + ParallelScanClaimMode claim_mode = ParallelScanClaimMode::LOCKED; + //! Each atomic ticket owns one entry of claim_nodes. + PaddedAtomic claim_index {0}; + //! Immutable after initialization; row_groups keeps the referenced nodes alive. + vector>> claim_nodes; //! Optional state for custom row group ordering unique_ptr reorderer; diff --git a/src/duckdb/src/include/duckdb/storage/table/table_index_list.hpp b/src/duckdb/src/include/duckdb/storage/table/table_index_list.hpp index d42458803..11e2a7987 100644 --- a/src/duckdb/src/include/duckdb/storage/table/table_index_list.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/table_index_list.hpp @@ -41,8 +41,19 @@ class TableIndexList { //! Iterates over shared ownership of stable index entries while holding the entry-list lock. TableIndexIterationHelper> IndexEntries() const; + //! Same as IndexEntries(), skipping the entries of indexes that are being built. + TableIndexIterationHelper> BuiltIndexEntries() const; //! Adds an index entry to the list of index entries, and returns it. shared_ptr AddIndex(unique_ptr index, idx_t index_oid, ConstraintCheckMode check_mode); + //! Adds the entry of an index being built (requires the commit lock) + shared_ptr AddBuildingIndex(const BoundIndex &index_template, transaction_t build_commit, + transaction_t build_transaction); + //! Returns the entry being built by the transaction, if any + shared_ptr FindBuildingIndex(transaction_t build_transaction) const; + //! Removes the entry if it is still being built + void RemoveBuildingIndex(const IndexEntry &entry); + //! Returns the number of indexes that are not being built + idx_t CountBuiltIndexes() const; //! Initializes the transaction-local delete and append indexes. void InitializeLocalIndexes(TableIndexList &delete_indexes, TableIndexList &append_indexes) const; //! Appends a chunk to all index entries. @@ -56,9 +67,10 @@ class TableIndexList { void RevertAppend(DataChunk &chunk, row_t row_start); //! Appends deleted rows to all unique indexes. void AppendToDeleteIndexes(DataChunk &chunk, Vector &row_ids); - //! Applies a removal or removal rollback to all index entries. + //! Applies a removal or removal rollback to the index entries added before the bound. void RemoveFromIndexes(DataChunk &chunk, Vector &row_ids, IndexRemovalType removal_type, - optional_idx active_checkpoint = optional_idx()); + optional_idx active_checkpoint = optional_idx(), + VisibilityBound bound = VisibilityBound::IncludingUncommitted()); //! Removes an index entry from the list of index entries and release any storage the index owns. void RemoveIndex(idx_t index_oid); //! Returns the entry matching the index OID. @@ -126,8 +138,8 @@ class TableIndexList { DataChunk &chunk, ConflictManager &conflict_manager); //! Persist index buffers and install replacements before returning their metadata. vector> Checkpoint(TableIndexWriter &writer); - //! Returns the physical table columns referenced by any index. - unordered_set GetIndexedColumns() const; + //! Returns the physical table columns of the indexes added before the bound (by default all). + unordered_set GetIndexedColumns(VisibilityBound bound = VisibilityBound::IncludingUncommitted()) const; //! Returns the column sets of unique indexes matching the conflict target. vector> GetConflictTargetColumns(const ConflictInfo &conflict_info) const; //! Get the combined column ids of the unique indexes. @@ -158,32 +170,38 @@ class TableIndexList { template class TableIndexIterationHelper { public: - explicit TableIndexIterationHelper(const TableIndexList &index_list); + TableIndexIterationHelper(const TableIndexList &index_list, bool skip_building_p); private: annotated_unique_lock lock; const vector> &index_entries; + bool skip_building; private: class TableIndexIterator { public: - explicit TableIndexIterator(optional_ptr>> index_entries); + TableIndexIterator(optional_ptr>> index_entries, bool skip_building_p); optional_ptr>> index_entries; optional_idx index; + bool skip_building; public: TableIndexIterator &operator++(); bool operator!=(const TableIndexIterator &other) const; T operator*() const; + + private: + void Advance(); + void SkipBuilding(); }; public: TableIndexIterator begin() { // NOLINT: match stl API - return TableIndexIterator(&index_entries); + return TableIndexIterator(&index_entries, skip_building); } TableIndexIterator end() { // NOLINT: match stl API - return TableIndexIterator(nullptr); + return TableIndexIterator(nullptr, skip_building); } }; diff --git a/src/duckdb/src/include/duckdb/transaction/commit_state.hpp b/src/duckdb/src/include/duckdb/transaction/commit_state.hpp index 4d394df9b..3f1ff1d5c 100644 --- a/src/duckdb/src/include/duckdb/transaction/commit_state.hpp +++ b/src/duckdb/src/include/duckdb/transaction/commit_state.hpp @@ -75,7 +75,8 @@ struct IndexDataRemover { public: explicit IndexDataRemover(DuckTransaction &transaction, QueryContext context, IndexRemovalType removal_type); - void PushDelete(DeleteInfo &info); + //! Removes the deleted rows from the indexes; returns true if they stay in deleted_rows_in_use + bool PushDelete(DeleteInfo &info); void Verify(); private: @@ -106,7 +107,8 @@ class CommitState { private: void CommitEntryDrop(CatalogEntry &entry, data_ptr_t extra_data, CommitInfo &info); - void CommitDelete(DeleteInfo &info, transaction_t old_id); + //! Returns true if the deleted rows stay in deleted_rows_in_use until cleanup + bool CommitDelete(DeleteInfo &info, transaction_t old_id); private: DuckTransaction &transaction; diff --git a/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp b/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp index e1f556a16..ba0044e1f 100644 --- a/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp +++ b/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp @@ -32,6 +32,8 @@ struct CommitInfo { optional_ptr drop_state; //! WAL offset covering the commit's flush marker (0 if no WAL was written) idx_t wal_sync_offset = 0; + //! Whether the commit left deleted rows in deleted_rows_in_use for cleanup + bool has_index_deletes = false; }; class DuckTransaction : public Transaction { diff --git a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp index 79945fd50..234b5fc7a 100644 --- a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp +++ b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp @@ -11,6 +11,7 @@ #include "duckdb/storage/table/table_index_list.hpp" #include "duckdb/storage/optimistic_data_writer.hpp" #include "duckdb/storage/storage_lock.hpp" +#include "duckdb/common/atomic.hpp" #include "duckdb/common/error_data.hpp" #include "duckdb/common/query_context.hpp" #include "duckdb/common/reference_map.hpp" @@ -69,8 +70,9 @@ class LocalTableStorage : public enable_shared_from_this { reference table_ref; //! The DuckTableEntry visible to this transaction that references table_ref. //! Updated through the append path (InitializeAppend, Append, LocalMerge) and - //! propagated from parent storage on ALTER operations. - optional_ptr table_entry; + //! propagated from parent storage on ALTER operations. Atomic: connections that share a transaction set it + //! concurrently. + atomic> table_entry; Allocator &allocator; //! The main row group collection. @@ -87,6 +89,8 @@ class LocalTableStorage : public enable_shared_from_this { //! Whether or not the storage was dropped atomic is_dropped {false}; + //! Whether an ALTER of a connection sharing the transaction replaced the storage by the one of the new table + atomic replaced_by_alter {false}; //! Serializes the appends and merges into the primary collection StorageLock append_lock; @@ -94,6 +98,9 @@ class LocalTableStorage : public enable_shared_from_this { StorageLock flush_lock; public: + //! Locks to use the primary collection (throw if the table was altered in the meantime) + unique_ptr LockShared(); + unique_ptr LockAppend(); //! Initialize a scan; the context of the scanning query is used for pushed down casts and zonemap checks void InitializeScan(const QueryContext &context, CollectionScanState &state, optional_ptr table_filters = nullptr); @@ -128,6 +135,8 @@ class LocalTableStorage : public enable_shared_from_this { OptimisticWriteCollection &GetOptimisticCollection(const PhysicalIndex collection_index); //! Resets the optimistic row group collection corresponding to the index. void ResetOptimisticCollection(const PhysicalIndex collection_index); + //! Whether a statement is writing an optimistic row group collection of the table + bool HasOptimisticCollections(); //! Returns the optimistic writer. OptimisticDataWriter &GetOptimisticWriter(); @@ -149,6 +158,8 @@ class LocalTableStorage : public enable_shared_from_this { class LocalTableManager { public: shared_ptr MoveEntry(DataTable &table); + //! Replaces the storage of a table by the storage of its altered version + void ReplaceEntry(DataTable &old_table, DataTable &new_table, shared_ptr entry); reference_map_t> MoveEntries(); vector> GetEntries() const; shared_ptr GetStorage(const DataTable &table) const; @@ -160,6 +171,8 @@ class LocalTableManager { private: mutable mutex table_storage_lock; reference_map_t> table_storage; + //! The old versions of the tables whose storage was replaced by an ALTER + reference_set_t altered_tables; }; //! The LocalStorage class holds appends that have not been committed yet @@ -259,11 +272,21 @@ class LocalStorage { } private: + //! The locks that are held while the storage of an altered table is replaced + struct LocalStorageAlterLocks { + unique_ptr append_key; + unique_ptr flush_key; + }; + DuckTransaction &transaction; LocalTableManager table_manager; bool synced_flushed_blocks = false; private: + //! Takes the locks of the storage of the table that an ALTER replaces. Throws if other statements use it + shared_ptr BeginAlter(DataTable &old_dt, LocalStorageAlterLocks &locks); + //! Replaces the storage of the old version of the table by the one of the new version + void FinishAlter(DataTable &old_dt, DataTable &new_dt, shared_ptr new_storage); //! Flushes the local rows into the shared table and indexes; invalidates the database if they cannot be restored void Flush(Context &context, DataTable &table, LocalTableStorage &storage, optional_ptr commit_state); diff --git a/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp b/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp index 62a86fd48..326dcbcda 100644 --- a/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp +++ b/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp @@ -16,6 +16,8 @@ #include "duckdb/common/error_data.hpp" #include "duckdb/common/case_insensitive_map.hpp" #include "duckdb/main/attached_database.hpp" +#include "duckdb/common/mutex.hpp" +#include "duckdb/common/atomic.hpp" namespace duckdb { class AttachedDatabase; @@ -40,7 +42,8 @@ struct TransactionReference { //! The MetaTransaction manages multiple transactions for different attached databases class MetaTransaction { public: - DUCKDB_API MetaTransaction(DatabaseInstance &db, timestamp_t start_timestamp, transaction_t global_transaction_id); + DUCKDB_API MetaTransaction(DatabaseInstance &db, shared_ptr temporary_objects, + timestamp_t start_timestamp, transaction_t global_transaction_id); DUCKDB_API ~MetaTransaction(); //! The timestamp when the transaction started @@ -52,6 +55,44 @@ class MetaTransaction { public: DUCKDB_API static MetaTransaction &Get(ClientContext &context); + //! The temporary objects (temp catalog) the transaction operates on: those of the connection that created it + AttachedDatabase &GetTemporaryObjects() const { + return *temporary_objects; + } + const shared_ptr &GetTemporaryObjectsPtr() const { + return temporary_objects; + } + + //! Makes the transaction joinable by other connections, returns its identifier + string ShareTransaction(); + //! The identifier under which the transaction was shared (empty if not shared) + string GetShareId(); + //! Whether the transaction was shared with other connections, or inherited by one + bool IsShared() { + lock_guard guard(shared_lock); + return !share_id.empty() || inherited; + } + //! Adds a participant to the shared transaction. Returns false if the transaction already ended. + //! An inheriting participant cannot keep the transaction alive on its own (see Leave). + bool Join(bool inherited = false); + struct LeaveResult { + //! Whether the participant that left was the last one - it then has to commit or roll back + bool last; + //! Whether all participants that left voted to commit + bool commit; + //! Whether only inheriting participants remain: the transaction can no longer commit + bool orphaned; + }; + //! A participant leaves the transaction, voting for a commit or rollback. When the last participant that did not + //! inherit the transaction leaves while inheriting ones remain, the transaction is rolled back. + LeaveResult Leave(bool commit, bool inherited = false); + //! Whether the transaction was committed or rolled back + bool IsFinished() const { + return finished; + } + void MarkFinished() { + finished = true; + } timestamp_t GetCurrentTransactionStartTimestamp() const { return start_timestamp; } @@ -102,6 +143,22 @@ class MetaTransaction { reference_map_t> referenced_databases; //! Map of name -> database for databases that are in-use by this transaction. identifier_map_t> used_databases; + //! The temporary objects of the connection that created the transaction + shared_ptr temporary_objects; + //! Whether the transaction ended (committed or rolled back) + atomic finished; + //! Guards the participant state below + mutex shared_lock; + //! The number of connections participating in the transaction, starting with the one that created it + idx_t participants = 1; + //! The number of participants that inherited the transaction (included in participants) + idx_t inherited_participants = 0; + //! Whether a connection ever inherited the transaction + bool inherited = false; + //! Whether a participant voted to roll back + bool rollback_vote = false; + //! The identifier the transaction was exported under + string share_id; //! Secrets that only live for the duration of this transaction. unique_ptr transaction_secret_storage; }; diff --git a/src/duckdb/src/include/duckdb/transaction/transaction_context.hpp b/src/duckdb/src/include/duckdb/transaction/transaction_context.hpp index b9db70df7..8df5a1e32 100644 --- a/src/duckdb/src/include/duckdb/transaction/transaction_context.hpp +++ b/src/duckdb/src/include/duckdb/transaction/transaction_context.hpp @@ -13,6 +13,7 @@ #include "duckdb/common/common.hpp" #include "duckdb/common/error_data.hpp" #include "duckdb/common/exception.hpp" +#include "duckdb/common/mutex.hpp" #include "duckdb/common/optional_ptr.hpp" #include "duckdb/parser/parsed_data/transaction_info.hpp" @@ -31,7 +32,7 @@ class TransactionContext { ~TransactionContext(); MetaTransaction &ActiveTransaction() { - if (!current_transaction) { + if (!HasActiveTransaction()) { throw InternalException("TransactionContext::ActiveTransaction called without active transaction"); } return *current_transaction; @@ -54,6 +55,23 @@ class TransactionContext { void SetReadOnly(); + //! Makes the current transaction joinable by other connections, returns its identifier + string ShareTransaction(); + //! Joins the shared transaction with the given identifier (only outside of a transaction) + void JoinTransaction(const string &share_id); + //! The current transaction if it was shared under the given identifier, otherwise null. + //! Safe to call from other connections. + shared_ptr GetSharedTransaction(const string &share_id); + //! Whether the current transaction is shared with other connections. Safe to call from other threads. + bool IsInSharedTransaction(); + //! Continues in the transaction active on `source` (only outside of a transaction). The connection then cannot + //! end the transaction: it stays in it until it is closed, and the transaction cannot commit while it is open. + void InheritTransaction(ClientContext &source); + //! Whether the connection inherited its transaction (see InheritTransaction) + bool IsInherited() const { + return inherited; + } + idx_t GetActiveQuery(); void ResetActiveQuery(); void SetActiveQuery(transaction_t query_number); @@ -74,12 +92,24 @@ class TransactionContext { bool auto_commit; TransactionInvalidationPolicy invalidation_policy = TransactionInvalidationPolicy::STANDARD_POLICY; bool auto_rollback = false; + //! Whether the current transaction was inherited from another connection + bool inherited = false; - unique_ptr current_transaction; + //! Guards replacing current_transaction against reads from other connections (GetSharedTransaction) + mutex current_transaction_lock; + shared_ptr current_transaction; //! The query number of the query currently running on this connection (MAXIMUM_QUERY_ID if none) atomic active_query_id = MAXIMUM_QUERY_ID; ErrorData autocheckpoint_error; + void SetCurrentTransaction(shared_ptr transaction); + shared_ptr TakeCurrentTransaction(); + shared_ptr GetCurrentTransaction(); + void RollbackTransaction(const shared_ptr &transaction, optional_ptr error); + //! Joins `transaction` and continues in it, discarding the current transaction (if any) + void EnterTransaction(shared_ptr transaction, bool inherit, const string ¬_active_error, + const string &aborted_error); + TransactionContext(const TransactionContext &) = delete; }; diff --git a/src/duckdb/src/include/duckdb/transaction/undo_buffer.hpp b/src/duckdb/src/include/duckdb/transaction/undo_buffer.hpp index 195024bd0..beb6b0397 100644 --- a/src/duckdb/src/include/duckdb/transaction/undo_buffer.hpp +++ b/src/duckdb/src/include/duckdb/transaction/undo_buffer.hpp @@ -28,7 +28,6 @@ struct UndoBufferProperties { idx_t estimated_size = 0; bool has_updates = false; bool has_deletes = false; - bool has_index_deletes = false; bool has_catalog_changes = false; bool has_dropped_entries = false; }; diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 012074a33..a39052d96 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -650,6 +650,40 @@ typedef struct { DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_register_table_function) (duckdb_v2_connection_handle conn, duckdb_v2_table_function_handle function, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_bind_data) + (duckdb_v2_data_source_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_global_state) + (duckdb_v2_data_source_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_local_state) + (duckdb_v2_data_source_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_output_chunk) + (duckdb_v2_data_source_exec_info_handle info, duckdb_v2_data_chunk_handle *chunk, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_user_data) + (duckdb_v2_data_source_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_get_bind_data) + (duckdb_v2_data_source_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_get_user_data) + (duckdb_v2_data_source_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_set_global_state) + (duckdb_v2_data_source_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_set_max_threads) + (duckdb_v2_data_source_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_get_bind_data) + (duckdb_v2_data_source_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_get_global_state) + (duckdb_v2_data_source_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_get_user_data) + (duckdb_v2_data_source_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_set_local_state) + (duckdb_v2_data_source_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_progress_get_bind_data) + (duckdb_v2_data_source_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_progress_get_global_state) + (duckdb_v2_data_source_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_progress_get_user_data) + (duckdb_v2_data_source_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_progress_set_progress) + (duckdb_v2_data_source_progress_info_handle info, double progress, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_table_function) (duckdb_v2_extension_handle extension, duckdb_v2_table_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_add_result_column) @@ -661,61 +695,14 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_table_function_create) (duckdb_v2_factory_handle factory, duckdb_v2_table_function_handle *function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_table_function_destroy)(duckdb_v2_table_function_handle *function); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_bind_data) - (duckdb_v2_table_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_global_state) - (duckdb_v2_table_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_local_state) - (duckdb_v2_table_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_output_chunk) - (duckdb_v2_table_function_exec_info_handle info, duckdb_v2_data_chunk_handle *chunk, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_user_data) - (duckdb_v2_table_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_get_signature) (duckdb_v2_table_function_handle function, duckdb_v2_function_signature_handle *sig, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_get_bind_data) - (duckdb_v2_table_function_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_get_user_data) - (duckdb_v2_table_function_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_set_global_state) - (duckdb_v2_table_function_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_set_max_threads) - (duckdb_v2_table_function_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_get_bind_data) - (duckdb_v2_table_function_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_get_global_state) - (duckdb_v2_table_function_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_get_user_data) - (duckdb_v2_table_function_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_set_local_state) - (duckdb_v2_table_function_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_progress_get_bind_data) - (duckdb_v2_table_function_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_progress_get_global_state) - (duckdb_v2_table_function_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_progress_get_user_data) - (duckdb_v2_table_function_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_progress_set_progress) - (duckdb_v2_table_function_progress_info_handle info, double progress, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_bind_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_bind_callback_fn callback, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_exec_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_init_global_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_init_global_callback_fn callback, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_init_local_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_init_local_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_name) (duckdb_v2_table_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_progress_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_progress_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_user_data) (duckdb_v2_table_function_handle function, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_cast_function_create) @@ -908,55 +895,9 @@ typedef struct { (duckdb_v2_copy_from_bind_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_bind_set_cardinality) (duckdb_v2_copy_from_bind_info_handle info, idx_t cardinality, bool is_exact, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_exec_get_bind_data) - (duckdb_v2_copy_from_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_exec_get_global_state) - (duckdb_v2_copy_from_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_exec_get_local_state) - (duckdb_v2_copy_from_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_exec_get_output_chunk) - (duckdb_v2_copy_from_exec_info_handle info, duckdb_v2_data_chunk_handle *chunk, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_exec_get_user_data) - (duckdb_v2_copy_from_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_global_get_bind_data) - (duckdb_v2_copy_from_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_global_get_user_data) - (duckdb_v2_copy_from_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_global_set_global_state) - (duckdb_v2_copy_from_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_global_set_max_threads) - (duckdb_v2_copy_from_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_local_get_bind_data) - (duckdb_v2_copy_from_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_local_get_global_state) - (duckdb_v2_copy_from_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_local_get_user_data) - (duckdb_v2_copy_from_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_init_local_set_local_state) - (duckdb_v2_copy_from_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_progress_get_bind_data) - (duckdb_v2_copy_from_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_progress_get_global_state) - (duckdb_v2_copy_from_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_progress_get_user_data) - (duckdb_v2_copy_from_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_progress_set_progress) - (duckdb_v2_copy_from_progress_info_handle info, double progress, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_bind_callback) (duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_bind_callback_fn callback, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_exec_callback) - (duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_init_global_callback) - (duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_init_global_callback_fn callback, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_init_local_callback) - (duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_init_local_callback_fn callback, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_progress_callback) - (duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_progress_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_function_create) (duckdb_v2_factory_handle factory, duckdb_v2_copy_function_handle *function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_copy_function_destroy)(duckdb_v2_copy_function_handle *function); @@ -1043,6 +984,20 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_copy_to_set_init_callback) (duckdb_v2_copy_function_handle function, duckdb_v2_copy_to_init_callback_fn callback, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_column_count) + (duckdb_v2_data_source_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_get_column_index) + (duckdb_v2_data_source_exec_info_handle info, idx_t index, idx_t *column_index, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_get_column_count) + (duckdb_v2_data_source_init_global_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_global_get_column_index) + (duckdb_v2_data_source_init_global_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_get_column_count) + (duckdb_v2_data_source_init_local_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_init_local_get_column_index) + (duckdb_v2_data_source_init_local_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_cast_get_mode) (duckdb_v2_expression_handle expression, DUCKDB_V2_CAST_MODE *mode, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_column_ref_get_index) @@ -1087,11 +1042,6 @@ typedef struct { (duckdb_v2_table_description_handle desc, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_description_is_readonly) (duckdb_v2_table_description_handle desc, bool *readonly, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_column_count) - (duckdb_v2_table_function_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_exec_get_column_index) - (duckdb_v2_table_function_exec_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_filter_pushdown_accept) (duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_filter_pushdown_get_bind_data) @@ -1108,16 +1058,6 @@ typedef struct { (duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_filter_pushdown_get_user_data) (duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_get_column_count) - (duckdb_v2_table_function_init_global_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_global_get_column_index) - (duckdb_v2_table_function_init_global_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_get_column_count) - (duckdb_v2_table_function_init_local_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_init_local_get_column_index) - (duckdb_v2_table_function_init_local_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_filter_pushdown_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_filter_pushdown_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -1149,30 +1089,30 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_attach_options_set) (duckdb_v2_attach_options_handle options, const char *key, idx_t key_length, const char *setting, idx_t setting_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_bind_data) + (duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_global_state) + (duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_local_state) + (duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_partition_column_count) + (duckdb_v2_data_source_partition_data_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_partition_column_index) + (duckdb_v2_data_source_partition_data_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_get_user_data) + (duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_requires_batch_index) + (duckdb_v2_data_source_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_requires_partition_columns) + (duckdb_v2_data_source_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_set_batch_index) + (duckdb_v2_data_source_partition_data_info_handle info, idx_t batch_index, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_partition_data_set_partition_value) + (duckdb_v2_data_source_partition_data_info_handle info, idx_t index, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_set_default) (duckdb_v2_instance_handle instance, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_bind_data) - (duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_global_state) - (duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_local_state) - (duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_partition_column_count) - (duckdb_v2_table_function_partition_data_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_partition_column_index) - (duckdb_v2_table_function_partition_data_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_get_user_data) - (duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_requires_batch_index) - (duckdb_v2_table_function_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_requires_partition_columns) - (duckdb_v2_table_function_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_set_batch_index) - (duckdb_v2_table_function_partition_data_info_handle info, idx_t batch_index, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_partition_data_set_partition_value) - (duckdb_v2_table_function_partition_data_info_handle info, idx_t index, duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_partitioning_get_bind_data) (duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_partitioning_get_partition_column_count) @@ -1185,9 +1125,6 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_table_function_partitioning_set_partition_info) (duckdb_v2_table_function_partitioning_info_handle info, DUCKDB_V2_TABLE_PARTITION_INFO partition_info, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_partition_data_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_partition_data_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_partitioning_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_partitioning_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -1209,6 +1146,16 @@ typedef struct { (duckdb_v2_copy_to_statistics_info_handle info, idx_t row_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_data_chunk_get_capacity) (duckdb_v2_data_chunk_handle chunk, idx_t *out_capacity, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_claim_batch_get_bind_data) + (duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_claim_batch_get_global_state) + (duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_claim_batch_get_local_state) + (duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_claim_batch_get_user_data) + (duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_claim_batch_set_claimed) + (duckdb_v2_data_source_claim_batch_info_handle info, bool claimed, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_multi_file_function) (duckdb_v2_extension_handle extension, duckdb_v2_multi_file_function_handle function, duckdb_v2_error_info_handle *err); @@ -1228,19 +1175,6 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_multi_file_function_set_single_file_function) (duckdb_v2_multi_file_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_bind_data) - (duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_global_state) - (duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_local_state) - (duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_get_user_data) - (duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_claim_batch_set_claimed) - (duckdb_v2_table_function_claim_batch_info_handle info, bool claimed, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_claim_batch_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_claim_batch_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_function_bind_get_arg_count) (duckdb_v2_function_bind_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); @@ -1570,20 +1504,17 @@ typedef struct { (duckdb_v2_sql_statement_handle statement, const char *name, idx_t name_length, duckdb_v2_column_data_collection_handle collection, const char *const *column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_metrics_get_bind_data) + (duckdb_v2_data_source_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_metrics_get_global_state) + (duckdb_v2_data_source_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_metrics_get_user_data) + (duckdb_v2_data_source_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_metrics_set) + (duckdb_v2_data_source_metrics_info_handle info, const char *name, idx_t name_length, uint64_t value, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_add_virtual_column) (duckdb_v2_table_function_handle function, DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_bind_data) - (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_global_state) - (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_user_data) - (duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_set) - (duckdb_v2_table_function_metrics_info_handle info, const char *name, idx_t name_length, uint64_t value, - duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_metrics_callback) - (duckdb_v2_table_function_handle function, duckdb_v2_table_function_metrics_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_expression_check_statistics) (duckdb_v2_context_handle context, duckdb_v2_expression_handle expression, duckdb_v2_stats_handle stats, DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, duckdb_v2_error_info_handle *err); @@ -1787,8 +1718,42 @@ 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_data_source_create) + (duckdb_v2_factory_handle factory, duckdb_v2_data_source_handle *source, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_data_source_destroy)(duckdb_v2_data_source_handle *source); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_claim_batch_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_claim_batch_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_exec_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_exec_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_init_global_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_init_global_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_init_local_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_init_local_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_metrics_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_metrics_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_partition_data_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_partition_data_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_progress_callback) + (duckdb_v2_data_source_handle source, duckdb_v2_data_source_progress_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_user_data) + (duckdb_v2_data_source_handle source, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_data_source) + (duckdb_v2_table_function_handle function, duckdb_v2_data_source_handle data_source, + 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_V2_ERROR(*duckdb_v2_copy_from_set_data_source) + (duckdb_v2_copy_function_handle function, duckdb_v2_data_source_handle data_source, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_create_in_transaction) + (duckdb_v2_context_handle ctx, duckdb_v2_connection_handle *out_conn, duckdb_v2_error_info_handle *err); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -2546,103 +2511,84 @@ typedef struct { #define duckdb_v2_connection_register_table_function duckdb_ext_api.duckdb_v2_connection_register_table_function #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_extension_register_table_function duckdb_ext_api.duckdb_v2_extension_register_table_function +#define duckdb_v2_data_source_exec_get_bind_data duckdb_ext_api.duckdb_v2_data_source_exec_get_bind_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_bind_add_result_column duckdb_ext_api.duckdb_v2_table_function_bind_add_result_column +#define duckdb_v2_data_source_exec_get_global_state duckdb_ext_api.duckdb_v2_data_source_exec_get_global_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_bind_set_cardinality duckdb_ext_api.duckdb_v2_table_function_bind_set_cardinality +#define duckdb_v2_data_source_exec_get_local_state duckdb_ext_api.duckdb_v2_data_source_exec_get_local_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_create duckdb_ext_api.duckdb_v2_table_function_create +#define duckdb_v2_data_source_exec_get_output_chunk duckdb_ext_api.duckdb_v2_data_source_exec_get_output_chunk #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_destroy duckdb_ext_api.duckdb_v2_table_function_destroy +#define duckdb_v2_data_source_exec_get_user_data duckdb_ext_api.duckdb_v2_data_source_exec_get_user_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_exec_get_bind_data duckdb_ext_api.duckdb_v2_table_function_exec_get_bind_data +#define duckdb_v2_data_source_init_global_get_bind_data duckdb_ext_api.duckdb_v2_data_source_init_global_get_bind_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_exec_get_global_state duckdb_ext_api.duckdb_v2_table_function_exec_get_global_state +#define duckdb_v2_data_source_init_global_get_user_data duckdb_ext_api.duckdb_v2_data_source_init_global_get_user_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_exec_get_local_state duckdb_ext_api.duckdb_v2_table_function_exec_get_local_state +#define duckdb_v2_data_source_init_global_set_global_state \ + duckdb_ext_api.duckdb_v2_data_source_init_global_set_global_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_exec_get_output_chunk duckdb_ext_api.duckdb_v2_table_function_exec_get_output_chunk +#define duckdb_v2_data_source_init_global_set_max_threads \ + duckdb_ext_api.duckdb_v2_data_source_init_global_set_max_threads #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_exec_get_user_data duckdb_ext_api.duckdb_v2_table_function_exec_get_user_data +#define duckdb_v2_data_source_init_local_get_bind_data duckdb_ext_api.duckdb_v2_data_source_init_local_get_bind_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_get_signature duckdb_ext_api.duckdb_v2_table_function_get_signature +#define duckdb_v2_data_source_init_local_get_global_state \ + duckdb_ext_api.duckdb_v2_data_source_init_local_get_global_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_global_get_bind_data \ - duckdb_ext_api.duckdb_v2_table_function_init_global_get_bind_data +#define duckdb_v2_data_source_init_local_get_user_data duckdb_ext_api.duckdb_v2_data_source_init_local_get_user_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_global_get_user_data \ - duckdb_ext_api.duckdb_v2_table_function_init_global_get_user_data +#define duckdb_v2_data_source_init_local_set_local_state duckdb_ext_api.duckdb_v2_data_source_init_local_set_local_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_global_set_global_state \ - duckdb_ext_api.duckdb_v2_table_function_init_global_set_global_state +#define duckdb_v2_data_source_progress_get_bind_data duckdb_ext_api.duckdb_v2_data_source_progress_get_bind_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_global_set_max_threads \ - duckdb_ext_api.duckdb_v2_table_function_init_global_set_max_threads +#define duckdb_v2_data_source_progress_get_global_state duckdb_ext_api.duckdb_v2_data_source_progress_get_global_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_local_get_bind_data \ - duckdb_ext_api.duckdb_v2_table_function_init_local_get_bind_data +#define duckdb_v2_data_source_progress_get_user_data duckdb_ext_api.duckdb_v2_data_source_progress_get_user_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_local_get_global_state \ - duckdb_ext_api.duckdb_v2_table_function_init_local_get_global_state +#define duckdb_v2_data_source_progress_set_progress duckdb_ext_api.duckdb_v2_data_source_progress_set_progress #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_local_get_user_data \ - duckdb_ext_api.duckdb_v2_table_function_init_local_get_user_data +#define duckdb_v2_extension_register_table_function duckdb_ext_api.duckdb_v2_extension_register_table_function #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_local_set_local_state \ - duckdb_ext_api.duckdb_v2_table_function_init_local_set_local_state +#define duckdb_v2_table_function_bind_add_result_column duckdb_ext_api.duckdb_v2_table_function_bind_add_result_column #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_progress_get_bind_data duckdb_ext_api.duckdb_v2_table_function_progress_get_bind_data +#define duckdb_v2_table_function_bind_set_cardinality duckdb_ext_api.duckdb_v2_table_function_bind_set_cardinality #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_progress_get_global_state \ - duckdb_ext_api.duckdb_v2_table_function_progress_get_global_state +#define duckdb_v2_table_function_create duckdb_ext_api.duckdb_v2_table_function_create #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_progress_get_user_data duckdb_ext_api.duckdb_v2_table_function_progress_get_user_data +#define duckdb_v2_table_function_destroy duckdb_ext_api.duckdb_v2_table_function_destroy #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_progress_set_progress duckdb_ext_api.duckdb_v2_table_function_progress_set_progress +#define duckdb_v2_table_function_get_signature duckdb_ext_api.duckdb_v2_table_function_get_signature #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_set_bind_callback duckdb_ext_api.duckdb_v2_table_function_set_bind_callback #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_set_exec_callback duckdb_ext_api.duckdb_v2_table_function_set_exec_callback -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_set_init_global_callback \ - duckdb_ext_api.duckdb_v2_table_function_set_init_global_callback -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_set_init_local_callback duckdb_ext_api.duckdb_v2_table_function_set_init_local_callback -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_set_name duckdb_ext_api.duckdb_v2_table_function_set_name #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_set_progress_callback duckdb_ext_api.duckdb_v2_table_function_set_progress_callback -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_set_user_data duckdb_ext_api.duckdb_v2_table_function_set_user_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -2907,72 +2853,9 @@ typedef struct { #define duckdb_v2_copy_from_bind_set_cardinality duckdb_ext_api.duckdb_v2_copy_from_bind_set_cardinality #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_exec_get_bind_data duckdb_ext_api.duckdb_v2_copy_from_exec_get_bind_data -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_exec_get_global_state duckdb_ext_api.duckdb_v2_copy_from_exec_get_global_state -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_exec_get_local_state duckdb_ext_api.duckdb_v2_copy_from_exec_get_local_state -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_exec_get_output_chunk duckdb_ext_api.duckdb_v2_copy_from_exec_get_output_chunk -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_exec_get_user_data duckdb_ext_api.duckdb_v2_copy_from_exec_get_user_data -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_init_global_get_bind_data duckdb_ext_api.duckdb_v2_copy_from_init_global_get_bind_data -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_init_global_get_user_data duckdb_ext_api.duckdb_v2_copy_from_init_global_get_user_data -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_init_global_set_global_state duckdb_ext_api.duckdb_v2_copy_from_init_global_set_global_state -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_init_global_set_max_threads duckdb_ext_api.duckdb_v2_copy_from_init_global_set_max_threads -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_init_local_get_bind_data duckdb_ext_api.duckdb_v2_copy_from_init_local_get_bind_data -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_init_local_get_global_state duckdb_ext_api.duckdb_v2_copy_from_init_local_get_global_state -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_init_local_get_user_data duckdb_ext_api.duckdb_v2_copy_from_init_local_get_user_data -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_init_local_set_local_state duckdb_ext_api.duckdb_v2_copy_from_init_local_set_local_state -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_progress_get_bind_data duckdb_ext_api.duckdb_v2_copy_from_progress_get_bind_data -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_progress_get_global_state duckdb_ext_api.duckdb_v2_copy_from_progress_get_global_state -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_progress_get_user_data duckdb_ext_api.duckdb_v2_copy_from_progress_get_user_data -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_progress_set_progress duckdb_ext_api.duckdb_v2_copy_from_progress_set_progress -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_copy_from_set_bind_callback duckdb_ext_api.duckdb_v2_copy_from_set_bind_callback #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_set_exec_callback duckdb_ext_api.duckdb_v2_copy_from_set_exec_callback -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_set_init_global_callback duckdb_ext_api.duckdb_v2_copy_from_set_init_global_callback -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_set_init_local_callback duckdb_ext_api.duckdb_v2_copy_from_set_init_local_callback -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_set_progress_callback duckdb_ext_api.duckdb_v2_copy_from_set_progress_callback -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_copy_function_create duckdb_ext_api.duckdb_v2_copy_function_create #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -3087,6 +2970,28 @@ typedef struct { #define duckdb_v2_copy_to_set_init_callback duckdb_ext_api.duckdb_v2_copy_to_set_init_callback #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_exec_get_column_count duckdb_ext_api.duckdb_v2_data_source_exec_get_column_count +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_exec_get_column_index duckdb_ext_api.duckdb_v2_data_source_exec_get_column_index +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_init_global_get_column_count \ + duckdb_ext_api.duckdb_v2_data_source_init_global_get_column_count +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_init_global_get_column_index \ + duckdb_ext_api.duckdb_v2_data_source_init_global_get_column_index +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_init_local_get_column_count \ + duckdb_ext_api.duckdb_v2_data_source_init_local_get_column_count +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_init_local_get_column_index \ + duckdb_ext_api.duckdb_v2_data_source_init_local_get_column_index +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_expression_cast_get_mode duckdb_ext_api.duckdb_v2_expression_cast_get_mode #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -3147,12 +3052,6 @@ typedef struct { #define duckdb_v2_table_description_is_readonly duckdb_ext_api.duckdb_v2_table_description_is_readonly #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_exec_get_column_count duckdb_ext_api.duckdb_v2_table_function_exec_get_column_count -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_exec_get_column_index duckdb_ext_api.duckdb_v2_table_function_exec_get_column_index -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_filter_pushdown_accept duckdb_ext_api.duckdb_v2_table_function_filter_pushdown_accept #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -3180,22 +3079,6 @@ typedef struct { duckdb_ext_api.duckdb_v2_table_function_filter_pushdown_get_user_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_global_get_column_count \ - duckdb_ext_api.duckdb_v2_table_function_init_global_get_column_count -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_global_get_column_index \ - duckdb_ext_api.duckdb_v2_table_function_init_global_get_column_index -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_local_get_column_count \ - duckdb_ext_api.duckdb_v2_table_function_init_local_get_column_count -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_init_local_get_column_index \ - duckdb_ext_api.duckdb_v2_table_function_init_local_get_column_index -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_set_filter_pushdown_callback \ duckdb_ext_api.duckdb_v2_table_function_set_filter_pushdown_callback #endif @@ -3236,47 +3119,47 @@ typedef struct { #define duckdb_v2_attach_options_set duckdb_ext_api.duckdb_v2_attach_options_set #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_instance_set_default duckdb_ext_api.duckdb_v2_instance_set_default +#define duckdb_v2_data_source_partition_data_get_bind_data \ + duckdb_ext_api.duckdb_v2_data_source_partition_data_get_bind_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_partition_data_get_bind_data \ - duckdb_ext_api.duckdb_v2_table_function_partition_data_get_bind_data +#define duckdb_v2_data_source_partition_data_get_global_state \ + duckdb_ext_api.duckdb_v2_data_source_partition_data_get_global_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_partition_data_get_global_state \ - duckdb_ext_api.duckdb_v2_table_function_partition_data_get_global_state +#define duckdb_v2_data_source_partition_data_get_local_state \ + duckdb_ext_api.duckdb_v2_data_source_partition_data_get_local_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_partition_data_get_local_state \ - duckdb_ext_api.duckdb_v2_table_function_partition_data_get_local_state +#define duckdb_v2_data_source_partition_data_get_partition_column_count \ + duckdb_ext_api.duckdb_v2_data_source_partition_data_get_partition_column_count #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_partition_data_get_partition_column_count \ - duckdb_ext_api.duckdb_v2_table_function_partition_data_get_partition_column_count +#define duckdb_v2_data_source_partition_data_get_partition_column_index \ + duckdb_ext_api.duckdb_v2_data_source_partition_data_get_partition_column_index #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_partition_data_get_partition_column_index \ - duckdb_ext_api.duckdb_v2_table_function_partition_data_get_partition_column_index +#define duckdb_v2_data_source_partition_data_get_user_data \ + duckdb_ext_api.duckdb_v2_data_source_partition_data_get_user_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_partition_data_get_user_data \ - duckdb_ext_api.duckdb_v2_table_function_partition_data_get_user_data +#define duckdb_v2_data_source_partition_data_requires_batch_index \ + duckdb_ext_api.duckdb_v2_data_source_partition_data_requires_batch_index #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_partition_data_requires_batch_index \ - duckdb_ext_api.duckdb_v2_table_function_partition_data_requires_batch_index +#define duckdb_v2_data_source_partition_data_requires_partition_columns \ + duckdb_ext_api.duckdb_v2_data_source_partition_data_requires_partition_columns #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_partition_data_requires_partition_columns \ - duckdb_ext_api.duckdb_v2_table_function_partition_data_requires_partition_columns +#define duckdb_v2_data_source_partition_data_set_batch_index \ + duckdb_ext_api.duckdb_v2_data_source_partition_data_set_batch_index #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_partition_data_set_batch_index \ - duckdb_ext_api.duckdb_v2_table_function_partition_data_set_batch_index +#define duckdb_v2_data_source_partition_data_set_partition_value \ + duckdb_ext_api.duckdb_v2_data_source_partition_data_set_partition_value #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_partition_data_set_partition_value \ - duckdb_ext_api.duckdb_v2_table_function_partition_data_set_partition_value +#define duckdb_v2_instance_set_default duckdb_ext_api.duckdb_v2_instance_set_default #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_partitioning_get_bind_data \ @@ -3299,10 +3182,6 @@ typedef struct { duckdb_ext_api.duckdb_v2_table_function_partitioning_set_partition_info #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_set_partition_data_callback \ - duckdb_ext_api.duckdb_v2_table_function_set_partition_data_callback -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_set_partitioning_callback \ duckdb_ext_api.duckdb_v2_table_function_set_partitioning_callback #endif @@ -3335,49 +3214,43 @@ typedef struct { #define duckdb_v2_data_chunk_get_capacity duckdb_ext_api.duckdb_v2_data_chunk_get_capacity #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_extension_register_multi_file_function duckdb_ext_api.duckdb_v2_extension_register_multi_file_function +#define duckdb_v2_data_source_claim_batch_get_bind_data duckdb_ext_api.duckdb_v2_data_source_claim_batch_get_bind_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_multi_file_function_create duckdb_ext_api.duckdb_v2_multi_file_function_create -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_multi_file_function_destroy duckdb_ext_api.duckdb_v2_multi_file_function_destroy +#define duckdb_v2_data_source_claim_batch_get_global_state \ + duckdb_ext_api.duckdb_v2_data_source_claim_batch_get_global_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_multi_file_function_set_file_extension duckdb_ext_api.duckdb_v2_multi_file_function_set_file_extension +#define duckdb_v2_data_source_claim_batch_get_local_state \ + duckdb_ext_api.duckdb_v2_data_source_claim_batch_get_local_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_multi_file_function_set_name duckdb_ext_api.duckdb_v2_multi_file_function_set_name +#define duckdb_v2_data_source_claim_batch_get_user_data duckdb_ext_api.duckdb_v2_data_source_claim_batch_get_user_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_multi_file_function_set_reader_type duckdb_ext_api.duckdb_v2_multi_file_function_set_reader_type +#define duckdb_v2_data_source_claim_batch_set_claimed duckdb_ext_api.duckdb_v2_data_source_claim_batch_set_claimed #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_multi_file_function_set_single_file_function \ - duckdb_ext_api.duckdb_v2_multi_file_function_set_single_file_function +#define duckdb_v2_extension_register_multi_file_function duckdb_ext_api.duckdb_v2_extension_register_multi_file_function #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_claim_batch_get_bind_data \ - duckdb_ext_api.duckdb_v2_table_function_claim_batch_get_bind_data +#define duckdb_v2_multi_file_function_create duckdb_ext_api.duckdb_v2_multi_file_function_create #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_claim_batch_get_global_state \ - duckdb_ext_api.duckdb_v2_table_function_claim_batch_get_global_state +#define duckdb_v2_multi_file_function_destroy duckdb_ext_api.duckdb_v2_multi_file_function_destroy #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_claim_batch_get_local_state \ - duckdb_ext_api.duckdb_v2_table_function_claim_batch_get_local_state +#define duckdb_v2_multi_file_function_set_file_extension duckdb_ext_api.duckdb_v2_multi_file_function_set_file_extension #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_claim_batch_get_user_data \ - duckdb_ext_api.duckdb_v2_table_function_claim_batch_get_user_data +#define duckdb_v2_multi_file_function_set_name duckdb_ext_api.duckdb_v2_multi_file_function_set_name #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_claim_batch_set_claimed duckdb_ext_api.duckdb_v2_table_function_claim_batch_set_claimed +#define duckdb_v2_multi_file_function_set_reader_type duckdb_ext_api.duckdb_v2_multi_file_function_set_reader_type #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_set_claim_batch_callback \ - duckdb_ext_api.duckdb_v2_table_function_set_claim_batch_callback +#define duckdb_v2_multi_file_function_set_single_file_function \ + duckdb_ext_api.duckdb_v2_multi_file_function_set_single_file_function #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_function_bind_get_arg_count duckdb_ext_api.duckdb_v2_function_bind_get_arg_count @@ -3803,23 +3676,19 @@ typedef struct { #define duckdb_v2_statement_add_collection duckdb_ext_api.duckdb_v2_statement_add_collection #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_add_virtual_column duckdb_ext_api.duckdb_v2_table_function_add_virtual_column -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_metrics_get_bind_data duckdb_ext_api.duckdb_v2_table_function_metrics_get_bind_data +#define duckdb_v2_data_source_metrics_get_bind_data duckdb_ext_api.duckdb_v2_data_source_metrics_get_bind_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_metrics_get_global_state \ - duckdb_ext_api.duckdb_v2_table_function_metrics_get_global_state +#define duckdb_v2_data_source_metrics_get_global_state duckdb_ext_api.duckdb_v2_data_source_metrics_get_global_state #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_metrics_get_user_data duckdb_ext_api.duckdb_v2_table_function_metrics_get_user_data +#define duckdb_v2_data_source_metrics_get_user_data duckdb_ext_api.duckdb_v2_data_source_metrics_get_user_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_metrics_set duckdb_ext_api.duckdb_v2_table_function_metrics_set +#define duckdb_v2_data_source_metrics_set duckdb_ext_api.duckdb_v2_data_source_metrics_set #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_table_function_set_metrics_callback duckdb_ext_api.duckdb_v2_table_function_set_metrics_callback +#define duckdb_v2_table_function_add_virtual_column duckdb_ext_api.duckdb_v2_table_function_add_virtual_column #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_expression_check_statistics duckdb_ext_api.duckdb_v2_expression_check_statistics @@ -4069,8 +3938,46 @@ 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_data_source_create duckdb_ext_api.duckdb_v2_data_source_create +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_destroy duckdb_ext_api.duckdb_v2_data_source_destroy +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_set_claim_batch_callback duckdb_ext_api.duckdb_v2_data_source_set_claim_batch_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_set_exec_callback duckdb_ext_api.duckdb_v2_data_source_set_exec_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_set_init_global_callback duckdb_ext_api.duckdb_v2_data_source_set_init_global_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_set_init_local_callback duckdb_ext_api.duckdb_v2_data_source_set_init_local_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_set_metrics_callback duckdb_ext_api.duckdb_v2_data_source_set_metrics_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_set_partition_data_callback \ + duckdb_ext_api.duckdb_v2_data_source_set_partition_data_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_set_progress_callback duckdb_ext_api.duckdb_v2_data_source_set_progress_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_set_user_data duckdb_ext_api.duckdb_v2_data_source_set_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_set_data_source duckdb_ext_api.duckdb_v2_table_function_set_data_source +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_value_variant_to_value duckdb_ext_api.duckdb_v2_value_variant_to_value #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_copy_from_set_data_source duckdb_ext_api.duckdb_v2_copy_from_set_data_source +#define duckdb_v2_connection_create_in_transaction duckdb_ext_api.duckdb_v2_connection_create_in_transaction +#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 7f0330ad6..675c77488 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -1965,6 +1965,36 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_create(duckdb_v2_instance_hand duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Opens a connection that runs in the transaction of a context. + * + * Lets a callback run SQL inside the transaction it is called in, such as a table function's bind callback reading a + * table. The connection sees everything the context's transaction sees, including its uncommitted changes and the + * context's temporary objects, and what it changes is part of that transaction. A statement of the connection that + * fails invalidates the transaction as a failure of the context's own statement would. + * + * The connection cannot start, commit or roll back a transaction: those statements fail with + * ERROR_DATABASE_TRANSACTION, and like any failing statement invalidate the transaction. The connection stays in the + * transaction until it is destroyed, which neither commits nor rolls the transaction back. Destroy it before the + * transaction ends, typically before the callback returns: a transaction that is committed while such a connection is + * still open is rolled back instead, and the connection's statements fail from then on. Interrupting the context's + * query also interrupts the connection's. The caller destroys it via `duckdb_v2_connection_destroy()`. + * + * history: + * - unstable: v2.0.0 + * + * @param ctx The context whose transaction the connection runs in. It must have an active transaction. + * @param out_conn Receives the new connection handle. + * @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_create_in_transaction(duckdb_v2_context_handle ctx, + duckdb_v2_connection_handle *out_conn, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Destroys the connection. @@ -8500,223 +8530,78 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_destroy(duckdb_v2_colu /* --- Struct definitions for catalog --- */ /* ============================================================================ - * MODULE: copy + * MODULE: custom_option * ============================================================================ */ -/* --- Enums for copy --- */ - -/* --- Struct forward declarations for copy --- */ - -/* --- Types for copy --- */ - -/*! - * An owned opaque handle to a custom copy function being built: an output format for `COPY ... TO`, an input format for - * `COPY ... FROM`, or both. Created with `duckdb_v2_copy_function_create()`, configured with the setter functions (e.g. - * `duckdb_v2_copy_function_set_name()`, `duckdb_v2_copy_to_set_batch_callback()`, - * `duckdb_v2_copy_from_set_exec_callback()`, etc.), made available with `duckdb_v2_connection_register_copy_function()` - * or `duckdb_v2_extension_register_copy_function()`, and destroyed with `duckdb_v2_copy_function_destroy()`. - */ -typedef struct _duckdb_v2_copy_function { - void *internal_ptr; -} * duckdb_v2_copy_function_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a copy function during the query preparation "bind" phase of a - * `COPY ... TO` statement. The "bind" callback receives this handle and can use it to e.g. inspect the names and types - * of the columns being written, read the statement's options and initialize some constant state. - */ -typedef struct _duckdb_v2_copy_to_bind_info { - void *internal_ptr; -} * duckdb_v2_copy_to_bind_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a copy function during the "batch size" phase of a `COPY ... - * TO` statement. The "batch size" callback receives this handle and must use it to report how many rows a batch should - * carry. - */ -typedef struct _duckdb_v2_copy_to_batch_size_info { - void *internal_ptr; -} * duckdb_v2_copy_to_batch_size_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a copy function during the per-file "init" phase of a `COPY ... - * TO` statement. The "init" callback receives this handle and can use it to e.g. read the path of the file being - * written and set up the state shared by every batch written to that file. - */ -typedef struct _duckdb_v2_copy_to_init_info { - void *internal_ptr; -} * duckdb_v2_copy_to_init_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a copy function during the "batch" phase of a `COPY ... TO` - * statement. The "batch" callback receives this handle and can use it to take ownership of the rows of the batch and to - * set the prepared form of the batch handed to the "flush" callback. - */ -typedef struct _duckdb_v2_copy_to_batch_info { - void *internal_ptr; -} * duckdb_v2_copy_to_batch_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a copy function during the "flush" phase of a `COPY ... TO` - * statement. The "flush" callback receives this handle and can use it to access the prepared batch and write it to the - * output. - */ -typedef struct _duckdb_v2_copy_to_flush_info { - void *internal_ptr; -} * duckdb_v2_copy_to_flush_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a copy function during the per-file "finalize" phase of a `COPY - * ... TO` statement. The "finalize" callback receives this handle and can use it to e.g. close the file after every - * batch has been flushed to it. - */ -typedef struct _duckdb_v2_copy_to_finalize_info { - void *internal_ptr; -} * duckdb_v2_copy_to_finalize_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a copy function when a `COPY ... TO` statement reports - * statistics about the files it wrote (e.g. with `RETURN_STATS`). The "statistics" callback receives this handle and - * uses it to report the statistics of one written file. - */ -typedef struct _duckdb_v2_copy_to_statistics_info { - void *internal_ptr; -} * duckdb_v2_copy_to_statistics_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a copy function during the query preparation "bind" phase of a - * `COPY ... FROM` statement. The "bind" callback receives this handle and can use it to e.g. read the path of the file - * to read, inspect the names and types of the columns the target table expects, read the statement's options, hint at - * the number of rows the read will produce and initialize some constant state. - */ -typedef struct _duckdb_v2_copy_from_bind_info { - void *internal_ptr; -} * duckdb_v2_copy_from_bind_info_handle; +/* --- Enums for custom_option --- */ -/*! - * A borrowed opaque handle to the arguments supplied to a copy function during the global state initialization "init - * global" phase of a `COPY ... FROM` statement. The "init global" callback receives this handle and can use it to e.g. - * set up the state shared by every thread reading the file, and to declare how many threads may read it. - */ -typedef struct _duckdb_v2_copy_from_init_global_info { - void *internal_ptr; -} * duckdb_v2_copy_from_init_global_info_handle; +/* --- Struct forward declarations for custom_option --- */ -/*! - * A borrowed opaque handle to the arguments supplied to a copy function during the local state initialization "init - * local" phase of a `COPY ... FROM` statement. The "init local" callback receives this handle and can use it to e.g. - * set up worker-local state, typically by claiming work from the shared global state. - */ -typedef struct _duckdb_v2_copy_from_init_local_info { - void *internal_ptr; -} * duckdb_v2_copy_from_init_local_info_handle; +/* --- Types for custom_option --- */ /*! - * A borrowed opaque handle to the arguments supplied to a copy function during the execution "exec" phase of a `COPY - * ... FROM` statement. The "exec" callback receives this handle and can use it to e.g. access the global and local - * state and write the next batch of rows to the output chunk. + * An owned opaque handle to a custom option being built. Created with `duckdb_v2_custom_option_create()`, configured + * with the setter functions (e.g. `duckdb_v2_custom_option_set_name()`, `duckdb_v2_custom_option_set_type()`, etc.), + * made available with `duckdb_v2_connection_register_custom_option()` or + * `duckdb_v2_extension_register_custom_option()`, and destroyed with `duckdb_v2_custom_option_destroy()`. */ -typedef struct _duckdb_v2_copy_from_exec_info { +typedef struct _duckdb_v2_custom_option { void *internal_ptr; -} * duckdb_v2_copy_from_exec_info_handle; +} * duckdb_v2_custom_option_handle; /*! - * A borrowed opaque handle to the arguments supplied to a copy function during the "progress" phase of a `COPY ... - * FROM` statement. The "progress" callback receives this handle and can use it to report how far the read has advanced. + * A borrowed opaque handle to an update of a custom option, received by its update callback. It gives access to the new + * value, the scope it is written at and the user data, and can replace the value. */ -typedef struct _duckdb_v2_copy_from_progress_info { +typedef struct _duckdb_v2_custom_option_update_info { void *internal_ptr; -} * duckdb_v2_copy_from_progress_info_handle; - -/* --- Constants for copy --- */ - -/* --- Function pointer typedefs for copy --- */ - -typedef void (*duckdb_v2_copy_to_bind_callback_fn)(duckdb_v2_copy_to_bind_info_handle info, - duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_copy_to_batch_size_callback_fn)(duckdb_v2_copy_to_batch_size_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_copy_to_init_callback_fn)(duckdb_v2_copy_to_init_info_handle info, - duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_copy_to_batch_callback_fn)(duckdb_v2_copy_to_batch_info_handle info, - duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_copy_to_flush_callback_fn)(duckdb_v2_copy_to_flush_info_handle info, - duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_copy_to_finalize_callback_fn)(duckdb_v2_copy_to_finalize_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_copy_to_statistics_callback_fn)(duckdb_v2_copy_to_statistics_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); +} * duckdb_v2_custom_option_update_info_handle; -typedef void (*duckdb_v2_copy_from_bind_callback_fn)(duckdb_v2_copy_from_bind_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); +/* --- Constants for custom_option --- */ -typedef void (*duckdb_v2_copy_from_init_global_callback_fn)(duckdb_v2_copy_from_init_global_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); +/* --- Function pointer typedefs for custom_option --- */ -typedef void (*duckdb_v2_copy_from_init_local_callback_fn)(duckdb_v2_copy_from_init_local_info_handle info, +typedef void (*duckdb_v2_custom_option_update_callback_fn)(duckdb_v2_custom_option_update_info_handle info, duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); -typedef void (*duckdb_v2_copy_from_exec_callback_fn)(duckdb_v2_copy_from_exec_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_copy_from_progress_callback_fn)(duckdb_v2_copy_from_progress_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -/* --- Functions for copy --- */ +/* --- Functions for custom_option --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new copy function through a factory. + * Creates a new custom option through a factory. * - * A copy function implements a file format for `COPY`: once registered, SQL reaches it with `COPY ... TO 'path' (FORMAT - * name)` and `COPY table FROM 'path' (FORMAT name)`. The function starts out empty: configure it with the setter - * functions (e.g. `duckdb_v2_copy_function_set_name()`, the `copy_to_set_*` callbacks for writing, the - * `copy_from_set_*` callbacks for reading, or both), then make it available with - * `duckdb_v2_connection_register_copy_function()` or `duckdb_v2_extension_register_copy_function()`. The caller owns - * the returned handle and must destroy it with `duckdb_v2_copy_function_destroy()`, also after registration. + * The option starts out empty: configure it with the setter functions, then make it available with + * `duckdb_v2_connection_register_custom_option()` or `duckdb_v2_extension_register_custom_option()`. The caller owns + * the returned handle and must destroy it with `duckdb_v2_custom_option_destroy()`, also after registration. * - * The copy function can only be registered on the database the factory belongs to. + * The custom option can only be registered on the instance the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the copy function through. - * @param function On success, receives the newly created copy function. Owned by the caller. + * @param factory The factory to create the custom option through. + * @param option On success, receives the newly created custom option. Owned by the caller. * @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_copy_function_create(duckdb_v2_factory_handle factory, - duckdb_v2_copy_function_handle *function, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_create(duckdb_v2_factory_handle factory, + duckdb_v2_custom_option_handle *option, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the copy function. + * Sets the name of the custom option, as `SET` and the config functions refer to it. * - * The name is the format SQL selects the function with: `COPY ... TO 'path' (FORMAT name)` or `COPY table FROM 'path' - * (FORMAT name)`. It is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before * registration. * * history: * - unstable: v2.0.0 * - * @param function The function to set the name of. + * @param option The option to set the name of. * @param name The name to set. Borrowed and copied. * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be * NULL only when this is 0. @@ -8724,1439 +8609,1974 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_create(duckdb_v2_factory_ha * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_set_name(duckdb_v2_copy_function_handle function, const char *name, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_name(duckdb_v2_custom_option_handle option, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the file extension of the files the copy function writes, without the leading dot, e.g. `parquet`. + * Sets the type of the custom option. Every value written to the option is cast to it, as SQL `SET` does. * - * DuckDB uses it when it names files itself, e.g. the files of `COPY ... TO 'dir' (PARTITION_BY ...)` or - * `(PER_THREAD_OUTPUT)`. A statement can override it with the `FILE_EXTENSION` option. An extension starting with a dot - * is rejected. The extension is borrowed and copied. Calling this again replaces the previous extension. Optional, but - * without it the names DuckDB gives files end in a bare dot, e.g. `data_0.`. + * The type is borrowed and copied. Optional when a default value is set, whose type the option then takes. * * history: * - unstable: v2.0.0 * - * @param function The function to set the file extension of. - * @param extension The extension to set, without the leading dot. Borrowed and copied. - * @param extension_length The length of `extension` in bytes. `extension` need not be null-terminated and may be NULL - * only when this is 0. + * @param option The option to set the type of. + * @param type The type to set. Borrowed and copied. * @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_copy_function_set_file_extension(duckdb_v2_copy_function_handle function, - const char *extension, idx_t extension_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_type(duckdb_v2_custom_option_handle option, + duckdb_v2_logical_type_handle type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the copy function. + * Sets the default value of the custom option: its value until it is set, and the value `RESET` restores. * - * Associates an opaque pointer with the function, retrievable from each callback of either side via its user data - * accessor (e.g. `duckdb_v2_copy_to_bind_get_user_data()`, `duckdb_v2_copy_from_exec_get_user_data()`, etc.). The - * opaque handle bundles the pointer with an optional destructor, invoked when the data is no longer needed. + * The value is borrowed and copied, and cast to the option's type at registration, which fails when the cast does. + * Without a default value the option reads as NULL until it is set. * * history: * - unstable: v2.0.0 * - * @param function The function to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param option The option to set the default value of. + * @param value The default value. Borrowed and copied. * @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_copy_function_set_user_data(duckdb_v2_copy_function_handle function, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_default_value(duckdb_v2_custom_option_handle option, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional bind callback of the `COPY ... TO` side. + * Sets the description of the custom option, as `duckdb_v2_option_get_description()` and `duckdb_settings()` report it. * - * The bind callback is invoked during query planning for each `COPY ... TO` statement that uses the function. It can - * inspect the names and types of the columns being written, read the statement's options and set "bind data" that is - * shared with the other `COPY ... TO` callbacks. + * The description is borrowed and copied. Calling this again replaces the previous description. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. + * @param option The option to set the description of. + * @param description The description to set. Borrowed and copied. + * @param description_length The length of `description` in bytes. `description` need not be null-terminated and may be + * NULL only when this is 0. * @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_copy_to_set_bind_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_to_bind_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_description(duckdb_v2_custom_option_handle option, + const char *description, idx_t description_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional batch size callback of the `COPY ... TO` side. + * Sets the scope a write at `SETTING_SCOPE_DEFAULT` goes to, like SQL `SET name = value`. * - * The batch size callback is invoked during query planning, after the bind callback, for each `COPY ... TO` statement - * that does not set `BATCH_SIZE` itself. It should report how many rows a batch should carry via - * `duckdb_v2_copy_to_batch_size_set_target()`; the engine then cuts the rows being written into batches of that size - * and hands each to the batch callback. Without a batch size from either the statement or the callback, a batch is cut - * for every chunk of rows sunk, i.e. a vector at a time. A batch may still be smaller than the reported size (the last - * one of a file, or when `BATCH_SIZE_BYTES` cuts it first). - * - * history: - * - unstable: v2.0.0 - * - * @param function The function to set the callback of. - * @param callback The callback to set. - * @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_copy_to_set_batch_size_callback( - duckdb_v2_copy_function_handle function, duckdb_v2_copy_to_batch_size_callback_fn callback, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the optional init callback of the `COPY ... TO` side. - * - * The init callback is invoked once per output file, before any batch destined for that file is prepared. It can read - * the path of the file via `duckdb_v2_copy_to_init_get_file_path()` and set "init data" that is shared with the batch, - * flush and finalize callbacks of that file. A statement may write several files, e.g. when its output is partitioned; - * each gets its own init data. + * Must be GLOBAL or SESSION, and a scope the option supports. Defaults to SESSION, or to GLOBAL when the option does + * not support SESSION. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. + * @param option The option to set the default scope of. + * @param scope The default scope, GLOBAL or SESSION. * @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_copy_to_set_init_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_to_init_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_default_scope(duckdb_v2_custom_option_handle option, + DUCKDB_V2_SETTING_SCOPE scope, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the batch callback of the `COPY ... TO` side. + * Sets whether the custom option can be written at a scope, as `duckdb_v2_option_supports_scope()` reports it. * - * The batch callback is invoked during query execution with a batch of the rows being written, taken via - * `duckdb_v2_copy_to_batch_take_input()`. It prepares the batch for writing, e.g. by encoding it into the output - * format, and sets "batch data" via `duckdb_v2_copy_to_batch_set_batch_data()` that is handed to the flush callback. - * Batches may be prepared by several threads at once, so the callback must synchronize its own access to the init data. - * A batch callback must be set for the `COPY ... TO` side to be registered. + * A custom option supports both GLOBAL and SESSION unless told otherwise. A write at a scope it does not support fails, + * from SQL as from `duckdb_v2_config_set_option_value()`. Registration fails when the option supports neither scope. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. + * @param option The option to configure. + * @param scope The scope, GLOBAL or SESSION. + * @param supported Whether the option can be written at the scope. * @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_copy_to_set_batch_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_to_batch_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_supports_scope(duckdb_v2_custom_option_handle option, + DUCKDB_V2_SETTING_SCOPE scope, bool supported, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the flush callback of the `COPY ... TO` side. + * Sets arbitrary user data on the custom option. * - * The flush callback is invoked once per prepared batch to write its batch data, available via - * `duckdb_v2_copy_to_flush_get_batch_data()`, to the output. Flushes of the same file never run concurrently. A flush - * callback must be set for the `COPY ... TO` side to be registered. + * Associates an opaque pointer with the option, retrievable from the update callback via + * `duckdb_v2_custom_option_update_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, + * invoked when the data is no longer needed: once the custom option handle is destroyed and, if it was registered, the + * instance is too. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. + * @param option The option to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. * @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_copy_to_set_flush_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_to_flush_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_user_data(duckdb_v2_custom_option_handle option, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional finalize callback of the `COPY ... TO` side. + * Sets the optional update callback of the custom option. * - * The finalize callback is invoked once per output file after the last batch destined for that file has been flushed. - * It can e.g. write a footer and close the file. + * The callback is invoked whenever the option is set or reset, from SQL as from `duckdb_v2_config_set_option_value()`, + * after the new value is cast to the option's type and before it is stored. It may replace the value with + * `duckdb_v2_custom_option_update_set_value()`, or refuse it by reporting an error. It is not invoked for the default + * value at registration, nor for a value given to the instance at startup. The callback must not write options itself. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. + * @param option The option to set the update callback of. + * @param callback The update callback to set. * @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_copy_to_set_finalize_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_to_finalize_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_update_callback( + duckdb_v2_custom_option_handle option, duckdb_v2_custom_option_update_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. + * Retrieves the user data set via `duckdb_v2_custom_option_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. + * @param info The update info handle. * @param data Receives the user data pointer, or null if none was set. * @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_copy_to_bind_get_user_data(duckdb_v2_copy_to_bind_info_handle info, void **data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_user_data( + duckdb_v2_custom_option_update_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the function's "bind data" from the bind callback. - * - * The bind data is stored with the bound statement and retrievable from the other callbacks of the same side. The - * opaque handle bundles the pointer with an optional destructor, invoked when the bind data is no longer needed, and an - * optional equality callback used when comparing two bound statements; without one, pointer equality is used. + * Retrieves the value the option is updated to, already cast to the option's type. On a reset this is the default + * value, which may be NULL. The returned value is owned by the caller and must be destroyed via + * `duckdb_v2_value_destroy()`. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param data Opaque handle bundling the bind data pointer plus optional destructor and equality callbacks. + * @param info The update info handle. + * @param value Receives the new value. Owned by the caller; destroy via `duckdb_v2_value_destroy()`. * @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_copy_to_bind_set_bind_data(duckdb_v2_copy_to_bind_info_handle info, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_value(duckdb_v2_custom_option_update_info_handle info, + duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the path the `COPY ... TO` statement writes to, as written in the statement. - * - * This is the target before the engine's own rewrites: the path of each file actually being written, e.g. a temporary - * name or a per-partition path, is only known to the init callback via `duckdb_v2_copy_to_init_get_file_path()`. The - * path is borrowed and valid only for the duration of the callback. + * Replaces the value the option is updated to, e.g. to normalize it. The value is borrowed and copied, and cast to the + * option's type, which fails when the cast does. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param path Receives a borrowed pointer to the file path. Valid only for the duration of the callback. - * @param path_length Receives the length of `*path` in bytes. `*path` is not guaranteed to be null-terminated. + * @param info The update info handle. + * @param value The value to store instead. Borrowed and copied. * @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_copy_to_bind_get_file_path(duckdb_v2_copy_to_bind_info_handle info, - const char **path, idx_t *path_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_set_value(duckdb_v2_custom_option_update_info_handle info, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns being written, i.e. the columns of the rows every batch carries. - * - * Valid indices for `duckdb_v2_copy_to_bind_get_column_type()` and `duckdb_v2_copy_to_bind_get_column_name()` are [0, - * count). + * Retrieves the scope the value is written at: GLOBAL or SESSION, a DEFAULT write already resolved to the option's + * default scope. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param count Receives the number of columns. + * @param info The update info handle. + * @param scope Receives the scope. * @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_copy_to_bind_get_column_count(duckdb_v2_copy_to_bind_info_handle info, - idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_scope(duckdb_v2_custom_option_update_info_handle info, + DUCKDB_V2_SETTING_SCOPE *scope, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the type of the column at the given index. - * - * Fails if the index is out of bounds. The returned type is owned by the caller and must be destroyed via - * `duckdb_v2_logical_type_destroy()`. + * Retrieves whether the update is a reset to the default value, like SQL `RESET`. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param index The index of the column to get the type of. - * @param type Receives the column type. Owned by the caller; destroy via `duckdb_v2_logical_type_destroy()`. + * @param info The update info handle. + * @param is_reset Receives whether the update is a reset. * @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_copy_to_bind_get_column_type(duckdb_v2_copy_to_bind_info_handle info, - idx_t index, duckdb_v2_logical_type_handle *type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_is_reset(duckdb_v2_custom_option_update_info_handle info, + bool *is_reset, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the name of the column at the given index. + * Registers the custom option on the connection's instance, visible to every connection. * - * Fails if the index is out of bounds. The name is borrowed and valid only for the duration of the callback. + * Registration is not transactional: it takes effect at once, also inside an explicit transaction, and a rollback does + * not undo it. Registration requires a name and a type, or a default value to take the type from, and fails when an + * option of the same name already exists. A value given for the option at startup is picked up. The custom option must + * have been created through a factory of the same instance. The caller still owns the handle after registration and + * must destroy it with `duckdb_v2_custom_option_destroy()`, which does not affect the registered option. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param index The index of the column to get the name of. - * @param name Receives a borrowed pointer to the column name. Valid only for the duration of the callback. - * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. + * @param conn The connection to register on. + * @param option The custom option to register. * @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_copy_to_bind_get_column_name(duckdb_v2_copy_to_bind_info_handle info, - idx_t index, const char **name, idx_t *name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_custom_option(duckdb_v2_connection_handle conn, + duckdb_v2_custom_option_handle option, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of options the `COPY` statement passed to the function. + * Registers the custom option on the loading extension's instance, visible to every connection. * - * The engine's own options (e.g. `USE_TMP_FILE` or `BATCH_SIZE`) are handled before the function sees the statement and - * are not included. Valid indices for `duckdb_v2_copy_to_bind_get_option_name()` and - * `duckdb_v2_copy_to_bind_get_option_value()` are [0, count). The options are ordered by name. + * Use this from the extension's load callback. Registration is not transactional, requires a name and a type, or a + * default value to take the type from, and fails when an option of the same name already exists. A value given for the + * option at startup is picked up. The custom option must have been created through a factory of the same instance. The + * caller still owns the handle after registration and must destroy it with `duckdb_v2_custom_option_destroy()`, which + * does not affect the registered option. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param count Receives the number of options. + * @param extension The loading extension. + * @param option The custom option to register. * @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_copy_to_bind_get_option_count(duckdb_v2_copy_to_bind_info_handle info, - idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_custom_option(duckdb_v2_extension_handle extension, + duckdb_v2_custom_option_handle option, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the name of the option at the given index. + * Destroys the custom option, releasing its resources. * - * Option names are SQL identifiers, matched case-insensitively. Fails if the index is out of bounds. The name is - * borrowed and valid only for the duration of the callback. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered option. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param index The index of the option to get the name of. - * @param name Receives a borrowed pointer to the option name. Valid only for the duration of the callback. - * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param option The option to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_option_name(duckdb_v2_copy_to_bind_info_handle info, - idx_t index, const char **name, idx_t *name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_destroy(duckdb_v2_custom_option_handle *option); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE +/* --- Struct definitions for custom_option --- */ + +/* ============================================================================ + * MODULE: expression + * ============================================================================ */ + +/* --- Enums for expression --- */ + /*! - * Retrieves the value of the option at the given index. - * - * An option written with a single value (e.g. `DELIM ','`) yields that value. An option written as a bare name (e.g. - * `HEADER`) yields the BOOLEAN `true`. An option written with a parenthesized list (e.g. `KEYS (a, b)`) yields a tuple: - * an unnamed STRUCT with one field per element, in order. Fails if the index is out of bounds. The returned value is - * owned by the caller and must be destroyed via `duckdb_v2_value_destroy()`. - * - * history: - * - unstable: v2.0.0 + * The type of a bound expression node. The values mirror the engine's own expression types, restricted to the node + * types a filter predicate can contain; every other node type is reported as `EXPRESSION_TYPE_INVALID`. * - * @param info The bind info handle. - * @param index The index of the option. - * @param value Receives the option's value. Owned by the caller; destroy via `duckdb_v2_value_destroy()`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR + * 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` therefore has one child, the value being + * cast, and its target type is the node's return type. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_option_value(duckdb_v2_copy_to_bind_info_handle info, - idx_t index, duckdb_v2_value_handle *value, - duckdb_v2_error_info_handle *err); -#endif +typedef enum DUCKDB_V2_EXPRESSION_TYPE { + //! A node type this API does not model. Its children can still be walked. + DUCKDB_V2_EXPRESSION_TYPE_INVALID = 0, + + /*! + * A cast. One child; the target type is the node's return type and `duckdb_v2_expression_cast_get_mode()` tells a + * `TRY_CAST` apart. + */ + DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_CAST = 12, + + //! Logical `NOT`. One child. + DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_NOT = 13, + + //! `IS NULL`. One child. + DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_IS_NULL = 14, + + //! `IS NOT NULL`. One child. + DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_IS_NOT_NULL = 15, + + //! `=`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_EQUAL = 25, + + //! `<>`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOTEQUAL = 26, + + //! `<`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_LESSTHAN = 27, + + //! `>`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_GREATERTHAN = 28, + + //! `<=`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO = 29, + + //! `>=`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO = 30, + + //! `IN`. The first child is the value tested, the remaining children are the candidates. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_IN = 35, + + //! `NOT IN`. The first child is the value tested, the remaining children are the candidates. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOT_IN = 36, + + //! `IS DISTINCT FROM`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_DISTINCT_FROM = 37, + + //! `BETWEEN`. Three children: the value tested, the lower bound and the upper bound. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_BETWEEN = 38, + + //! `IS NOT DISTINCT FROM`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOT_DISTINCT_FROM = 40, + + //! Logical `AND`. Two or more children. + DUCKDB_V2_EXPRESSION_TYPE_CONJUNCTION_AND = 50, + + //! Logical `OR`. Two or more children. + DUCKDB_V2_EXPRESSION_TYPE_CONJUNCTION_OR = 51, + + //! A constant. No children; read it with `duckdb_v2_expression_constant_get_value()`. + DUCKDB_V2_EXPRESSION_TYPE_VALUE_CONSTANT = 75, + + //! A prepared statement parameter whose value is not known yet. No children. + DUCKDB_V2_EXPRESSION_TYPE_VALUE_PARAMETER = 76, + + /*! + * A call to a scalar function other than the ones listed above. The children are its arguments; read the name with + * `duckdb_v2_expression_function_get_name()`. + */ + DUCKDB_V2_EXPRESSION_TYPE_BOUND_FUNCTION = 141, + + //! A `CASE` expression. The children are each `WHEN` condition followed by its `THEN` result, then the `ELSE` + //! result. + DUCKDB_V2_EXPRESSION_TYPE_CASE_EXPR = 150, + + //! `COALESCE`. One or more children. + DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_COALESCE = 152, + + //! A reference to a column. No children; read it with `duckdb_v2_expression_column_ref_get_index()`. + DUCKDB_V2_EXPRESSION_TYPE_BOUND_COLUMN_REF = 228, + DUCKDB_V2_EXPRESSION_TYPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_EXPRESSION_TYPE; + +/*! + * What checking a predicate against the statistics of its column found out (`FilterPropagateResult`): whether every row + * the statistics describe passes the predicate, none does, or the statistics do not tell. + */ +typedef enum DUCKDB_V2_FILTER_PROPAGATE_RESULT { + //! The statistics do not decide the predicate. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_NO_PRUNING_POSSIBLE = 0, + + //! Every row passes the predicate. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_ALWAYS_TRUE = 1, + + //! No row passes the predicate. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_ALWAYS_FALSE = 2, + + //! Every row passes the predicate or evaluates it to NULL. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_TRUE_OR_NULL = 3, + + //! No row passes the predicate: each evaluates it to false or to NULL. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_FALSE_OR_NULL = 4, + DUCKDB_V2_FILTER_PROPAGATE_RESULT_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_FILTER_PROPAGATE_RESULT; + +/* --- Struct forward declarations for expression --- */ + +/* --- Types for expression --- */ + +/*! + * A borrowed opaque handle to a node of a bound expression tree. Read-only and owned by the engine: valid only for the + * duration of the callback that handed it out, and never destroyed by the caller. Child nodes borrowed via + * `duckdb_v2_expression_get_child()` share their parent's lifetime. + */ +typedef struct _duckdb_v2_expression { + void *internal_ptr; +} * duckdb_v2_expression_handle; + +/* --- Constants for expression --- */ + +/* --- Function pointer typedefs for expression --- */ + +/* --- Functions for expression --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. + * Returns the type of an expression node. + * + * The type decides which of the type-specific accessors apply, and what the node's children mean; see + * `EXPRESSION_TYPE`. A node of a type this API does not model reports `EXPRESSION_TYPE_INVALID`. * * history: * - unstable: v2.0.0 * - * @param info The batch size info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param expression The expression node. + * @param type Receives the node type. * @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_copy_to_batch_size_get_user_data(duckdb_v2_copy_to_batch_size_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_type(duckdb_v2_expression_handle expression, + DUCKDB_V2_EXPRESSION_TYPE *type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's `COPY ... TO` bind callback. + * Returns the logical type the expression node evaluates to. + * + * For a cast this is the target type. The returned type is owned by the caller and must be destroyed via + * `duckdb_v2_logical_type_destroy()`. * * history: * - unstable: v2.0.0 * - * @param info The batch size info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param expression The expression node. + * @param type Receives the owned logical type. * @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_copy_to_batch_size_get_bind_data(duckdb_v2_copy_to_batch_size_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_return_type(duckdb_v2_expression_handle expression, + duckdb_v2_logical_type_handle *type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the number of rows a batch should carry, as the target the engine cuts batches at. The batch size callback must - * set this to a value greater than 0; the statement fails otherwise. DuckDB defines the `BATCH_SIZE` on omission of - * calling the function. + * Returns the number of child nodes of an expression node. + * + * Works for every node type, including `EXPRESSION_TYPE_INVALID`. Constants, parameters and column references have no + * children. * * history: * - unstable: v2.0.0 * - * @param info The batch size info handle. - * @param rows The number of rows a batch should carry. Must be greater than 0. + * @param expression The expression node. + * @param count Receives the number of children. * @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_copy_to_batch_size_set_target(duckdb_v2_copy_to_batch_size_info_handle info, - idx_t rows, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_child_count(duckdb_v2_expression_handle expression, idx_t *count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. + * Retrieves a child node of an expression node by index. + * + * Fails if the index is out of bounds. Children are ordered as the node type describes (see `EXPRESSION_TYPE`). The + * child is borrowed and shares the lifetime of its parent. * * history: * - unstable: v2.0.0 * - * @param info The init info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param expression The expression node. + * @param index The index of the child to retrieve. + * @param child Receives the borrowed child node. * @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_copy_to_init_get_user_data(duckdb_v2_copy_to_init_info_handle info, void **data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_child(duckdb_v2_expression_handle expression, idx_t index, + duckdb_v2_expression_handle *child, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's `COPY ... TO` bind callback. + * Returns the value of a constant node. + * + * Fails if the node is not of type `EXPRESSION_TYPE_VALUE_CONSTANT`. The returned value is owned by the caller and must + * be destroyed via `duckdb_v2_value_destroy()`. * * history: * - unstable: v2.0.0 * - * @param info The init info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param expression The constant node. + * @param value Receives the owned constant value. * @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_copy_to_init_get_bind_data(duckdb_v2_copy_to_init_info_handle info, void **data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_constant_get_value(duckdb_v2_expression_handle expression, + duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the path of the file the init callback is preparing. + * Returns the column a column reference node points at. * - * This is the path the batches of this file are to be written to, after the engine has applied its own rewrites (e.g. a - * temporary name while the file is being written, or a per-partition path). The path is borrowed and valid only for the - * duration of the callback. + * Fails if the node is not of type `EXPRESSION_TYPE_BOUND_COLUMN_REF`. The index counts the columns of the operator the + * predicate is evaluated against, which is not necessarily the full set of columns that operator can produce: a + * callback resolves it through whatever handed it the expression, e.g. + * `duckdb_v2_table_function_filter_pushdown_get_column_index()` for a filter offered to a table function. * * history: * - unstable: v2.0.0 * - * @param info The init info handle. - * @param path Receives a borrowed pointer to the file path. Valid only for the duration of the callback. - * @param path_length Receives the length of `*path` in bytes. `*path` is not guaranteed to be null-terminated. + * @param expression The column reference node. + * @param index Receives the column index. * @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_copy_to_init_get_file_path(duckdb_v2_copy_to_init_info_handle info, - const char **path, idx_t *path_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_column_ref_get_index(duckdb_v2_expression_handle expression, + idx_t *index, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the function's "init data" from the init callback. + * Returns the name of the scalar function a function node calls. * - * The init data lives for the duration of the file being written and is retrievable from the batch, flush and finalize - * callbacks of that file. Batches may be prepared by several threads at once, so the function must synchronize its own - * access to it from the batch callback. The opaque handle bundles the pointer with an optional destructor, invoked when - * the file is done with the data. + * Applies to `EXPRESSION_TYPE_BOUND_FUNCTION` and to the node types that are function calls underneath: the + * comparisons, `EXPRESSION_TYPE_COMPARE_BETWEEN` and `EXPRESSION_TYPE_OPERATOR_CAST`. Fails for any other node type. + * For a comparison the name is its operator, e.g. `<`; for `BETWEEN` and casts it is an internal name, so dispatch on + * the type rather than the name for those. The name is borrowed and shares the lifetime of the node. * * history: * - unstable: v2.0.0 * - * @param info The init info handle. - * @param data Opaque handle bundling the init data pointer plus an optional destructor. + * @param expression The function node. + * @param name Receives a borrowed pointer to the function name. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @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_copy_to_init_set_init_data(duckdb_v2_copy_to_init_info_handle info, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_function_get_name(duckdb_v2_expression_handle expression, + const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. + * Returns the qualified name of the scalar function a function node calls. + * + * Applies to the same node types as `duckdb_v2_expression_function_get_name()`, and fails for any other. The name is + * qualified with the catalog and schema the function was resolved in, where known. The returned name is owned by the + * caller and must be destroyed via `duckdb_v2_qname_destroy()`. * * history: * - unstable: v2.0.0 * - * @param info The batch info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param expression The function node. + * @param name Receives the owned qualified name. * @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_copy_to_batch_get_user_data(duckdb_v2_copy_to_batch_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_function_get_qname(duckdb_v2_expression_handle expression, + duckdb_v2_qname_handle *name, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's `COPY ... TO` bind callback. + * Returns whether a cast node is a regular `CAST` or a `TRY_CAST`. * - * history: - * - unstable: v2.0.0 + * Fails if the node is not of type `EXPRESSION_TYPE_OPERATOR_CAST`. A `TRY_CAST` yields NULL for a value it cannot + * convert where a regular `CAST` would fail the query. * - * @param info The batch info handle. - * @param data Receives the bind data pointer, or null if none was set. + * history: + * - unstable: v2.0.0 + * + * @param expression The cast node. + * @param mode Receives the cast mode. * @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_copy_to_batch_get_bind_data(duckdb_v2_copy_to_batch_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_cast_get_mode(duckdb_v2_expression_handle expression, + DUCKDB_V2_CAST_MODE *mode, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the init data set by the function's `COPY ... TO` init callback for the file this batch belongs to. + * Checks a predicate over one column against the statistics of that column (`ExpressionFilter::CheckStatistics`): the + * statistics of the column are propagated through the expression - comparisons, conjunctions, IS NULL, IN, casts and + * the functions the engine knows the statistics of - to find out whether every row the statistics describe passes the + * predicate, none does, or nothing can be told. A table function uses it to skip a row group (or a file) whose + * statistics, built with `duckdb_v2_stats_create()`, make a pushed-down filter it did not take over false for every + * row. Every column reference of the predicate stands for the column described by `stats`. * * history: * - unstable: v2.0.0 * - * @param info The batch info handle. - * @param data Receives the init data pointer, or null if none was set. + * @param context The context of the query; the statistics of function calls in the predicate are derived through it. + * @param expression The predicate: a boolean expression over one column, referenced by its column references. + * @param stats The statistics of that column over the rows in question. + * @param result Receives what the statistics decide about the predicate. * @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_copy_to_batch_get_init_data(duckdb_v2_copy_to_batch_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_check_statistics(duckdb_v2_context_handle context, + duckdb_v2_expression_handle expression, + duckdb_v2_stats_handle stats, + DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, + duckdb_v2_error_info_handle *err); #endif +/* --- Struct definitions for expression --- */ + +/* ============================================================================ + * MODULE: log sink + * ============================================================================ */ + +/* --- Enums for log sink --- */ + +//! The scope a log entry was written in, which decides which of its ids are present. +typedef enum DUCKDB_V2_LOG_SCOPE { + //! Written for the database as a whole, carrying no connection, transaction or query id. + DUCKDB_V2_LOG_SCOPE_DATABASE = 10, + + //! Written by a connection, carrying its connection id and, inside one, the transaction and query ids. + DUCKDB_V2_LOG_SCOPE_CONNECTION = 20, + + //! Written by a thread executing a query, carrying the thread id next to the connection's ids. + DUCKDB_V2_LOG_SCOPE_THREAD = 30, + DUCKDB_V2_LOG_SCOPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_LOG_SCOPE; + +/* --- Struct forward declarations for log sink --- */ + +/* --- Types for log sink --- */ + +/*! + * An owned opaque handle to a log sink being built. Created with `duckdb_v2_log_sink_create()`, configured with + * `duckdb_v2_log_sink_set_name()`, `duckdb_v2_log_sink_set_write_callback()` and the other setters, made available with + * `duckdb_v2_instance_register_log_sink()` or `duckdb_v2_extension_register_log_sink()`, and destroyed with + * `duckdb_v2_log_sink_destroy()`. + */ +typedef struct _duckdb_v2_log_sink { + void *internal_ptr; +} * duckdb_v2_log_sink_handle; + +/*! + * A borrowed opaque handle to the context of a log entry, received by a log sink's write callback next to the entry + * itself, and valid only for the duration of that call. Read the ids `duckdb_logs` reports for the entry through its + * getters, e.g. `duckdb_v2_log_sink_write_info_get_connection_id()`. + */ +typedef struct _duckdb_v2_log_sink_write_info { + void *internal_ptr; +} * duckdb_v2_log_sink_write_info_handle; + +/*! + * A borrowed opaque handle received by a log sink's flush callback, and valid only for the duration of that call. It + * carries nothing yet. + */ +typedef struct _duckdb_v2_log_sink_flush_info { + void *internal_ptr; +} * duckdb_v2_log_sink_flush_info_handle; + +/* --- Constants for log sink --- */ + +/* --- Function pointer typedefs for log sink --- */ + +typedef void (*duckdb_v2_log_sink_write_callback_fn)(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); + +typedef void (*duckdb_v2_log_sink_flush_callback_fn)(duckdb_v2_log_sink_flush_info_handle info, void *user_data, + duckdb_v2_error_info_handle *err); + +/* --- Functions for log sink --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Takes ownership of the rows of the batch to prepare. + * Creates a new log sink through a factory. * - * The collection holds one column per column reported by `duckdb_v2_copy_to_bind_get_column_count()`, in the same - * order, and can be scanned with `duckdb_v2_column_data_collection_scan()`. The batch can only be taken once: a second - * call fails. Once taken, the caller owns the collection and must destroy it via - * `duckdb_v2_column_data_collection_destroy()`, e.g. by keeping it as the batch data with that destructor. A batch that - * is never taken is destroyed when the callback returns. + * The log sink starts out empty: configure it with the setter functions, then make it available with + * `duckdb_v2_instance_register_log_sink()` or `duckdb_v2_extension_register_log_sink()`. The caller owns the returned + * handle and must destroy it with `duckdb_v2_log_sink_destroy()`, also after registration. + * + * The log sink can only be registered on the instance the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param info The batch info handle. - * @param collection Receives the collection holding the rows of the batch. Owned by the caller; destroy via - * `duckdb_v2_column_data_collection_destroy()`. + * @param factory The factory to create the log sink through. + * @param sink On success, receives the newly created log sink. Owned by the caller. * @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_copy_to_batch_take_input(duckdb_v2_copy_to_batch_info_handle info, - duckdb_v2_column_data_collection_handle *collection, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_create(duckdb_v2_factory_handle factory, + duckdb_v2_log_sink_handle *sink, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the prepared "batch data" from the batch callback. + * Sets the name the logging configuration refers to the log sink by. * - * The batch data is the prepared form of the batch and is handed to the flush callback via - * `duckdb_v2_copy_to_flush_get_batch_data()`. The opaque handle bundles the pointer with an optional destructor, - * invoked once the batch has been flushed. + * Names are matched case-insensitively. The name is borrowed and copied. Calling this again replaces the previous name. + * A name must be set before registration. * * history: * - unstable: v2.0.0 * - * @param info The batch info handle. - * @param data Opaque handle bundling the batch data pointer plus an optional destructor. + * @param sink The log sink to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @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_copy_to_batch_set_batch_data(duckdb_v2_copy_to_batch_info_handle info, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_name(duckdb_v2_log_sink_handle sink, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. + * Sets arbitrary user data on the log sink. + * + * Associates an opaque pointer with the sink, handed to its write and flush callbacks. The opaque handle bundles the + * pointer with an optional destructor, invoked when the data is no longer needed: when the instance is destroyed if the + * sink was registered, else when the log sink handle is. * * history: * - unstable: v2.0.0 * - * @param info The flush info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param sink The log sink to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. * @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_copy_to_flush_get_user_data(duckdb_v2_copy_to_flush_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_user_data(duckdb_v2_log_sink_handle sink, duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's `COPY ... TO` bind callback. + * Sets the write callback of the log sink, invoked for every entry the logging configuration directs to the sink. + * + * The callback must return quickly, must be safe to run concurrently and on any thread, and must not log or change the + * logging configuration. A write callback must be set before registration. * * history: * - unstable: v2.0.0 * - * @param info The flush info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param sink The log sink to set the write callback of. + * @param callback The write callback to set. * @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_copy_to_flush_get_bind_data(duckdb_v2_copy_to_flush_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_write_callback(duckdb_v2_log_sink_handle sink, + duckdb_v2_log_sink_write_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the init data set by the function's `COPY ... TO` init callback for the file this batch belongs to. + * Sets the optional flush callback of the log sink, invoked when DuckDB flushes its log, so entries the sink holds on + * to can be written out. When DuckDB flushes is up to DuckDB; entries still held when the instance is destroyed are for + * the user data's destructor to write out. + * + * Like the write callback, it must be safe to run on any thread, and must not log or change the logging configuration. * * history: * - unstable: v2.0.0 * - * @param info The flush info handle. - * @param data Receives the init data pointer, or null if none was set. + * @param sink The log sink to set the flush callback of. + * @param callback The flush callback to set. * @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_copy_to_flush_get_init_data(duckdb_v2_copy_to_flush_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_flush_callback(duckdb_v2_log_sink_handle sink, + duckdb_v2_log_sink_flush_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the batch data set by the function's batch callback for the batch being flushed. + * Retrieves the id of the connection that wrote the entry, as `duckdb_logs` reports it. An entry written for the + * database as a whole has none: `present` then receives false and `id` is left untouched. * * history: * - unstable: v2.0.0 * - * @param info The flush info handle. - * @param data Receives the batch data pointer, or null if none was set. + * @param info The write info handle of the entry. + * @param id Receives the connection id, if present. + * @param present Receives whether the entry has a connection id. * @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_copy_to_flush_get_batch_data(duckdb_v2_copy_to_flush_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_connection_id(duckdb_v2_log_sink_write_info_handle info, + idx_t *id, bool *present, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. + * Retrieves the id of the transaction the entry was written in, as `duckdb_logs` reports it. An entry written outside a + * transaction has none: `present` then receives false and `id` is left untouched. * * history: * - unstable: v2.0.0 * - * @param info The finalize info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param info The write info handle of the entry. + * @param id Receives the transaction id, if present. + * @param present Receives whether the entry has a transaction id. * @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_copy_to_finalize_get_user_data(duckdb_v2_copy_to_finalize_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_transaction_id(duckdb_v2_log_sink_write_info_handle info, + idx_t *id, bool *present, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's `COPY ... TO` bind callback. + * Retrieves the id of the query the entry was written for, as `duckdb_logs` reports it. An entry written outside a + * query has none: `present` then receives false and `id` is left untouched. * * history: * - unstable: v2.0.0 * - * @param info The finalize info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param info The write info handle of the entry. + * @param id Receives the query id, if present. + * @param present Receives whether the entry has a query id. * @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_copy_to_finalize_get_bind_data(duckdb_v2_copy_to_finalize_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_query_id(duckdb_v2_log_sink_write_info_handle info, + idx_t *id, bool *present, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the init data set by the function's `COPY ... TO` init callback for the file being finalized. + * Retrieves the id of the thread that wrote the entry, as `duckdb_logs` reports it. Only an entry written in the thread + * scope has one: otherwise `present` receives false and `id` is left untouched. The id identifies the thread that + * logged, which need not be the thread the write callback runs on. * * history: * - unstable: v2.0.0 * - * @param info The finalize info handle. - * @param data Receives the init data pointer, or null if none was set. + * @param info The write info handle of the entry. + * @param id Receives the thread id, if present. + * @param present Receives whether the entry has a thread id. * @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_copy_to_finalize_get_init_data(duckdb_v2_copy_to_finalize_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_thread_id(duckdb_v2_log_sink_write_info_handle info, + idx_t *id, bool *present, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the bind callback of the `COPY ... FROM` side. + * Registers the log sink on the instance, making it available to the logging configuration under its name. * - * The bind callback is invoked during query planning for each `COPY ... FROM` statement that uses the function. It can - * read the path of the file to read and the statement's options, inspect the names and types of the columns the target - * table expects, hint at the number of rows the read will produce, and set "bind data" that is shared with the other - * `COPY ... FROM` callbacks. The columns are fixed by the target table: the function must produce them as they are. A - * bind callback must be set for the `COPY ... FROM` side to be registered. + * Registering does not direct any entries to the sink by itself; the logging configuration does. Registration is not + * transactional, requires a name and a write callback, and fails when the name is taken: by a sink DuckDB provides + * itself, such as `memory`, `stdout` or `file`, or by a sink registered before. The log sink must have been created + * through a factory of the same instance. Its user data passes to the registered sink. The caller still owns the handle + * after registration and must destroy it with `duckdb_v2_log_sink_destroy()`, which does not affect the registered + * sink. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. + * @param instance The instance to register on. + * @param sink The log sink to register. * @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_copy_from_set_bind_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_from_bind_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_register_log_sink(duckdb_v2_instance_handle instance, + duckdb_v2_log_sink_handle sink, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional global init callback of the `COPY ... FROM` side. + * Registers the log sink on the loading extension's instance, making it available to the logging configuration under + * its name. * - * The global init callback is invoked once per statement, at the start of execution. It can set "global state" shared - * by every thread reading the file, and declare how many threads may read it in parallel via - * `duckdb_v2_copy_from_init_global_set_max_threads()`. + * Use this from the extension's load callback. Registration follows the rules of + * `duckdb_v2_instance_register_log_sink()`. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. + * @param extension The loading extension. + * @param sink The log sink to register. * @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_copy_from_set_init_global_callback( - duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_init_global_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_log_sink(duckdb_v2_extension_handle extension, + duckdb_v2_log_sink_handle sink, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional local init callback of the `COPY ... FROM` side. + * Destroys the log sink, releasing its resources. * - * The local init callback is invoked once per thread that will read the file. It can set worker-local "local state", - * retrievable from the exec callback, typically derived from the shared global state. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered sink. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param sink The log sink to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_set_init_local_callback( - duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_init_local_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_destroy(duckdb_v2_log_sink_handle *sink); #endif +/* --- Struct definitions for log sink --- */ + +/* ============================================================================ + * MODULE: logical_type + * ============================================================================ */ + +/* --- Enums for logical_type --- */ + +/*! + * Logical type identifier. The values are the same integers DuckDB uses internally, so round-tripping is lossless. The + * bind- and UDF-only ids (UNKNOWN, ANY, TEMPLATE) appear here for completeness; they do not show up in result column + * types in practice. + */ +typedef enum DUCKDB_V2_LOGICAL_TYPE_ID { + //! Invalid / unset. + DUCKDB_V2_LOGICAL_TYPE_ID_INVALID = 0, + + //! NULL constant type. + DUCKDB_V2_LOGICAL_TYPE_ID_SQLNULL = 1, + + //! Unknown — used for unresolved parameter expressions. + DUCKDB_V2_LOGICAL_TYPE_ID_UNKNOWN = 2, + + //! ANY — used for functions that accept any type. + DUCKDB_V2_LOGICAL_TYPE_ID_ANY = 3, + + //! A type carried as a value (type parameters). Values of this type are built via value_create_type. + DUCKDB_V2_LOGICAL_TYPE_ID_TYPE = 6, + DUCKDB_V2_LOGICAL_TYPE_ID_BOOLEAN = 10, + DUCKDB_V2_LOGICAL_TYPE_ID_TINYINT = 11, + DUCKDB_V2_LOGICAL_TYPE_ID_SMALLINT = 12, + DUCKDB_V2_LOGICAL_TYPE_ID_INTEGER = 13, + DUCKDB_V2_LOGICAL_TYPE_ID_BIGINT = 14, + + //! 32-bit days since epoch. + DUCKDB_V2_LOGICAL_TYPE_ID_DATE = 15, + + //! 64-bit microseconds since midnight. + DUCKDB_V2_LOGICAL_TYPE_ID_TIME = 16, + + //! 64-bit seconds since epoch. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_SEC = 17, + + //! 64-bit milliseconds since epoch. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_MS = 18, + + //! 64-bit microseconds since epoch. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP = 19, + + //! 64-bit nanoseconds since epoch. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_NS = 20, + + //! Decimal with width and scale parameters. + DUCKDB_V2_LOGICAL_TYPE_ID_DECIMAL = 21, + DUCKDB_V2_LOGICAL_TYPE_ID_FLOAT = 22, + DUCKDB_V2_LOGICAL_TYPE_ID_DOUBLE = 23, + DUCKDB_V2_LOGICAL_TYPE_ID_VARCHAR = 25, + DUCKDB_V2_LOGICAL_TYPE_ID_BLOB = 26, + DUCKDB_V2_LOGICAL_TYPE_ID_INTERVAL = 27, + DUCKDB_V2_LOGICAL_TYPE_ID_UTINYINT = 28, + DUCKDB_V2_LOGICAL_TYPE_ID_USMALLINT = 29, + DUCKDB_V2_LOGICAL_TYPE_ID_UINTEGER = 30, + DUCKDB_V2_LOGICAL_TYPE_ID_UBIGINT = 31, + + //! 64-bit microseconds since epoch, timezone-aware. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_TZ = 32, + + //! 64-bit nanoseconds since epoch, timezone-aware. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_TZ_NS = 33, + + //! 64-bit microseconds since midnight + 32-bit offset. + DUCKDB_V2_LOGICAL_TYPE_ID_TIME_TZ = 34, + + //! 64-bit nanoseconds since midnight. + DUCKDB_V2_LOGICAL_TYPE_ID_TIME_NS = 35, + DUCKDB_V2_LOGICAL_TYPE_ID_BIT = 36, + + //! Arbitrary-precision integer (VARINT-encoded). + DUCKDB_V2_LOGICAL_TYPE_ID_BIGNUM = 39, + DUCKDB_V2_LOGICAL_TYPE_ID_UHUGEINT = 49, + DUCKDB_V2_LOGICAL_TYPE_ID_HUGEINT = 50, + DUCKDB_V2_LOGICAL_TYPE_ID_UUID = 54, + + //! Geometry (spatial extension). + DUCKDB_V2_LOGICAL_TYPE_ID_GEOMETRY = 60, + + //! Geography (spatial extension); like GEOMETRY, but with spherical edges. + DUCKDB_V2_LOGICAL_TYPE_ID_GEOGRAPHY = 61, + DUCKDB_V2_LOGICAL_TYPE_ID_STRUCT = 100, + DUCKDB_V2_LOGICAL_TYPE_ID_LIST = 101, + DUCKDB_V2_LOGICAL_TYPE_ID_MAP = 102, + DUCKDB_V2_LOGICAL_TYPE_ID_ENUM = 104, + DUCKDB_V2_LOGICAL_TYPE_ID_UNION = 107, + DUCKDB_V2_LOGICAL_TYPE_ID_ARRAY = 108, + DUCKDB_V2_LOGICAL_TYPE_ID_VARIANT = 109, + + //! Unnamed struct; shares the physical representation of STRUCT. + DUCKDB_V2_LOGICAL_TYPE_ID_TUPLE = 110, + DUCKDB_V2_LOGICAL_TYPE_ID_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_LOGICAL_TYPE_ID; + +/* --- Struct forward declarations for logical_type --- */ + +/* --- Types for logical_type --- */ + +/* --- Constants for logical_type --- */ + +/* --- Function pointer typedefs for logical_type --- */ + +/* --- Functions for logical_type --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the exec callback of the `COPY ... FROM` side. + * Creates a logical type from a type id plus value parameters. + * + * The id-keyed twin of factory_create_type_from_name: the type id names the kind, and the parameters bind it. With + * param_count 0 it instantiates a primitive directly, without touching the catalog: BOOLEAN, TINYINT..BIGINT, + * UTINYINT..UBIGINT, HUGEINT, UHUGEINT, FLOAT, DOUBLE, DATE, every TIME and TIMESTAMP variant, INTERVAL, VARCHAR, BLOB, + * BIT, BIGNUM, and UUID. ANY is accepted as well. * - * The exec callback implements the read: it is invoked repeatedly during query execution and writes the next batch of - * rows to the output chunk, until it produces an empty batch to signal the end of the read. An exec callback must be - * set for the `COPY ... FROM` side to be registered. + * ANY is a function-signature wildcard, constructible here so it can be passed to the function parameter and varargs + * setters, as a fixed-arity ANY parameter or an ANY varargs type. Data-creating surfaces reject it: value and data + * chunk creation, scalar and aggregate return types, table function result columns, cast source and target types, and + * custom type registration. + * + * With parameters, the id resolves to its canonical built-in type and binds through the same constructors as + * factory_create_type_from_name, so the parameterized kinds construct here too: decimal(width, scale); list(T); + * array(T, size); map(K, V); struct(fields); union(members); enum(entries); and varchar with a named "collation" + * parameter. Parameters are (name, value) pairs in two parallel arrays, exactly as for factory_create_type_from_name. + * + * Returns ERROR_INPUT_INVALID when param_count is 0 and the id needs parameters (DECIMAL, LIST, STRUCT, TUPLE, MAP, + * ARRAY, UNION, ENUM, VARIANT, GEOMETRY, GEOGRAPHY), for the bind-time-only ids (SQLNULL, UNKNOWN), for TYPE — + * construct that via factory_create_type_from_text — and for INVALID. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to resolve the type in. + * @param type_id The type id to instantiate. + * @param param_names Optional. An array of param_count parameter names; an empty entry (NULL or zero length) is + * positional. Pass NULL for all-positional parameters. + * @param param_names_lengths Byte lengths of the entries in `param_names`; element i is the length of `param_names[i]`. + * May be NULL only when `param_names` is NULL. + * @param param_values An array of param_count parameter values. Borrowed (copied in). Pass NULL when param_count is 0. + * @param param_count The number of parameters. 0 instantiates a parameterless primitive. + * @param out_type Receives the new logical type handle. + * @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_copy_from_set_exec_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_from_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id( + duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char *const *param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional progress callback of the `COPY ... FROM` side. + * Creates a logical type from a type name plus value parameters. * - * The progress callback is invoked on demand during execution to report how far the read has advanced, which the engine - * surfaces as the query's progress. It is invoked concurrently with the exec callback, so it must read the global state - * in a thread-safe way. + * The generic constructor: resolves the name in the factory's catalog and binds it with the given parameters, exactly + * as SQL binds a type expression. Built-in parameterized kinds and registered extension types construct through this + * same call. + * + * An unqualified name is resolved along the search path first and then in the system catalog, which is where the + * 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, + * as named or all-positional TYPE values); union(members, as named TYPE values); enum(entries, as VARCHAR values); and + * varchar with a named "collation" VARCHAR parameter. + * + * A name that resolves to a type with no bind function takes no parameters, and passing any fails. Bind errors — + * unknown name, wrong parameter count or types — surface from the call. + * + * Resolves in the scope of the factory: a connection's or callback's factory reaches the catalog, an instance's factory + * knows only the built-in types. A connection's factory looks up catalog types in the connection's transaction, or in + * one of its own when none is open. Through an instance's factory, only an unqualified built-in name resolves. + * + * The returned logical type is caller-owned and must be destroyed via logical_type_destroy. A type resolved from the + * catalog shares database-owned storage, such as an ENUM dictionary, so destroy it before closing the database. This is + * the inverse of logical_type_get_param_count / logical_type_get_param. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to resolve the type in. + * @param name The type name to resolve. Parts are matched case-insensitively; qualify it to name a type in a particular + * catalog or schema. + * @param param_names Optional. An array of param_count parameter names; an empty entry (NULL or zero length) is + * positional. Pass NULL for all-positional parameters. + * @param param_names_lengths Byte lengths of the entries in `param_names`; element i is the length of `param_names[i]`. + * May be NULL only when `param_names` is NULL. + * @param param_values An array of param_count parameter values. Borrowed (copied in). Pass NULL when param_count is 0. + * @param param_count The number of parameters. + * @param out_type Receives the new logical type handle. + * @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_copy_from_set_progress_callback( - duckdb_v2_copy_function_handle function, duckdb_v2_copy_from_progress_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_name( + duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char *const *param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. + * Creates a logical type by parsing SQL text. + * + * Parses a SQL type expression and returns the bound logical type. It accepts primitives ("INTEGER"), parameterized + * kinds ("DECIMAL(18,3)", "INTEGER[]", "STRUCT(a INTEGER, b VARCHAR)", "MAP(VARCHAR, INTEGER)", "INTEGER[3]", "UNION(i + * INTEGER, s VARCHAR)", "ENUM('a', 'b')"), and catalog-registered type names, both user-defined and from extensions. A + * catalog type name binds to its structural type, and the name is not preserved as an alias. Names are + * case-insensitive. Parse and bind errors surface from the call. + * + * Resolves in the scope of the factory: a connection's or callback's factory reaches the catalog, an instance's factory + * knows only the built-in types. A connection's factory looks up catalog types in the connection's transaction, or in + * one of its own when none is open. Text naming only built-in types never touches the catalog. + * + * The returned logical type is caller-owned and must be destroyed via logical_type_destroy. A type resolved from the + * catalog shares database-owned storage, such as an ENUM dictionary, so destroy it before closing the database. This is + * the inverse of logical_type_to_text for every constructible kind. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to resolve the type in. + * @param text The SQL type expression to parse. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. + * @param out_type Receives the new logical type handle. + * @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_copy_from_bind_get_user_data(duckdb_v2_copy_from_bind_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_text(duckdb_v2_factory_handle factory, const char *text, + idx_t text_length, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the function's "bind data" from the bind callback. + * Creates a copy of a logical type. * - * The bind data is stored with the bound statement and retrievable from the other callbacks of the same side. The - * opaque handle bundles the pointer with an optional destructor, invoked when the bind data is no longer needed, and an - * optional equality callback used when comparing two bound statements; without one, pointer equality is used. + * On success, writes the new caller-owned handle into *out_type; destroy it via logical_type_destroy. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param data Opaque handle bundling the bind data pointer plus optional destructor and equality callbacks. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param type The logical type to copy. + * @param out_type Receives the new logical type handle. + * @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_copy_from_bind_set_bind_data(duckdb_v2_copy_from_bind_info_handle info, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_copy(duckdb_v2_logical_type_handle type, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the path the `COPY ... FROM` statement reads from, as written in the statement. + * Destroys a logical type handle. * - * The engine does not expand globs or check that the file exists; both are left to the function. The path is borrowed - * and valid only for the duration of the callback. + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. On success the slot is set to nullptr. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param path Receives a borrowed pointer to the file path. Valid only for the duration of the callback. - * @param path_length Receives the length of `*path` in bytes. `*path` is not guaranteed to be null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param type The logical type to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_file_path(duckdb_v2_copy_from_bind_info_handle info, - const char **path, idx_t *path_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_destroy(duckdb_v2_logical_type_handle *type); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns the target table expects, i.e. the columns every batch the exec callback produces must - * carry, in this order. + * Compares two logical types for deep equality. * - * Valid indices for `duckdb_v2_copy_from_bind_get_column_type()` and `duckdb_v2_copy_from_bind_get_column_name()` are - * [0, count). + * Two types are equal when they agree in kind and in every parameter, recursively. DECIMAL(10, 2) equals DECIMAL(10, + * 2), but not DECIMAL(10, 3) and not FLOAT; two STRUCTs are equal when they have the same field names in the same order + * and equal field types. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param count Receives the number of columns. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param left The first logical type. + * @param right The second logical type. + * @param result Receives the result of the comparison. + * @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_copy_from_bind_get_column_count(duckdb_v2_copy_from_bind_info_handle info, - idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_is_equal(duckdb_v2_logical_type_handle left, + duckdb_v2_logical_type_handle right, bool *result, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the type of the column at the given index. - * - * Fails if the index is out of bounds. The returned type is owned by the caller and must be destroyed via - * `duckdb_v2_logical_type_destroy()`. + * Returns the logical type id. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param index The index of the column to get the type of. - * @param type Receives the column type. Owned by the caller; destroy via `duckdb_v2_logical_type_destroy()`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param type The logical type. + * @param out_id Receives the type id. + * @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_copy_from_bind_get_column_type(duckdb_v2_copy_from_bind_info_handle info, - idx_t index, duckdb_v2_logical_type_handle *type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_id(duckdb_v2_logical_type_handle type, + DUCKDB_V2_LOGICAL_TYPE_ID *out_id, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the name of the column at the given index. + * Borrows the logical type's name. * - * Fails if the index is out of bounds. The name is borrowed and valid only for the duration of the callback. + * The alias when one is set — an extension or user-defined name such as "POINT_2D" — otherwise the canonical name of + * the type id, such as "INTEGER", "DECIMAL", or "TIMESTAMP WITH TIME ZONE". Never the empty view. This is exactly the + * name vocabulary create_type_from_name accepts. The view is valid until the logical type is destroyed; a canonical + * name points at static storage. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param index The index of the column to get the name of. - * @param name Receives a borrowed pointer to the column name. Valid only for the duration of the callback. - * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param type The logical type. + * @param out_name Receives a borrowed pointer to the name (alias when set, else the id's canonical name). + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. + * @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_copy_from_bind_get_column_name(duckdb_v2_copy_from_bind_info_handle info, - idx_t index, const char **name, - idx_t *name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_name(duckdb_v2_logical_type_handle type, const char **out_name, + idx_t *out_name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of options the `COPY` statement passed to the function. + * Renders a logical type as SQL text. * - * Every option other than `FORMAT` is included. Valid indices for `duckdb_v2_copy_from_bind_get_option_name()` and - * `duckdb_v2_copy_from_bind_get_option_value()` are [0, count). The options are ordered by name. + * An aliased type renders as its alias, and create_type_from_text resolves that spelling only when the name is + * registered in the factory's catalog. The text round-trips through create_type_from_text for every constructible kind, + * with one exception: ANY renders as "ANY", but create_type_from_text cannot parse it back, since ANY is a signature + * wildcard rather than a parseable SQL type. + * + * Writes into a caller-supplied buffer, so nothing is allocated on the caller's behalf and nothing has to be freed. + * Pass out_text = NULL to size the buffer without rendering into it: out_length then receives the length, and + * out_capacity is ignored. With out_text != NULL, out_capacity must be at least out_length + 1, or the call returns + * ERROR_INPUT_OBJECT_SIZE with out_length set to the required length and out_text left untouched. + * + * out_length never counts the terminator, but a successful write always appends one, so the buffer is usable as a C + * string. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param count Receives the number of options. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param type The logical type. + * @param out_text Caller-owned buffer receiving the text plus a null terminator, or NULL to only report the required + * length in out_length. + * @param out_capacity Bytes available in out_text, terminator included. Ignored when out_text is NULL. + * @param out_length Receives the text length excluding the null terminator — written on success and on + * ERROR_INPUT_OBJECT_SIZE. + * @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_copy_from_bind_get_option_count(duckdb_v2_copy_from_bind_info_handle info, - idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_to_text(duckdb_v2_logical_type_handle type, char *out_text, + idx_t out_capacity, idx_t *out_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the name of the option at the given index. + * Returns the number of value parameters of a logical type. * - * Option names are SQL identifiers, matched case-insensitively. Fails if the index is out of bounds. The name is - * borrowed and valid only for the duration of the callback. + * The inspection dual of create_type_from_name: these are the parameters that reconstruct the type through it. Per + * kind: DECIMAL 2 (width, scale); LIST 1 (element type); ARRAY 2 (element type, size); MAP 2 (key type, value type); + * STRUCT and TUPLE one per field; UNION one per member; ENUM one per dictionary entry; VARCHAR 1 when a collation is + * set, else 0; GEOMETRY and GEOGRAPHY 1 when a coordinate system is set, else 0; everything else 0. A bound type + * reports only what it actually carries, so a bind-time modifier that is not retained — an ignored VARCHAR length, say + * — does not reappear. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param index The index of the option to get the name of. - * @param name Receives a borrowed pointer to the option name. Valid only for the duration of the callback. - * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param type The logical type. + * @param out_count Receives the number of parameters. + * @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_copy_from_bind_get_option_name(duckdb_v2_copy_from_bind_info_handle info, - idx_t index, const char **name, - idx_t *name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param_count(duckdb_v2_logical_type_handle type, + idx_t *out_count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the value of the option at the given index. + * Returns one value parameter of a logical type. * - * An option written with a single value (e.g. `DELIM ','`) yields that value. An option written as a bare name (e.g. - * `HEADER`) yields the BOOLEAN `true`. An option written with a parenthesized list (e.g. `KEYS (a, b)`) yields a tuple: - * an unnamed STRUCT with one field per element, in order. Fails if the index is out of bounds. The returned value is - * owned by the caller and must be destroyed via `duckdb_v2_value_destroy()`. + * out_name receives a borrowed view of the parameter name — a STRUCT field name, a UNION member name, "collation" — or + * an empty name for a positional parameter. A non-empty view is valid until the logical type is destroyed. out_value + * receives an owned value, destroyed via value_destroy: child types come back as TYPE values (unwrap them with + * value_get_type), DECIMAL width and scale as UINTEGER, ARRAY size as BIGINT, and ENUM dictionary entries and + * collations as VARCHAR. An out-of-range index returns ERROR_INPUT_INVALID. Each call allocates one owned value. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param index The index of the option. - * @param value Receives the option's value. Owned by the caller; destroy via `duckdb_v2_value_destroy()`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param type The logical type. + * @param index The parameter index, in [0, param_count). + * @param out_name Receives a borrowed pointer to the parameter name, or NULL with a zero length for a positional + * parameter. + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. + * @param out_value Receives the owned parameter 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_copy_from_bind_get_option_value(duckdb_v2_copy_from_bind_info_handle info, - idx_t index, duckdb_v2_value_handle *value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param(duckdb_v2_logical_type_handle type, idx_t index, + const char **out_name, idx_t *out_name_length, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports the estimated number of rows the read will produce. + * Creates a logical type that is an alias of another logical type. * - * The estimate is a hint for the optimizer, not a limit: producing a different number of rows is not an error. Without - * it, the optimizer falls back on its own defaults. + * The alias keeps the base type's internal representation, so executing against it needs no special handling, while + * remaining logically distinct from the base type. Intended for custom type bind callbacks, where both the base type + * and the name come from the bind info. + * + * The alias is not registered anywhere, so this works through any factory. An empty alias name returns + * ERROR_INPUT_INVALID. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param cardinality The estimated number of rows. - * @param is_exact Whether the estimate is exact, which also makes it an upper bound on the row count. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to resolve the type in. + * @param base_type The logical type to alias. Typically the base type supplied in the custom type bind info. + * @param alias_name The name for the resulting type. Typically the name of the custom type being constructed, also + * available from the bind info. + * @param alias_name_length The length of `alias_name` in bytes. `alias_name` must be valid UTF-8, need not be + * null-terminated, and may be NULL only when this is 0. + * @param out_type Receives the new type: the base type's internal representation under the given alias name. + * @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_copy_from_bind_set_cardinality(duckdb_v2_copy_from_bind_info_handle info, - idx_t cardinality, bool is_exact, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_with_alias(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle base_type, + const char *alias_name, idx_t alias_name_length, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. + * Creates the common type of a set of logical types. * - * history: - * - unstable: v2.0.0 + * The common type is the type every input implicitly casts to, resolved by the same rule a SQL list literal and + * value_create_list follow: INTEGER and BIGINT resolve to BIGINT, and DECIMAL(4,1) and DECIMAL(5,4) to DECIMAL(7,4). + * The types are combined pairwise from left to right, and the result is not guaranteed to be independent of their + * order. * - * @param info The global init info handle. - * @param data Receives the user data pointer, or null if none was set. - * @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_copy_from_init_global_get_user_data( - duckdb_v2_copy_from_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the bind data set by the function's `COPY ... FROM` bind callback. + * A connection's or a callback's factory also applies the casts that extensions registered, while an instance's factory + * knows only the built-in ones, so the two can resolve the same set differently. A single type resolves to a copy of + * itself. + * + * Returns ERROR_INPUT_INVALID for an empty set, for a NULL entry and for ANY, and ERROR_QUERY_NOT_IMPLEMENTED when the + * types have no common type. * * history: * - unstable: v2.0.0 * - * @param info The global init info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to resolve the type in. + * @param types An array of type_count logical types. Borrowed. + * @param type_count The number of types. Must be at least 1. + * @param out_type Receives the new logical type handle. + * @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_copy_from_init_global_get_bind_data( - duckdb_v2_copy_from_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_common_type(duckdb_v2_factory_handle factory, + const duckdb_v2_logical_type_handle *types, + idx_t type_count, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); +#endif + +/* --- Struct definitions for logical_type --- */ + +/* ============================================================================ + * MODULE: macro + * ============================================================================ */ + +/* --- Enums for macro --- */ + +//! The kind of a macro function, deciding how its body is read. Pass one to `duckdb_v2_macro_function_create()`. +typedef enum DUCKDB_V2_MACRO_FUNCTION_TYPE { + //! A scalar macro. The body is a single expression, and the macro is called like a scalar function. + DUCKDB_V2_MACRO_FUNCTION_TYPE_SCALAR = 0, + + //! A table macro. The body is a single SELECT query, and the macro is called like a table function. + DUCKDB_V2_MACRO_FUNCTION_TYPE_TABLE = 1, + DUCKDB_V2_MACRO_FUNCTION_TYPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_MACRO_FUNCTION_TYPE; + +/* --- Struct forward declarations for macro --- */ + +/* --- Types for macro --- */ + /*! - * Sets the function's "global state" from the global init callback. + * An owned opaque handle to a macro function being built. Created with `duckdb_v2_macro_function_create()`, configured + * with `duckdb_v2_macro_function_set_name()`, `duckdb_v2_macro_function_set_body()` and the signature obtained via + * `duckdb_v2_macro_function_get_signature()`, made available with `duckdb_v2_extension_register_macro_function()`, and + * destroyed with `duckdb_v2_macro_function_destroy()`. + */ +typedef struct _duckdb_v2_macro_function { + void *internal_ptr; +} * duckdb_v2_macro_function_handle; + +/* --- Constants for macro --- */ + +/* --- Function pointer typedefs for macro --- */ + +/* --- Functions for macro --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a new macro function through a factory. * - * The global state lives for the duration of the read and is retrievable from the local init, exec and progress - * callbacks. Every thread reading the file shares it, so the function must synchronize its own access to it. The opaque - * handle bundles the pointer with an optional destructor, invoked when the read is done with the state. + * The macro function starts out empty: configure it with the setter functions and the signature obtained via + * `duckdb_v2_macro_function_get_signature()`, then make it available with + * `duckdb_v2_extension_register_macro_function()`. The caller owns the returned handle and must destroy it with + * `duckdb_v2_macro_function_destroy()`, also after registration. + * + * The macro function can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param info The global init info handle. - * @param data Opaque handle bundling the global state pointer plus an optional destructor. + * @param factory The factory to create the macro function through. + * @param type Whether the macro is a scalar or a table macro. + * @param function On success, receives the newly created macro function. Owned by the caller. * @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_copy_from_init_global_set_global_state( - duckdb_v2_copy_from_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_create(duckdb_v2_factory_handle factory, + DUCKDB_V2_MACRO_FUNCTION_TYPE type, + duckdb_v2_macro_function_handle *function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets how many threads may read the file in parallel. + * Sets the name of the macro function, as SQL calls it. * - * Defaults to 1, a single-threaded read. The engine creates at most this many local states, and therefore runs at most - * this many exec callbacks concurrently. It is an upper bound, not a request: the engine may use fewer threads. + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param info The global init info handle. - * @param max_threads The maximum number of threads. Must be at least 1. + * @param function The macro function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @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_copy_from_init_global_set_max_threads( - duckdb_v2_copy_from_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_set_name(duckdb_v2_macro_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. + * Sets the body of the macro function, as SQL text. + * + * For a scalar macro the body is a single expression, for a table macro a single SELECT query. It refers to the + * parameters by name. The body is parsed at registration, which fails on a syntax error; names in it are resolved only + * when the macro is called, as with SQL `CREATE MACRO`. The body is borrowed and copied. Calling this again replaces + * the previous body. A body must be set before registration. * * history: * - unstable: v2.0.0 * - * @param info The local init info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param function The macro function to set the body of. + * @param body The SQL text of the body. Borrowed and copied. + * @param body_length The length of `body` in bytes. `body` need not be null-terminated and may be NULL only when this + * is 0. * @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_copy_from_init_local_get_user_data( - duckdb_v2_copy_from_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_set_body(duckdb_v2_macro_function_handle function, + const char *body, idx_t body_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's `COPY ... FROM` bind callback. + * Returns the macro function's signature so its parameters can be declared. + * + * Add parameters with `duckdb_v2_function_signature_add_parameter()`. A macro's parameters can always be passed by + * position or by name, so only `FUNCTION_PARAMETER_KIND_STANDARD` parameters are accepted; a macro has no variadic + * parameters. A parameter of type ANY is untyped, and a parameter with a default value can be omitted by a caller. A + * macro's result is decided by its body, so the signature cannot set a return type. Registration fails on a signature + * that does not follow these rules. The signature is modified in place. * * history: * - unstable: v2.0.0 * - * @param info The local init info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param function The macro function to get the signature of. + * @param sig The returned signature. Borrowed and valid for the lifetime of the macro function handle. * @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_copy_from_init_local_get_bind_data( - duckdb_v2_copy_from_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_get_signature(duckdb_v2_macro_function_handle function, + duckdb_v2_function_signature_handle *sig, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the global state set by the function's global init callback. + * Returns the documentation of the macro function so it can be filled in. * - * Shared with every other thread reading the file; access to it must be synchronized by the function. + * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with + * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified + * in place and registered with the macro function. Optional. * * history: * - unstable: v2.0.0 * - * @param info The local init info handle. - * @param data Receives the global state pointer, or null if none was set. + * @param function The macro function to get the documentation of. + * @param docs The returned documentation. Borrowed and valid for the lifetime of the macro function handle. * @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_copy_from_init_local_get_global_state( - duckdb_v2_copy_from_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_get_docs(duckdb_v2_macro_function_handle function, + duckdb_v2_function_docs_handle *docs, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the function's worker-local "local state" from the local init callback. + * Registers the macro function, making it available for use in SQL queries. * - * The local state is associated with the executing thread for the duration of the read and retrievable from the exec - * callback via `duckdb_v2_copy_from_exec_get_local_state()`. No other thread observes it, so it needs no - * synchronization. The opaque handle bundles the pointer with an optional destructor, invoked when the local state is - * no longer needed. + * The macro function is registered on the loading extension's database and attributed to the extension. Use this from + * the extension's load callback. Registration requires a name and a body that parses, and a signature that follows the + * rules of `duckdb_v2_macro_function_get_signature()`. It fails when a function of the same name already exists: a + * macro function has a single overload. The macro function must have been created through a factory of the same + * database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_macro_function_destroy()`, which does not affect the registered macro function. * * history: * - unstable: v2.0.0 * - * @param info The local init info handle. - * @param data Opaque handle bundling the local state pointer plus an optional destructor. + * @param extension The loading extension. + * @param function The macro function to register. * @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_copy_from_init_local_set_local_state( - duckdb_v2_copy_from_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_macro_function(duckdb_v2_extension_handle extension, + duckdb_v2_macro_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. + * Destroys the macro function, releasing its resources. + * + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered macro function. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param function The macro function to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_exec_get_user_data(duckdb_v2_copy_from_exec_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_destroy(duckdb_v2_macro_function_handle *function); #endif +/* --- Struct definitions for macro --- */ + +/* ============================================================================ + * MODULE: pragma + * ============================================================================ */ + +/* --- Enums for pragma --- */ + +/* --- Struct forward declarations for pragma --- */ + +/* --- Types for pragma --- */ + +/*! + * An owned opaque handle to a custom pragma function being built. Created with `duckdb_v2_pragma_function_create()`, + * configured with the setter functions (e.g. `duckdb_v2_pragma_function_set_name()`, + * `duckdb_v2_pragma_function_set_query_callback()`, etc.) and the signature obtained via + * `duckdb_v2_pragma_function_get_signature()`, made available with `duckdb_v2_connection_register_pragma_function()` or + * `duckdb_v2_extension_register_pragma_function()`, and destroyed with `duckdb_v2_pragma_function_destroy()`. + */ +typedef struct _duckdb_v2_pragma_function { + void *internal_ptr; +} * duckdb_v2_pragma_function_handle; + +/*! + * A borrowed opaque handle to the result of a pragma function's "query" callback. The query callback receives this + * handle next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments and the user data, and + * uses it to set the query to run in place of the `PRAGMA` statement. + */ +typedef struct _duckdb_v2_pragma_function_query_info { + void *internal_ptr; +} * duckdb_v2_pragma_function_query_info_handle; + +/* --- Constants for pragma --- */ + +/* --- Function pointer typedefs for pragma --- */ + +typedef void (*duckdb_v2_pragma_function_query_callback_fn)(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); + +typedef void (*duckdb_v2_pragma_function_exec_callback_fn)(duckdb_v2_function_bind_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +/* --- Functions for pragma --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's `COPY ... FROM` bind callback. + * Creates a new pragma function through a factory. + * + * The function starts out empty: configure it with the setter functions (e.g. `duckdb_v2_pragma_function_set_name()`, + * `duckdb_v2_pragma_function_set_query_callback()`, etc.) and the signature obtained via + * `duckdb_v2_pragma_function_get_signature()`, then make it available with + * `duckdb_v2_connection_register_pragma_function()` or `duckdb_v2_extension_register_pragma_function()`. The caller + * owns the returned handle and must destroy it with `duckdb_v2_pragma_function_destroy()`, also after registration. + * + * The pragma function can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param factory The factory to create the pragma function through. + * @param function On success, receives the newly created pragma function. Owned by the caller. * @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_copy_from_exec_get_bind_data(duckdb_v2_copy_from_exec_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_pragma_function_handle *function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the global state set by the function's global init callback. + * Sets the name of the pragma function, as the `PRAGMA` statement calls it. * - * Shared with every other thread reading the file; access to it must be synchronized by the function. + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the global state pointer, or null if none was set. + * @param function The function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @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_copy_from_exec_get_global_state(duckdb_v2_copy_from_exec_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_name(duckdb_v2_pragma_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the worker-local local state set by the function's local init callback. + * Returns the documentation of the function so it can be filled in. + * + * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with + * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified + * in place and registered with the function. Optional. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the local state pointer for the executing thread, or null if none was set. + * @param function The function to get the documentation of. + * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. * @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_copy_from_exec_get_local_state(duckdb_v2_copy_from_exec_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_get_docs(duckdb_v2_pragma_function_handle function, + duckdb_v2_function_docs_handle *docs, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the output chunk the exec callback must write the next batch of rows into. + * Returns the function's signature so it can be configured. * - * The chunk holds one vector per column reported by `duckdb_v2_copy_from_bind_get_column_count()`, in the same order; - * reach them with `duckdb_v2_data_chunk_get_vector()`. The chunk starts out empty on every invocation: write the rows, - * then declare how many there are with `duckdb_v2_vector_set_size()` on the first vector, which the engine takes as the - * batch's row count and propagates to the other vectors. Producing an empty batch signals the end of the read, after - * which the callback is not invoked again on that thread. Borrowed; valid only for the duration of the callback. + * Add parameters with `duckdb_v2_function_signature_add_parameter()`. A pragma produces no value, so its signature + * cannot set a return type. A signature without parameters makes a pragma called as `PRAGMA name`. The signature is + * modified in place. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param chunk Receives the borrowed output chunk to write into. + * @param function The function to get the signature of. + * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. * @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_copy_from_exec_get_output_chunk(duckdb_v2_copy_from_exec_info_handle info, - duckdb_v2_data_chunk_handle *chunk, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_get_signature(duckdb_v2_pragma_function_handle function, + duckdb_v2_function_signature_handle *sig, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. - * - * history: - * - unstable: v2.0.0 + * Sets arbitrary user data on the pragma function. * - * @param info The progress info handle. - * @param data Receives the user data pointer, or null if none was set. + * Associates an opaque pointer with the function, retrievable from the callbacks via + * `duckdb_v2_function_bind_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, invoked + * when the data is no longer needed. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. * @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_copy_from_progress_get_user_data(duckdb_v2_copy_from_progress_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_user_data(duckdb_v2_pragma_function_handle function, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's `COPY ... FROM` bind callback. + * Sets the query callback of the pragma function, making it a query pragma. + * + * The query callback is invoked before the `PRAGMA` statement is bound, and must set a SQL string through + * `duckdb_v2_pragma_function_query_set_query()`. The string is parsed and its statements run in place of the `PRAGMA` + * statement. A pragma function has either a query callback or an exec callback; registration fails when both or neither + * are set. * * history: * - unstable: v2.0.0 * - * @param info The progress info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param function The function to set the query callback of. + * @param callback The query callback to set. * @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_copy_from_progress_get_bind_data(duckdb_v2_copy_from_progress_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_query_callback( + duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_query_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the global state set by the function's global init callback. + * Sets the exec callback of the pragma function, making it an exec pragma. * - * The progress callback runs concurrently with the exec callbacks reading the file, so it must read the global state in - * a thread-safe way. + * The exec callback is invoked when the `PRAGMA` statement executes, and runs for its side effects: the statement + * produces no rows. A pragma function has either a query callback or an exec callback; registration fails when both or + * neither are set. * * history: * - unstable: v2.0.0 * - * @param info The progress info handle. - * @param data Receives the global state pointer, or null if none was set. + * @param function The function to set the exec callback of. + * @param callback The exec callback to set. * @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_copy_from_progress_get_global_state( - duckdb_v2_copy_from_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_exec_callback( + duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_exec_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports how far the read has advanced. + * Sets the SQL to run in place of the `PRAGMA` statement. * - * A fraction between 0.0 (nothing read yet) and 1.0 (done); values outside that range are clamped. A progress callback - * that returns without calling this reports no progress. + * The query may hold several statements, separated by semicolons. It is borrowed and copied. Calling this again + * replaces the previous query. The query callback must set a query. * * history: * - unstable: v2.0.0 * - * @param info The progress info handle. - * @param progress The fraction of the read that is complete, in [0.0, 1.0]. + * @param info The query info handle. + * @param query The SQL to run. Borrowed and copied. + * @param query_length The length of `query` in bytes. `query` need not be null-terminated and may be NULL only when + * this is 0. * @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_copy_from_progress_set_progress(duckdb_v2_copy_from_progress_info_handle info, - double progress, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_query_set_query(duckdb_v2_pragma_function_query_info_handle info, + const char *query, idx_t query_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the copy function, making it available as a `COPY` format. + * Registers the pragma function, making it available to the `PRAGMA` statement. * * The function is registered on the connection's database, visible to every connection, in the connection's * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. Registration requires a name and at least one configured side: a `COPY ... TO` side needs its - * batch and flush callbacks, a `COPY ... FROM` side needs its bind and exec callbacks. A statement in a direction the - * function does not implement fails with an error. The copy function must have been created through a factory of the + * a rollback undoes it. Registration requires a name and exactly one of a query callback or an exec callback, and fails + * when a pragma of the same name already exists. The pragma function must have been created through a factory of the * same database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_copy_function_destroy()`, which does not affect the registered function. + * `duckdb_v2_pragma_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 * * @param conn The connection to register on. - * @param function The copy function to register. + * @param function The pragma function to register. * @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_register_copy_function(duckdb_v2_connection_handle conn, - duckdb_v2_copy_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_pragma_function(duckdb_v2_connection_handle conn, + duckdb_v2_pragma_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the copy function, making it available as a `COPY` format. + * Registers the pragma function, making it available to the `PRAGMA` statement. * * The function is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. Registration requires a name and at least one configured side: a `COPY ... TO` side needs - * its batch and flush callbacks, a `COPY ... FROM` side needs its bind and exec callbacks. A statement in a direction - * the function does not implement fails with an error. The copy function must have been created through a factory of + * extension's load callback. Registration requires a name and exactly one of a query callback or an exec callback, and + * fails when a pragma of the same name already exists. The pragma function must have been created through a factory of * the same database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_copy_function_destroy()`, which does not affect the registered function. + * `duckdb_v2_pragma_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 * * @param extension The loading extension. - * @param function The copy function to register. + * @param function The pragma function to register. * @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_extension_register_copy_function(duckdb_v2_extension_handle extension, - duckdb_v2_copy_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_pragma_function(duckdb_v2_extension_handle extension, + duckdb_v2_pragma_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the copy function, releasing its resources. + * Destroys the pragma function, releasing its resources. * * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent * double-destruction. Destroying the handle after registration does not affect the registered function. @@ -10167,9524 +10587,8831 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_copy_function(duckdb_v * @param function The function to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_destroy(duckdb_v2_copy_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_destroy(duckdb_v2_pragma_function_handle *function); #endif +/* --- Struct definitions for pragma --- */ + +/* ============================================================================ + * MODULE: replacement scan + * ============================================================================ */ + +/* --- Enums for replacement scan --- */ + +/* --- Struct forward declarations for replacement scan --- */ + +/* --- Types for replacement scan --- */ + +/*! + * An owned opaque handle to a replacement scan being built. Created with `duckdb_v2_replacement_scan_create()`, + * configured with `duckdb_v2_replacement_scan_set_callback()` and `duckdb_v2_replacement_scan_set_user_data()`, made + * available with `duckdb_v2_connection_register_replacement_scan()`, `duckdb_v2_instance_register_replacement_scan()` + * or `duckdb_v2_extension_register_replacement_scan()`, and destroyed with `duckdb_v2_replacement_scan_destroy()`. + */ +typedef struct _duckdb_v2_replacement_scan { + void *internal_ptr; +} * duckdb_v2_replacement_scan_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a replacement scan when the binder consults it. The callback + * receives this handle and can use it to inspect the unresolved name and to claim it by naming what to read instead. + * Valid only for the duration of the callback; the name it hands out is owned separately and outlives it. + */ +typedef struct _duckdb_v2_replacement_scan_info { + void *internal_ptr; +} * duckdb_v2_replacement_scan_info_handle; + +/* --- Constants for replacement scan --- */ + +/* --- Function pointer typedefs for replacement scan --- */ + +typedef void (*duckdb_v2_replacement_scan_callback_fn)(duckdb_v2_replacement_scan_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +/* --- Functions for replacement scan --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional statistics callback of the `COPY ... TO` side. + * Creates a new replacement scan through a factory. * - * The statistics callback reports statistics about a written file, such as the number of rows and bytes it holds, which - * `COPY ... TO` returns when the statement asks for them with `RETURN_STATS`. It is invoked once per output file, after - * the finalize callback of that file, and only when the statement asks for the statistics. Without a statistics - * callback, `RETURN_STATS` is rejected for the function. + * The scan starts out empty: configure it with `duckdb_v2_replacement_scan_set_callback()` and optionally + * `duckdb_v2_replacement_scan_set_user_data()`, then make it available with + * `duckdb_v2_connection_register_replacement_scan()`, `duckdb_v2_instance_register_replacement_scan()` or + * `duckdb_v2_extension_register_replacement_scan()`. The caller owns the returned handle and must destroy it with + * `duckdb_v2_replacement_scan_destroy()`, also after registration. + * + * The scan can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The callback to set. + * @param factory The factory to create the scan through. + * @param scan On success, receives the newly created replacement scan. Owned by the caller. * @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_copy_to_set_statistics_callback( - duckdb_v2_copy_function_handle function, duckdb_v2_copy_to_statistics_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_create(duckdb_v2_factory_handle factory, + duckdb_v2_replacement_scan_handle *scan, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set on the copy function via `duckdb_v2_copy_function_set_user_data()`. + * Sets the callback of the replacement scan. + * + * The callback is invoked during query planning for each table reference the catalog could not resolve. It can inspect + * the unresolved name via `duckdb_v2_replacement_scan_get_name()`, and claim the reference via + * `duckdb_v2_replacement_scan_set_function_name()`, `duckdb_v2_replacement_scan_set_collection()` or + * `duckdb_v2_replacement_scan_set_subquery()`; returning without claiming declines it. The context passed to the + * callback may be used to read settings, but not to run queries. A callback must be set before registration. * * history: * - unstable: v2.0.0 * - * @param info The statistics info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param scan The scan to set the callback of. + * @param callback The callback to set. * @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_copy_to_statistics_get_user_data(duckdb_v2_copy_to_statistics_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_callback(duckdb_v2_replacement_scan_handle scan, + duckdb_v2_replacement_scan_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's `COPY ... TO` bind callback. + * Sets arbitrary user data on the replacement scan. + * + * Associates an opaque pointer with the scan, retrievable from the callback via + * `duckdb_v2_replacement_scan_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, + * invoked when the data is no longer needed, at the latest when the scan's scope ends. The callback may be invoked from + * several connections at once, so the data must be safe to read concurrently. * * history: * - unstable: v2.0.0 * - * @param info The statistics info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param scan The scan to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. * @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_copy_to_statistics_get_bind_data(duckdb_v2_copy_to_statistics_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_user_data(duckdb_v2_replacement_scan_handle scan, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the init data set by the function's `COPY ... TO` init callback for the file being reported. + * Retrieves the user data set via `duckdb_v2_replacement_scan_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param info The statistics info handle. - * @param data Receives the init data pointer, or null if none was set. + * @param info The info handle. + * @param data Receives the user data pointer, or null if none was set. * @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_copy_to_statistics_get_init_data(duckdb_v2_copy_to_statistics_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_get_user_data(duckdb_v2_replacement_scan_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports how many rows were written to the file. Reported as 0 when the callback does not set it. + * Retrieves the name the catalog could not resolve. + * + * The name as written in the query, as a path: an unqualified reference has a single part, and a qualified one carries + * its catalog and schema before it -- see `duckdb_v2_qname_get_part()`. For a file-backed reference the single part is + * the path with the quotes stripped. The returned name is owned by the caller and must be destroyed via + * `duckdb_v2_qname_destroy()`; being owned, it may outlive the callback. * * history: * - unstable: v2.0.0 * - * @param info The statistics info handle. - * @param row_count The number of rows written to the file. + * @param info The info handle. + * @param name Receives the unresolved name. Owned by the caller; destroy via `duckdb_v2_qname_destroy()`. * @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_copy_to_statistics_set_row_count(duckdb_v2_copy_to_statistics_info_handle info, - idx_t row_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_get_name(duckdb_v2_replacement_scan_info_handle info, + duckdb_v2_qname_handle *name, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports the size of the written file in bytes. Reported as 0 when the callback does not set it. + * Claims the reference by naming a table function to read instead. + * + * Arguments to the function are added with `duckdb_v2_replacement_scan_add_argument()` and + * `duckdb_v2_replacement_scan_add_named_argument()`. The name is borrowed and copied, and its parts are matched + * case-insensitively. A qualified name targets a function in a particular schema or catalog, exactly as writing it out + * in SQL would. The name is not resolved here: an unknown function fails later, when the replacement is bound. Calling + * this again replaces the previous name and keeps the arguments added so far. + * + * The three claim forms, `duckdb_v2_replacement_scan_set_function_name()`, + * `duckdb_v2_replacement_scan_set_collection()` and `duckdb_v2_replacement_scan_set_subquery()`, are mutually + * exclusive: claiming the reference through a second, different form results in an error. * * history: * - unstable: v2.0.0 * - * @param info The statistics info handle. - * @param file_size_bytes The size of the file in bytes. + * @param info The info handle. + * @param name The table function to read instead. Borrowed and copied. * @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_copy_to_statistics_set_file_size(duckdb_v2_copy_to_statistics_info_handle info, - idx_t file_size_bytes, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_function_name(duckdb_v2_replacement_scan_info_handle info, + duckdb_v2_qname_handle name, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for copy --- */ - -/* ============================================================================ - * MODULE: custom_option - * ============================================================================ */ - -/* --- Enums for custom_option --- */ - -/* --- Struct forward declarations for custom_option --- */ - -/* --- Types for custom_option --- */ - -/*! - * An owned opaque handle to a custom option being built. Created with `duckdb_v2_custom_option_create()`, configured - * with the setter functions (e.g. `duckdb_v2_custom_option_set_name()`, `duckdb_v2_custom_option_set_type()`, etc.), - * made available with `duckdb_v2_connection_register_custom_option()` or - * `duckdb_v2_extension_register_custom_option()`, and destroyed with `duckdb_v2_custom_option_destroy()`. - */ -typedef struct _duckdb_v2_custom_option { - void *internal_ptr; -} * duckdb_v2_custom_option_handle; - +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to an update of a custom option, received by its update callback. It gives access to the new - * value, the scope it is written at and the user data, and can replace the value. - */ -typedef struct _duckdb_v2_custom_option_update_info { - void *internal_ptr; -} * duckdb_v2_custom_option_update_info_handle; - -/* --- Constants for custom_option --- */ - -/* --- Function pointer typedefs for custom_option --- */ - -typedef void (*duckdb_v2_custom_option_update_callback_fn)(duckdb_v2_custom_option_update_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -/* --- Functions for custom_option --- */ - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Creates a new custom option through a factory. - * - * The option starts out empty: configure it with the setter functions, then make it available with - * `duckdb_v2_connection_register_custom_option()` or `duckdb_v2_extension_register_custom_option()`. The caller owns - * the returned handle and must destroy it with `duckdb_v2_custom_option_destroy()`, also after registration. + * Appends a positional argument to the claimed table function. * - * The custom option can only be registered on the instance the factory belongs to. + * Positional arguments are passed in the order they are added, before any named ones. The value is borrowed and copied, + * so the caller may destroy it after the call. Requires `duckdb_v2_replacement_scan_set_function_name()` to have been + * called first; otherwise the call results in an error. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the custom option through. - * @param option On success, receives the newly created custom option. Owned by the caller. + * @param info The info handle. + * @param value The argument value. Borrowed and copied. * @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_custom_option_create(duckdb_v2_factory_handle factory, - duckdb_v2_custom_option_handle *option, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_add_argument(duckdb_v2_replacement_scan_info_handle info, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the custom option, as `SET` and the config functions refer to it. + * Appends a named argument to the claimed table function. * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * Equivalent to writing `name := value` at the call site. The name and the value are borrowed and copied, so the caller + * may destroy the value after the call. Requires `duckdb_v2_replacement_scan_set_function_name()` to have been called + * first; otherwise the call results in an error. * * history: * - unstable: v2.0.0 * - * @param option The option to set the name of. - * @param name The name to set. Borrowed and copied. + * @param info The info handle. + * @param name The name of the parameter to bind the value to. Borrowed and copied. * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be * NULL only when this is 0. + * @param value The argument value. Borrowed and copied. * @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_custom_option_set_name(duckdb_v2_custom_option_handle option, const char *name, - idx_t name_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_add_named_argument(duckdb_v2_replacement_scan_info_handle info, + const char *name, idx_t name_length, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the type of the custom option. Every value written to the option is cast to it, as SQL `SET` does. + * Claims the reference by naming a column data collection to read instead. * - * The type is borrowed and copied. Optional when a default value is set, whose type the option then takes. + * The collection is borrowed, not copied: the caller keeps ownership and must keep it alive, and must not clear, reset + * or destroy it, for as long as any result reading it is live, since the result scans its buffers directly. * - * history: - * - unstable: v2.0.0 + * A prepared statement extends that lifetime well beyond its own results. Preparing a statement over a claimed name + * captures the borrow in the plan, and since a collection claim reads no database there is nothing to invalidate that + * plan: `duckdb_v2_prepared_statement_reuses_plan()` reports true, and every later execution reuses the captured borrow + * without consulting the callback again. So dropping the name from whatever the callback resolves against does not + * release the collection, and releasing it while such a statement is live leaves the next execution reading freed + * memory. Destroy every prepared statement over a claimed name before clearing, resetting or destroying the collection + * behind it. * - * @param option The option to set the type of. - * @param type The type to set. Borrowed and copied. - * @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_custom_option_set_type(duckdb_v2_custom_option_handle option, - duckdb_v2_logical_type_handle type, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the default value of the custom option: its value until it is set, and the value `RESET` restores. + * By default the collection's columns are named col1..colN. Pass `column_names` to name them instead. When supplied, + * `column_count` must equal the collection's column count and no name may be empty; pass NULL and 0 for the default + * names. * - * The value is borrowed and copied, and cast to the option's type at registration, which fails when the cast does. - * Without a default value the option reads as NULL until it is set. + * The three claim forms, `duckdb_v2_replacement_scan_set_function_name()`, + * `duckdb_v2_replacement_scan_set_collection()` and `duckdb_v2_replacement_scan_set_subquery()`, are mutually + * exclusive: claiming the reference through a second, different form results in an error. * * history: * - unstable: v2.0.0 * - * @param option The option to set the default value of. - * @param value The default value. Borrowed and copied. + * @param info The info handle. + * @param collection The collection to read instead. Borrowed; the caller keeps ownership and must keep it alive. + * @param column_names Optional. An array of `column_count` column names, in order. Pass NULL for the default names + * col1..colN. + * @param column_names_lengths Byte lengths of the entries in `column_names`; element i is the length of + * `column_names[i]`. May be NULL only when `column_names` is NULL. + * @param column_count The number of names in `column_names`. Must equal the collection's column count, or 0 for the + * default names. * @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_custom_option_set_default_value(duckdb_v2_custom_option_handle option, - duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_collection( + duckdb_v2_replacement_scan_info_handle info, duckdb_v2_column_data_collection_handle collection, + const char *const *column_names, const idx_t *column_names_lengths, idx_t column_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the description of the custom option, as `duckdb_v2_option_get_description()` and `duckdb_settings()` report it. + * Claims the reference by naming a query to read instead. * - * The description is borrowed and copied. Calling this again replaces the previous description. + * The text is parsed at the call and must contain exactly one SELECT statement: a syntax error, several statements or a + * statement of another kind results in an error. The text is borrowed for the call only. Prefer + * `duckdb_v2_replacement_scan_set_function_name()` when a single table function call suffices, as it avoids the parse + * and keeps the plan flatter. + * + * The three claim forms, `duckdb_v2_replacement_scan_set_function_name()`, + * `duckdb_v2_replacement_scan_set_collection()` and `duckdb_v2_replacement_scan_set_subquery()`, are mutually + * exclusive: claiming the reference through a second, different form results in an error. * * history: * - unstable: v2.0.0 * - * @param option The option to set the description of. - * @param description The description to set. Borrowed and copied. - * @param description_length The length of `description` in bytes. `description` need not be null-terminated and may be - * NULL only when this is 0. + * @param info The info handle. + * @param sql The SELECT statement to read instead. Borrowed for the call only. + * @param sql_length The length of `sql` in bytes. `sql` need not be null-terminated and may be NULL only when this is + * 0. * @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_custom_option_set_description(duckdb_v2_custom_option_handle option, - const char *description, idx_t description_length, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_subquery(duckdb_v2_replacement_scan_info_handle info, + const char *sql, idx_t sql_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the scope a write at `SETTING_SCOPE_DEFAULT` goes to, like SQL `SET name = value`. + * Sets the alias the claimed replacement is bound under. * - * Must be GLOBAL or SESSION, and a scope the option supports. Defaults to SESSION, or to GLOBAL when the option does - * not support SESSION. + * Optional, and independent of the claim form. An alias written in the query takes precedence over this one; without + * either, the table name of the reference is used, which for a file-backed reference is the path. The alias is borrowed + * and copied. * * history: * - unstable: v2.0.0 * - * @param option The option to set the default scope of. - * @param scope The default scope, GLOBAL or SESSION. + * @param info The info handle. + * @param alias The alias to bind the replacement under. Borrowed and copied. + * @param alias_length The length of `alias` in bytes. `alias` must be valid UTF-8, need not be null-terminated, and may + * be NULL only when this is 0. * @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_custom_option_set_default_scope(duckdb_v2_custom_option_handle option, - DUCKDB_V2_SETTING_SCOPE scope, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_alias(duckdb_v2_replacement_scan_info_handle info, + const char *alias, idx_t alias_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets whether the custom option can be written at a scope, as `duckdb_v2_option_supports_scope()` reports it. + * Registers the replacement scan, making it consulted for names the catalog cannot resolve. * - * A custom option supports both GLOBAL and SESSION unless told otherwise. A write at a scope it does not support fails, - * from SQL as from `duckdb_v2_config_set_option_value()`. Registration fails when the option supports neither scope. + * The scan is visible only to queries on this connection and is released when the connection is destroyed. It is + * consulted before every instance-wide scan, so it can claim a name that a built-in scan would otherwise take. + * Registration requires a callback. Scans are consulted in registration order within their scope, connection-scoped + * ones before instance-wide ones, and the first to claim a name wins. A scan cannot be registered twice, and a + * registered scan cannot be unregistered: it lives until its scope ends. The scan must have been created through a + * factory of the same database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_replacement_scan_destroy()`, which does not affect the registered scan. * * history: * - unstable: v2.0.0 * - * @param option The option to configure. - * @param scope The scope, GLOBAL or SESSION. - * @param supported Whether the option can be written at the scope. + * @param conn The connection to register on. + * @param scan The replacement scan to register. * @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_custom_option_set_supports_scope(duckdb_v2_custom_option_handle option, - DUCKDB_V2_SETTING_SCOPE scope, bool supported, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_replacement_scan(duckdb_v2_connection_handle conn, + duckdb_v2_replacement_scan_handle scan, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the custom option. + * Registers the replacement scan, making it consulted for names the catalog cannot resolve. * - * Associates an opaque pointer with the option, retrievable from the update callback via - * `duckdb_v2_custom_option_update_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, - * invoked when the data is no longer needed: once the custom option handle is destroyed and, if it was registered, the - * instance is too. + * The scan is visible to every connection to the instance and lives until the instance is destroyed. Registering it + * while queries are binding on other connections is not thread-safe: register before issuing queries. Registration + * requires a callback. Scans are consulted in registration order within their scope, connection-scoped ones before + * instance-wide ones, and the first to claim a name wins. A scan cannot be registered twice, and a registered scan + * cannot be unregistered: it lives until its scope ends. The scan must have been created through a factory of the same + * database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_replacement_scan_destroy()`, which does not affect the registered scan. * * history: * - unstable: v2.0.0 * - * @param option The option to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param instance The instance to register on. + * @param scan The replacement scan to register. * @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_custom_option_set_user_data(duckdb_v2_custom_option_handle option, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_register_replacement_scan(duckdb_v2_instance_handle instance, + duckdb_v2_replacement_scan_handle scan, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional update callback of the custom option. + * Registers the replacement scan, making it consulted for names the catalog cannot resolve. * - * The callback is invoked whenever the option is set or reset, from SQL as from `duckdb_v2_config_set_option_value()`, - * after the new value is cast to the option's type and before it is stored. It may replace the value with - * `duckdb_v2_custom_option_update_set_value()`, or refuse it by reporting an error. It is not invoked for the default - * value at registration, nor for a value given to the instance at startup. The callback must not write options itself. + * The scan is visible to every connection to the loading extension's instance and lives until the instance is + * destroyed. Use this from the extension's load callback. Registration requires a callback. Scans are consulted in + * registration order within their scope, connection-scoped ones before instance-wide ones, and the first to claim a + * name wins. A scan cannot be registered twice, and a registered scan cannot be unregistered: it lives until its scope + * ends. The scan must have been created through a factory of the same database. The caller still owns the handle after + * registration and must destroy it with `duckdb_v2_replacement_scan_destroy()`, which does not affect the registered + * scan. * * history: * - unstable: v2.0.0 * - * @param option The option to set the update callback of. - * @param callback The update callback to set. + * @param extension The loading extension. + * @param scan The replacement scan to register. * @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_custom_option_set_update_callback( - duckdb_v2_custom_option_handle option, duckdb_v2_custom_option_update_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_replacement_scan(duckdb_v2_extension_handle extension, + duckdb_v2_replacement_scan_handle scan, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_custom_option_set_user_data()`. - * - * history: - * - unstable: v2.0.0 + * Destroys the replacement scan, releasing its resources. * - * @param info The update info handle. - * @param data Receives the user data pointer, or null if none was set. - * @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_custom_option_update_get_user_data( - duckdb_v2_custom_option_update_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the value the option is updated to, already cast to the option's type. On a reset this is the default - * value, which may be NULL. The returned value is owned by the caller and must be destroyed via - * `duckdb_v2_value_destroy()`. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered scan. * * history: * - unstable: v2.0.0 * - * @param info The update info handle. - * @param value Receives the new value. Owned by the caller; destroy via `duckdb_v2_value_destroy()`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param scan The scan to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_value(duckdb_v2_custom_option_update_info_handle info, - duckdb_v2_value_handle *value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_destroy(duckdb_v2_replacement_scan_handle *scan); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Replaces the value the option is updated to, e.g. to normalize it. The value is borrowed and copied, and cast to the - * option's type, which fails when the cast does. - * - * history: - * - unstable: v2.0.0 - * - * @param info The update info handle. - * @param value The value to store instead. Borrowed and copied. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR +/* --- Struct definitions for replacement scan --- */ + +/* ============================================================================ + * MODULE: scalar + * ============================================================================ */ + +/* --- Enums for scalar --- */ + +/* --- Struct forward declarations for scalar --- */ + +/* --- Types for scalar --- */ + +/*! + * An owned opaque handle to a custom scalar function being built. Created with `duckdb_v2_scalar_function_create()`, + * configured with the setter functions (e.g. `duckdb_v2_scalar_function_set_name()`, + * `duckdb_v2_scalar_function_set_exec_callback()`, etc.) and the signature obtained via + * `duckdb_v2_scalar_function_get_signature()`, made available with `duckdb_v2_connection_register_scalar_function()` or + * `duckdb_v2_extension_register_scalar_function()`, and destroyed with `duckdb_v2_scalar_function_destroy()`. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_set_value(duckdb_v2_custom_option_update_info_handle info, - duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_scalar_function { + void *internal_ptr; +} * duckdb_v2_scalar_function_handle; -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the scope the value is written at: GLOBAL or SESSION, a DEFAULT write already resolved to the option's - * default scope. - * - * history: - * - unstable: v2.0.0 - * - * @param info The update info handle. - * @param scope Receives the scope. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR + * A borrowed opaque handle to the result of a scalar function's "resolve types" phase. The "resolve types" callback + * receives this handle next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments and the + * user data, and can use it to set the return type of the call site being bound. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_scope(duckdb_v2_custom_option_update_info_handle info, - DUCKDB_V2_SETTING_SCOPE *scope, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_scalar_function_resolve_types_info { + void *internal_ptr; +} * duckdb_v2_scalar_function_resolve_types_info_handle; + +/*! + * A borrowed opaque handle to the result of a scalar function's "bind" phase. The "bind" callback receives this handle + * next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments and the user data, and can use + * it to set the bind data of the call site being bound. + */ +typedef struct _duckdb_v2_scalar_function_bind_info { + void *internal_ptr; +} * duckdb_v2_scalar_function_bind_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a scalar function during the local state initialization "init" + * phase. The "init" callback receives this handle and can use it to e.g. set up local state reusable across invocations + * of the "exec" execution callback. + */ +typedef struct _duckdb_v2_scalar_function_init_info { + void *internal_ptr; +} * duckdb_v2_scalar_function_init_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a scalar function during the execution "exec" phase. The "exec" + * callback receives this handle and can use it to e.g. access the input argument vectors, retrieve the number of rows + * to process, and write results to the output vector. + */ +typedef struct _duckdb_v2_scalar_function_exec_info { + void *internal_ptr; +} * duckdb_v2_scalar_function_exec_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a scalar function during the "stats" phase of query + * optimization. The "stats" callback receives this handle and can use it to read the statistics of the arguments of the + * call site and narrow the statistics of its result. + */ +typedef struct _duckdb_v2_scalar_function_stats_info { + void *internal_ptr; +} * duckdb_v2_scalar_function_stats_info_handle; + +/* --- Constants for scalar --- */ + +/* --- Function pointer typedefs for scalar --- */ + +typedef void (*duckdb_v2_scalar_function_resolve_types_callback_fn)( + 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); + +typedef void (*duckdb_v2_scalar_function_bind_callback_fn)(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); + +typedef void (*duckdb_v2_scalar_function_init_callback_fn)(duckdb_v2_scalar_function_init_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_scalar_function_exec_callback_fn)(duckdb_v2_scalar_function_exec_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_scalar_function_stats_callback_fn)(duckdb_v2_scalar_function_stats_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +/* --- Functions for scalar --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves whether the update is a reset to the default value, like SQL `RESET`. + * Creates a new scalar function through a factory. + * + * The function starts out empty: configure it with the setter functions (e.g. `duckdb_v2_scalar_function_set_name()`, + * `duckdb_v2_scalar_function_set_exec_callback()`, etc.) and the signature obtained via + * `duckdb_v2_scalar_function_get_signature()`, then make it available with + * `duckdb_v2_connection_register_scalar_function()` or `duckdb_v2_extension_register_scalar_function()`. The caller + * owns the returned handle and must destroy it with `duckdb_v2_scalar_function_destroy()`, also after registration. + * + * The scalar function can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param info The update info handle. - * @param is_reset Receives whether the update is a reset. + * @param factory The factory to create the scalar function through. + * @param function On success, receives the newly created scalar function. Owned by the caller. * @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_custom_option_update_is_reset(duckdb_v2_custom_option_update_info_handle info, - bool *is_reset, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_scalar_function_handle *function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the custom option on the connection's instance, visible to every connection. + * Sets the name of the scalar function. * - * Registration is not transactional: it takes effect at once, also inside an explicit transaction, and a rollback does - * not undo it. Registration requires a name and a type, or a default value to take the type from, and fails when an - * option of the same name already exists. A value given for the option at startup is picked up. The custom option must - * have been created through a factory of the same instance. The caller still owns the handle after registration and - * must destroy it with `duckdb_v2_custom_option_destroy()`, which does not affect the registered option. + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param option The custom option to register. + * @param function The function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @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_register_custom_option(duckdb_v2_connection_handle conn, - duckdb_v2_custom_option_handle option, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_name(duckdb_v2_scalar_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the custom option on the loading extension's instance, visible to every connection. + * Sets the schema of the system catalog that the scalar function is registered in. * - * Use this from the extension's load callback. Registration is not transactional, requires a name and a type, or a - * default value to take the type from, and fails when an option of the same name already exists. A value given for the - * option at startup is picked up. The custom option must have been created through a factory of the same instance. The - * caller still owns the handle after registration and must destroy it with `duckdb_v2_custom_option_destroy()`, which - * does not affect the registered option. + * The schema is borrowed and copied. Calling this again replaces the previous schema. Without a schema the function is + * registered in the default schema. The schema must exist when the function is registered, e.g. `collations`, whose + * functions are the string collations of the database. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param option The custom option to register. + * @param function The function to set the schema of. + * @param schema The name of the schema. Borrowed and copied. + * @param schema_length The length of `schema` in bytes. `schema` must be valid UTF-8, need not be null-terminated, and + * may be NULL only when this is 0. * @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_extension_register_custom_option(duckdb_v2_extension_handle extension, - duckdb_v2_custom_option_handle option, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_schema(duckdb_v2_scalar_function_handle function, + const char *schema, idx_t schema_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the custom option, releasing its resources. + * Returns the documentation of the function so it can be filled in. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered option. + * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with + * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified + * in place, describes this overload only, and is registered with the function. Optional. * * history: * - unstable: v2.0.0 * - * @param option The option to destroy. + * @param function The function to get the documentation of. + * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. + * @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_custom_option_destroy(duckdb_v2_custom_option_handle *option); -#endif - -/* --- Struct definitions for custom_option --- */ - -/* ============================================================================ - * MODULE: expression - * ============================================================================ */ - -/* --- Enums for expression --- */ - -/*! - * The type of a bound expression node. The values mirror the engine's own expression types, restricted to the node - * types a filter predicate can contain; every other node type is reported as `EXPRESSION_TYPE_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` therefore has one child, the value being - * cast, and its target type is the node's return type. - */ -typedef enum DUCKDB_V2_EXPRESSION_TYPE { - //! A node type this API does not model. Its children can still be walked. - DUCKDB_V2_EXPRESSION_TYPE_INVALID = 0, - - /*! - * A cast. One child; the target type is the node's return type and `duckdb_v2_expression_cast_get_mode()` tells a - * `TRY_CAST` apart. - */ - DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_CAST = 12, - - //! Logical `NOT`. One child. - DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_NOT = 13, - - //! `IS NULL`. One child. - DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_IS_NULL = 14, - - //! `IS NOT NULL`. One child. - DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_IS_NOT_NULL = 15, - - //! `=`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_EQUAL = 25, - - //! `<>`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOTEQUAL = 26, - - //! `<`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_LESSTHAN = 27, - - //! `>`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_GREATERTHAN = 28, - - //! `<=`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO = 29, - - //! `>=`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO = 30, - - //! `IN`. The first child is the value tested, the remaining children are the candidates. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_IN = 35, - - //! `NOT IN`. The first child is the value tested, the remaining children are the candidates. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOT_IN = 36, - - //! `IS DISTINCT FROM`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_DISTINCT_FROM = 37, - - //! `BETWEEN`. Three children: the value tested, the lower bound and the upper bound. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_BETWEEN = 38, - - //! `IS NOT DISTINCT FROM`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOT_DISTINCT_FROM = 40, - - //! Logical `AND`. Two or more children. - DUCKDB_V2_EXPRESSION_TYPE_CONJUNCTION_AND = 50, - - //! Logical `OR`. Two or more children. - DUCKDB_V2_EXPRESSION_TYPE_CONJUNCTION_OR = 51, - - //! A constant. No children; read it with `duckdb_v2_expression_constant_get_value()`. - DUCKDB_V2_EXPRESSION_TYPE_VALUE_CONSTANT = 75, - - //! A prepared statement parameter whose value is not known yet. No children. - DUCKDB_V2_EXPRESSION_TYPE_VALUE_PARAMETER = 76, - - /*! - * A call to a scalar function other than the ones listed above. The children are its arguments; read the name with - * `duckdb_v2_expression_function_get_name()`. - */ - DUCKDB_V2_EXPRESSION_TYPE_BOUND_FUNCTION = 141, - - //! A `CASE` expression. The children are each `WHEN` condition followed by its `THEN` result, then the `ELSE` - //! result. - DUCKDB_V2_EXPRESSION_TYPE_CASE_EXPR = 150, - - //! `COALESCE`. One or more children. - DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_COALESCE = 152, - - //! A reference to a column. No children; read it with `duckdb_v2_expression_column_ref_get_index()`. - DUCKDB_V2_EXPRESSION_TYPE_BOUND_COLUMN_REF = 228, - DUCKDB_V2_EXPRESSION_TYPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_EXPRESSION_TYPE; - -/*! - * What checking a predicate against the statistics of its column found out (`FilterPropagateResult`): whether every row - * the statistics describe passes the predicate, none does, or the statistics do not tell. - */ -typedef enum DUCKDB_V2_FILTER_PROPAGATE_RESULT { - //! The statistics do not decide the predicate. - DUCKDB_V2_FILTER_PROPAGATE_RESULT_NO_PRUNING_POSSIBLE = 0, - - //! Every row passes the predicate. - DUCKDB_V2_FILTER_PROPAGATE_RESULT_ALWAYS_TRUE = 1, - - //! No row passes the predicate. - DUCKDB_V2_FILTER_PROPAGATE_RESULT_ALWAYS_FALSE = 2, - - //! Every row passes the predicate or evaluates it to NULL. - DUCKDB_V2_FILTER_PROPAGATE_RESULT_TRUE_OR_NULL = 3, - - //! No row passes the predicate: each evaluates it to false or to NULL. - DUCKDB_V2_FILTER_PROPAGATE_RESULT_FALSE_OR_NULL = 4, - DUCKDB_V2_FILTER_PROPAGATE_RESULT_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_FILTER_PROPAGATE_RESULT; - -/* --- Struct forward declarations for expression --- */ - -/* --- Types for expression --- */ - -/*! - * A borrowed opaque handle to a node of a bound expression tree. Read-only and owned by the engine: valid only for the - * duration of the callback that handed it out, and never destroyed by the caller. Child nodes borrowed via - * `duckdb_v2_expression_get_child()` share their parent's lifetime. - */ -typedef struct _duckdb_v2_expression { - void *internal_ptr; -} * duckdb_v2_expression_handle; - -/* --- Constants for expression --- */ - -/* --- Function pointer typedefs for expression --- */ - -/* --- Functions for expression --- */ - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the type of an expression node. - * - * The type decides which of the type-specific accessors apply, and what the node's children mean; see - * `EXPRESSION_TYPE`. A node of a type this API does not model reports `EXPRESSION_TYPE_INVALID`. - * - * history: - * - unstable: v2.0.0 - * - * @param expression The expression node. - * @param type Receives the node type. - * @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_expression_get_type(duckdb_v2_expression_handle expression, - DUCKDB_V2_EXPRESSION_TYPE *type, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the logical type the expression node evaluates to. - * - * For a cast this is the target type. The returned type is owned by the caller and must be destroyed via - * `duckdb_v2_logical_type_destroy()`. - * - * history: - * - unstable: v2.0.0 - * - * @param expression The expression node. - * @param type Receives the owned logical type. - * @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_expression_get_return_type(duckdb_v2_expression_handle expression, - duckdb_v2_logical_type_handle *type, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the number of child nodes of an expression node. - * - * Works for every node type, including `EXPRESSION_TYPE_INVALID`. Constants, parameters and column references have no - * children. - * - * history: - * - unstable: v2.0.0 - * - * @param expression The expression node. - * @param count Receives the number of children. - * @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_expression_get_child_count(duckdb_v2_expression_handle expression, idx_t *count, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves a child node of an expression node by index. - * - * Fails if the index is out of bounds. Children are ordered as the node type describes (see `EXPRESSION_TYPE`). The - * child is borrowed and shares the lifetime of its parent. - * - * history: - * - unstable: v2.0.0 - * - * @param expression The expression node. - * @param index The index of the child to retrieve. - * @param child Receives the borrowed child node. - * @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_expression_get_child(duckdb_v2_expression_handle expression, idx_t index, - duckdb_v2_expression_handle *child, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the value of a constant node. - * - * Fails if the node is not of type `EXPRESSION_TYPE_VALUE_CONSTANT`. The returned value is owned by the caller and must - * be destroyed via `duckdb_v2_value_destroy()`. - * - * history: - * - unstable: v2.0.0 - * - * @param expression The constant node. - * @param value Receives the owned constant value. - * @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_expression_constant_get_value(duckdb_v2_expression_handle expression, - duckdb_v2_value_handle *value, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the column a column reference node points at. - * - * Fails if the node is not of type `EXPRESSION_TYPE_BOUND_COLUMN_REF`. The index counts the columns of the operator the - * predicate is evaluated against, which is not necessarily the full set of columns that operator can produce: a - * callback resolves it through whatever handed it the expression, e.g. - * `duckdb_v2_table_function_filter_pushdown_get_column_index()` for a filter offered to a table function. - * - * history: - * - unstable: v2.0.0 - * - * @param expression The column reference node. - * @param index Receives the column index. - * @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_expression_column_ref_get_index(duckdb_v2_expression_handle expression, - idx_t *index, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the name of the scalar function a function node calls. - * - * Applies to `EXPRESSION_TYPE_BOUND_FUNCTION` and to the node types that are function calls underneath: the - * comparisons, `EXPRESSION_TYPE_COMPARE_BETWEEN` and `EXPRESSION_TYPE_OPERATOR_CAST`. Fails for any other node type. - * For a comparison the name is its operator, e.g. `<`; for `BETWEEN` and casts it is an internal name, so dispatch on - * the type rather than the name for those. The name is borrowed and shares the lifetime of the node. - * - * history: - * - unstable: v2.0.0 - * - * @param expression The function node. - * @param name Receives a borrowed pointer to the function name. - * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. - * @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_expression_function_get_name(duckdb_v2_expression_handle expression, - const char **name, idx_t *name_length, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the qualified name of the scalar function a function node calls. - * - * Applies to the same node types as `duckdb_v2_expression_function_get_name()`, and fails for any other. The name is - * qualified with the catalog and schema the function was resolved in, where known. The returned name is owned by the - * caller and must be destroyed via `duckdb_v2_qname_destroy()`. - * - * history: - * - unstable: v2.0.0 - * - * @param expression The function node. - * @param name Receives the owned qualified name. - * @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_expression_function_get_qname(duckdb_v2_expression_handle expression, - duckdb_v2_qname_handle *name, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns whether a cast node is a regular `CAST` or a `TRY_CAST`. - * - * Fails if the node is not of type `EXPRESSION_TYPE_OPERATOR_CAST`. A `TRY_CAST` yields NULL for a value it cannot - * convert where a regular `CAST` would fail the query. - * - * history: - * - unstable: v2.0.0 - * - * @param expression The cast node. - * @param mode Receives the cast mode. - * @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_expression_cast_get_mode(duckdb_v2_expression_handle expression, - DUCKDB_V2_CAST_MODE *mode, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Checks a predicate over one column against the statistics of that column (`ExpressionFilter::CheckStatistics`): the - * statistics of the column are propagated through the expression - comparisons, conjunctions, IS NULL, IN, casts and - * the functions the engine knows the statistics of - to find out whether every row the statistics describe passes the - * predicate, none does, or nothing can be told. A table function uses it to skip a row group (or a file) whose - * statistics, built with `duckdb_v2_stats_create()`, make a pushed-down filter it did not take over false for every - * row. Every column reference of the predicate stands for the column described by `stats`. - * - * history: - * - unstable: v2.0.0 - * - * @param context The context of the query; the statistics of function calls in the predicate are derived through it. - * @param expression The predicate: a boolean expression over one column, referenced by its column references. - * @param stats The statistics of that column over the rows in question. - * @param result Receives what the statistics decide about the predicate. - * @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_expression_check_statistics(duckdb_v2_context_handle context, - duckdb_v2_expression_handle expression, - duckdb_v2_stats_handle stats, - DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, - duckdb_v2_error_info_handle *err); -#endif - -/* --- Struct definitions for expression --- */ - -/* ============================================================================ - * MODULE: log sink - * ============================================================================ */ - -/* --- Enums for log sink --- */ - -//! The scope a log entry was written in, which decides which of its ids are present. -typedef enum DUCKDB_V2_LOG_SCOPE { - //! Written for the database as a whole, carrying no connection, transaction or query id. - DUCKDB_V2_LOG_SCOPE_DATABASE = 10, - - //! Written by a connection, carrying its connection id and, inside one, the transaction and query ids. - DUCKDB_V2_LOG_SCOPE_CONNECTION = 20, - - //! Written by a thread executing a query, carrying the thread id next to the connection's ids. - DUCKDB_V2_LOG_SCOPE_THREAD = 30, - DUCKDB_V2_LOG_SCOPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_LOG_SCOPE; - -/* --- Struct forward declarations for log sink --- */ - -/* --- Types for log sink --- */ - -/*! - * An owned opaque handle to a log sink being built. Created with `duckdb_v2_log_sink_create()`, configured with - * `duckdb_v2_log_sink_set_name()`, `duckdb_v2_log_sink_set_write_callback()` and the other setters, made available with - * `duckdb_v2_instance_register_log_sink()` or `duckdb_v2_extension_register_log_sink()`, and destroyed with - * `duckdb_v2_log_sink_destroy()`. - */ -typedef struct _duckdb_v2_log_sink { - void *internal_ptr; -} * duckdb_v2_log_sink_handle; - -/*! - * A borrowed opaque handle to the context of a log entry, received by a log sink's write callback next to the entry - * itself, and valid only for the duration of that call. Read the ids `duckdb_logs` reports for the entry through its - * getters, e.g. `duckdb_v2_log_sink_write_info_get_connection_id()`. - */ -typedef struct _duckdb_v2_log_sink_write_info { - void *internal_ptr; -} * duckdb_v2_log_sink_write_info_handle; - -/*! - * A borrowed opaque handle received by a log sink's flush callback, and valid only for the duration of that call. It - * carries nothing yet. - */ -typedef struct _duckdb_v2_log_sink_flush_info { - void *internal_ptr; -} * duckdb_v2_log_sink_flush_info_handle; - -/* --- Constants for log sink --- */ - -/* --- Function pointer typedefs for log sink --- */ - -typedef void (*duckdb_v2_log_sink_write_callback_fn)(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); - -typedef void (*duckdb_v2_log_sink_flush_callback_fn)(duckdb_v2_log_sink_flush_info_handle info, void *user_data, - duckdb_v2_error_info_handle *err); - -/* --- Functions for log sink --- */ - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Creates a new log sink through a factory. - * - * The log sink starts out empty: configure it with the setter functions, then make it available with - * `duckdb_v2_instance_register_log_sink()` or `duckdb_v2_extension_register_log_sink()`. The caller owns the returned - * handle and must destroy it with `duckdb_v2_log_sink_destroy()`, also after registration. - * - * The log sink can only be registered on the instance the factory belongs to. - * - * history: - * - unstable: v2.0.0 - * - * @param factory The factory to create the log sink through. - * @param sink On success, receives the newly created log sink. Owned by the caller. - * @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_log_sink_create(duckdb_v2_factory_handle factory, - duckdb_v2_log_sink_handle *sink, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the name the logging configuration refers to the log sink by. - * - * Names are matched case-insensitively. The name is borrowed and copied. Calling this again replaces the previous name. - * A name must be set before registration. - * - * history: - * - unstable: v2.0.0 - * - * @param sink The log sink to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @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_log_sink_set_name(duckdb_v2_log_sink_handle sink, const char *name, - idx_t name_length, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets arbitrary user data on the log sink. - * - * Associates an opaque pointer with the sink, handed to its write and flush callbacks. The opaque handle bundles the - * pointer with an optional destructor, invoked when the data is no longer needed: when the instance is destroyed if the - * sink was registered, else when the log sink handle is. - * - * history: - * - unstable: v2.0.0 - * - * @param sink The log sink to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. - * @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_log_sink_set_user_data(duckdb_v2_log_sink_handle sink, duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the write callback of the log sink, invoked for every entry the logging configuration directs to the sink. - * - * The callback must return quickly, must be safe to run concurrently and on any thread, and must not log or change the - * logging configuration. A write callback must be set before registration. - * - * history: - * - unstable: v2.0.0 - * - * @param sink The log sink to set the write callback of. - * @param callback The write callback to set. - * @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_log_sink_set_write_callback(duckdb_v2_log_sink_handle sink, - duckdb_v2_log_sink_write_callback_fn callback, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the optional flush callback of the log sink, invoked when DuckDB flushes its log, so entries the sink holds on - * to can be written out. When DuckDB flushes is up to DuckDB; entries still held when the instance is destroyed are for - * the user data's destructor to write out. - * - * Like the write callback, it must be safe to run on any thread, and must not log or change the logging configuration. - * - * history: - * - unstable: v2.0.0 - * - * @param sink The log sink to set the flush callback of. - * @param callback The flush callback to set. - * @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_log_sink_set_flush_callback(duckdb_v2_log_sink_handle sink, - duckdb_v2_log_sink_flush_callback_fn callback, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the id of the connection that wrote the entry, as `duckdb_logs` reports it. An entry written for the - * database as a whole has none: `present` then receives false and `id` is left untouched. - * - * history: - * - unstable: v2.0.0 - * - * @param info The write info handle of the entry. - * @param id Receives the connection id, if present. - * @param present Receives whether the entry has a connection id. - * @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_log_sink_write_info_get_connection_id(duckdb_v2_log_sink_write_info_handle info, - idx_t *id, bool *present, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the id of the transaction the entry was written in, as `duckdb_logs` reports it. An entry written outside a - * transaction has none: `present` then receives false and `id` is left untouched. - * - * history: - * - unstable: v2.0.0 - * - * @param info The write info handle of the entry. - * @param id Receives the transaction id, if present. - * @param present Receives whether the entry has a transaction id. - * @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_log_sink_write_info_get_transaction_id(duckdb_v2_log_sink_write_info_handle info, - idx_t *id, bool *present, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the id of the query the entry was written for, as `duckdb_logs` reports it. An entry written outside a - * query has none: `present` then receives false and `id` is left untouched. - * - * history: - * - unstable: v2.0.0 - * - * @param info The write info handle of the entry. - * @param id Receives the query id, if present. - * @param present Receives whether the entry has a query id. - * @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_log_sink_write_info_get_query_id(duckdb_v2_log_sink_write_info_handle info, - idx_t *id, bool *present, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the id of the thread that wrote the entry, as `duckdb_logs` reports it. Only an entry written in the thread - * scope has one: otherwise `present` receives false and `id` is left untouched. The id identifies the thread that - * logged, which need not be the thread the write callback runs on. - * - * history: - * - unstable: v2.0.0 - * - * @param info The write info handle of the entry. - * @param id Receives the thread id, if present. - * @param present Receives whether the entry has a thread id. - * @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_log_sink_write_info_get_thread_id(duckdb_v2_log_sink_write_info_handle info, - idx_t *id, bool *present, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Registers the log sink on the instance, making it available to the logging configuration under its name. - * - * Registering does not direct any entries to the sink by itself; the logging configuration does. Registration is not - * transactional, requires a name and a write callback, and fails when the name is taken: by a sink DuckDB provides - * itself, such as `memory`, `stdout` or `file`, or by a sink registered before. The log sink must have been created - * through a factory of the same instance. Its user data passes to the registered sink. The caller still owns the handle - * after registration and must destroy it with `duckdb_v2_log_sink_destroy()`, which does not affect the registered - * sink. - * - * history: - * - unstable: v2.0.0 - * - * @param instance The instance to register on. - * @param sink The log sink to register. - * @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_instance_register_log_sink(duckdb_v2_instance_handle instance, - duckdb_v2_log_sink_handle sink, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Registers the log sink on the loading extension's instance, making it available to the logging configuration under - * its name. - * - * Use this from the extension's load callback. Registration follows the rules of - * `duckdb_v2_instance_register_log_sink()`. - * - * history: - * - unstable: v2.0.0 - * - * @param extension The loading extension. - * @param sink The log sink to register. - * @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_extension_register_log_sink(duckdb_v2_extension_handle extension, - duckdb_v2_log_sink_handle sink, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Destroys the log sink, releasing its resources. - * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered sink. - * - * history: - * - unstable: v2.0.0 - * - * @param sink The log sink to destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_destroy(duckdb_v2_log_sink_handle *sink); -#endif - -/* --- Struct definitions for log sink --- */ - -/* ============================================================================ - * MODULE: logical_type - * ============================================================================ */ - -/* --- Enums for logical_type --- */ - -/*! - * Logical type identifier. The values are the same integers DuckDB uses internally, so round-tripping is lossless. The - * bind- and UDF-only ids (UNKNOWN, ANY, TEMPLATE) appear here for completeness; they do not show up in result column - * types in practice. - */ -typedef enum DUCKDB_V2_LOGICAL_TYPE_ID { - //! Invalid / unset. - DUCKDB_V2_LOGICAL_TYPE_ID_INVALID = 0, - - //! NULL constant type. - DUCKDB_V2_LOGICAL_TYPE_ID_SQLNULL = 1, - - //! Unknown — used for unresolved parameter expressions. - DUCKDB_V2_LOGICAL_TYPE_ID_UNKNOWN = 2, - - //! ANY — used for functions that accept any type. - DUCKDB_V2_LOGICAL_TYPE_ID_ANY = 3, - - //! A type carried as a value (type parameters). Values of this type are built via value_create_type. - DUCKDB_V2_LOGICAL_TYPE_ID_TYPE = 6, - DUCKDB_V2_LOGICAL_TYPE_ID_BOOLEAN = 10, - DUCKDB_V2_LOGICAL_TYPE_ID_TINYINT = 11, - DUCKDB_V2_LOGICAL_TYPE_ID_SMALLINT = 12, - DUCKDB_V2_LOGICAL_TYPE_ID_INTEGER = 13, - DUCKDB_V2_LOGICAL_TYPE_ID_BIGINT = 14, - - //! 32-bit days since epoch. - DUCKDB_V2_LOGICAL_TYPE_ID_DATE = 15, - - //! 64-bit microseconds since midnight. - DUCKDB_V2_LOGICAL_TYPE_ID_TIME = 16, - - //! 64-bit seconds since epoch. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_SEC = 17, - - //! 64-bit milliseconds since epoch. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_MS = 18, - - //! 64-bit microseconds since epoch. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP = 19, - - //! 64-bit nanoseconds since epoch. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_NS = 20, - - //! Decimal with width and scale parameters. - DUCKDB_V2_LOGICAL_TYPE_ID_DECIMAL = 21, - DUCKDB_V2_LOGICAL_TYPE_ID_FLOAT = 22, - DUCKDB_V2_LOGICAL_TYPE_ID_DOUBLE = 23, - DUCKDB_V2_LOGICAL_TYPE_ID_VARCHAR = 25, - DUCKDB_V2_LOGICAL_TYPE_ID_BLOB = 26, - DUCKDB_V2_LOGICAL_TYPE_ID_INTERVAL = 27, - DUCKDB_V2_LOGICAL_TYPE_ID_UTINYINT = 28, - DUCKDB_V2_LOGICAL_TYPE_ID_USMALLINT = 29, - DUCKDB_V2_LOGICAL_TYPE_ID_UINTEGER = 30, - DUCKDB_V2_LOGICAL_TYPE_ID_UBIGINT = 31, - - //! 64-bit microseconds since epoch, timezone-aware. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_TZ = 32, - - //! 64-bit nanoseconds since epoch, timezone-aware. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_TZ_NS = 33, - - //! 64-bit microseconds since midnight + 32-bit offset. - DUCKDB_V2_LOGICAL_TYPE_ID_TIME_TZ = 34, - - //! 64-bit nanoseconds since midnight. - DUCKDB_V2_LOGICAL_TYPE_ID_TIME_NS = 35, - DUCKDB_V2_LOGICAL_TYPE_ID_BIT = 36, - - //! Arbitrary-precision integer (VARINT-encoded). - DUCKDB_V2_LOGICAL_TYPE_ID_BIGNUM = 39, - DUCKDB_V2_LOGICAL_TYPE_ID_UHUGEINT = 49, - DUCKDB_V2_LOGICAL_TYPE_ID_HUGEINT = 50, - DUCKDB_V2_LOGICAL_TYPE_ID_UUID = 54, - - //! Geometry (spatial extension). - DUCKDB_V2_LOGICAL_TYPE_ID_GEOMETRY = 60, - - //! Geography (spatial extension); like GEOMETRY, but with spherical edges. - DUCKDB_V2_LOGICAL_TYPE_ID_GEOGRAPHY = 61, - DUCKDB_V2_LOGICAL_TYPE_ID_STRUCT = 100, - DUCKDB_V2_LOGICAL_TYPE_ID_LIST = 101, - DUCKDB_V2_LOGICAL_TYPE_ID_MAP = 102, - DUCKDB_V2_LOGICAL_TYPE_ID_ENUM = 104, - DUCKDB_V2_LOGICAL_TYPE_ID_UNION = 107, - DUCKDB_V2_LOGICAL_TYPE_ID_ARRAY = 108, - DUCKDB_V2_LOGICAL_TYPE_ID_VARIANT = 109, - - //! Unnamed struct; shares the physical representation of STRUCT. - DUCKDB_V2_LOGICAL_TYPE_ID_TUPLE = 110, - DUCKDB_V2_LOGICAL_TYPE_ID_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_LOGICAL_TYPE_ID; - -/* --- Struct forward declarations for logical_type --- */ - -/* --- Types for logical_type --- */ - -/* --- Constants for logical_type --- */ - -/* --- Function pointer typedefs for logical_type --- */ - -/* --- Functions for logical_type --- */ - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Creates a logical type from a type id plus value parameters. - * - * The id-keyed twin of factory_create_type_from_name: the type id names the kind, and the parameters bind it. With - * param_count 0 it instantiates a primitive directly, without touching the catalog: BOOLEAN, TINYINT..BIGINT, - * UTINYINT..UBIGINT, HUGEINT, UHUGEINT, FLOAT, DOUBLE, DATE, every TIME and TIMESTAMP variant, INTERVAL, VARCHAR, BLOB, - * BIT, BIGNUM, and UUID. ANY is accepted as well. - * - * ANY is a function-signature wildcard, constructible here so it can be passed to the function parameter and varargs - * setters, as a fixed-arity ANY parameter or an ANY varargs type. Data-creating surfaces reject it: value and data - * chunk creation, scalar and aggregate return types, table function result columns, cast source and target types, and - * custom type registration. - * - * With parameters, the id resolves to its canonical built-in type and binds through the same constructors as - * factory_create_type_from_name, so the parameterized kinds construct here too: decimal(width, scale); list(T); - * array(T, size); map(K, V); struct(fields); union(members); enum(entries); and varchar with a named "collation" - * parameter. Parameters are (name, value) pairs in two parallel arrays, exactly as for factory_create_type_from_name. - * - * Returns ERROR_INPUT_INVALID when param_count is 0 and the id needs parameters (DECIMAL, LIST, STRUCT, TUPLE, MAP, - * ARRAY, UNION, ENUM, VARIANT, GEOMETRY, GEOGRAPHY), for the bind-time-only ids (SQLNULL, UNKNOWN), for TYPE — - * construct that via factory_create_type_from_text — and for INVALID. - * - * history: - * - unstable: v2.0.0 - * - * @param factory The factory to resolve the type in. - * @param type_id The type id to instantiate. - * @param param_names Optional. An array of param_count parameter names; an empty entry (NULL or zero length) is - * positional. Pass NULL for all-positional parameters. - * @param param_names_lengths Byte lengths of the entries in `param_names`; element i is the length of `param_names[i]`. - * May be NULL only when `param_names` is NULL. - * @param param_values An array of param_count parameter values. Borrowed (copied in). Pass NULL when param_count is 0. - * @param param_count The number of parameters. 0 instantiates a parameterless primitive. - * @param out_type Receives the new logical type handle. - * @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_factory_create_type_from_id( - duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char *const *param_names, - const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, - duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Creates a logical type from a type name plus value parameters. - * - * The generic constructor: resolves the name in the factory's catalog and binds it with the given parameters, exactly - * as SQL binds a type expression. Built-in parameterized kinds and registered extension types construct through this - * same call. - * - * An unqualified name is resolved along the search path first and then in the system catalog, which is where the - * 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, - * as named or all-positional TYPE values); union(members, as named TYPE values); enum(entries, as VARCHAR values); and - * varchar with a named "collation" VARCHAR parameter. - * - * A name that resolves to a type with no bind function takes no parameters, and passing any fails. Bind errors — - * unknown name, wrong parameter count or types — surface from the call. - * - * Resolves in the scope of the factory: a connection's or callback's factory reaches the catalog, an instance's factory - * knows only the built-in types. A connection's factory looks up catalog types in the connection's transaction, or in - * one of its own when none is open. Through an instance's factory, only an unqualified built-in name resolves. - * - * The returned logical type is caller-owned and must be destroyed via logical_type_destroy. A type resolved from the - * catalog shares database-owned storage, such as an ENUM dictionary, so destroy it before closing the database. This is - * the inverse of logical_type_get_param_count / logical_type_get_param. - * - * history: - * - unstable: v2.0.0 - * - * @param factory The factory to resolve the type in. - * @param name The type name to resolve. Parts are matched case-insensitively; qualify it to name a type in a particular - * catalog or schema. - * @param param_names Optional. An array of param_count parameter names; an empty entry (NULL or zero length) is - * positional. Pass NULL for all-positional parameters. - * @param param_names_lengths Byte lengths of the entries in `param_names`; element i is the length of `param_names[i]`. - * May be NULL only when `param_names` is NULL. - * @param param_values An array of param_count parameter values. Borrowed (copied in). Pass NULL when param_count is 0. - * @param param_count The number of parameters. - * @param out_type Receives the new logical type handle. - * @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_factory_create_type_from_name( - duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char *const *param_names, - const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, - duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Creates a logical type by parsing SQL text. - * - * Parses a SQL type expression and returns the bound logical type. It accepts primitives ("INTEGER"), parameterized - * kinds ("DECIMAL(18,3)", "INTEGER[]", "STRUCT(a INTEGER, b VARCHAR)", "MAP(VARCHAR, INTEGER)", "INTEGER[3]", "UNION(i - * INTEGER, s VARCHAR)", "ENUM('a', 'b')"), and catalog-registered type names, both user-defined and from extensions. A - * catalog type name binds to its structural type, and the name is not preserved as an alias. Names are - * case-insensitive. Parse and bind errors surface from the call. - * - * Resolves in the scope of the factory: a connection's or callback's factory reaches the catalog, an instance's factory - * knows only the built-in types. A connection's factory looks up catalog types in the connection's transaction, or in - * one of its own when none is open. Text naming only built-in types never touches the catalog. - * - * The returned logical type is caller-owned and must be destroyed via logical_type_destroy. A type resolved from the - * catalog shares database-owned storage, such as an ENUM dictionary, so destroy it before closing the database. This is - * the inverse of logical_type_to_text for every constructible kind. - * - * history: - * - unstable: v2.0.0 - * - * @param factory The factory to resolve the type in. - * @param text The SQL type expression to parse. - * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this - * is 0. - * @param out_type Receives the new logical type handle. - * @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_factory_create_type_from_text(duckdb_v2_factory_handle factory, const char *text, - idx_t text_length, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Creates a copy of a logical type. - * - * On success, writes the new caller-owned handle into *out_type; destroy it via logical_type_destroy. - * - * history: - * - unstable: v2.0.0 - * - * @param type The logical type to copy. - * @param out_type Receives the new logical type handle. - * @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_logical_type_copy(duckdb_v2_logical_type_handle type, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Destroys a logical type handle. - * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. On success the slot is set to nullptr. - * - * history: - * - unstable: v2.0.0 - * - * @param type The logical type to destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_destroy(duckdb_v2_logical_type_handle *type); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Compares two logical types for deep equality. - * - * Two types are equal when they agree in kind and in every parameter, recursively. DECIMAL(10, 2) equals DECIMAL(10, - * 2), but not DECIMAL(10, 3) and not FLOAT; two STRUCTs are equal when they have the same field names in the same order - * and equal field types. - * - * history: - * - unstable: v2.0.0 - * - * @param left The first logical type. - * @param right The second logical type. - * @param result Receives the result of the comparison. - * @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_logical_type_is_equal(duckdb_v2_logical_type_handle left, - duckdb_v2_logical_type_handle right, bool *result, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the logical type id. - * - * history: - * - unstable: v2.0.0 - * - * @param type The logical type. - * @param out_id Receives the type id. - * @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_logical_type_get_id(duckdb_v2_logical_type_handle type, - DUCKDB_V2_LOGICAL_TYPE_ID *out_id, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Borrows the logical type's name. - * - * The alias when one is set — an extension or user-defined name such as "POINT_2D" — otherwise the canonical name of - * the type id, such as "INTEGER", "DECIMAL", or "TIMESTAMP WITH TIME ZONE". Never the empty view. This is exactly the - * name vocabulary create_type_from_name accepts. The view is valid until the logical type is destroyed; a canonical - * name points at static storage. - * - * history: - * - unstable: v2.0.0 - * - * @param type The logical type. - * @param out_name Receives a borrowed pointer to the name (alias when set, else the id's canonical name). - * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be - * null-terminated. - * @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_logical_type_get_name(duckdb_v2_logical_type_handle type, const char **out_name, - idx_t *out_name_length, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Renders a logical type as SQL text. - * - * An aliased type renders as its alias, and create_type_from_text resolves that spelling only when the name is - * registered in the factory's catalog. The text round-trips through create_type_from_text for every constructible kind, - * with one exception: ANY renders as "ANY", but create_type_from_text cannot parse it back, since ANY is a signature - * wildcard rather than a parseable SQL type. - * - * Writes into a caller-supplied buffer, so nothing is allocated on the caller's behalf and nothing has to be freed. - * Pass out_text = NULL to size the buffer without rendering into it: out_length then receives the length, and - * out_capacity is ignored. With out_text != NULL, out_capacity must be at least out_length + 1, or the call returns - * ERROR_INPUT_OBJECT_SIZE with out_length set to the required length and out_text left untouched. - * - * out_length never counts the terminator, but a successful write always appends one, so the buffer is usable as a C - * string. - * - * history: - * - unstable: v2.0.0 - * - * @param type The logical type. - * @param out_text Caller-owned buffer receiving the text plus a null terminator, or NULL to only report the required - * length in out_length. - * @param out_capacity Bytes available in out_text, terminator included. Ignored when out_text is NULL. - * @param out_length Receives the text length excluding the null terminator — written on success and on - * ERROR_INPUT_OBJECT_SIZE. - * @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_logical_type_to_text(duckdb_v2_logical_type_handle type, char *out_text, - idx_t out_capacity, idx_t *out_length, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the number of value parameters of a logical type. - * - * The inspection dual of create_type_from_name: these are the parameters that reconstruct the type through it. Per - * kind: DECIMAL 2 (width, scale); LIST 1 (element type); ARRAY 2 (element type, size); MAP 2 (key type, value type); - * STRUCT and TUPLE one per field; UNION one per member; ENUM one per dictionary entry; VARCHAR 1 when a collation is - * set, else 0; GEOMETRY and GEOGRAPHY 1 when a coordinate system is set, else 0; everything else 0. A bound type - * reports only what it actually carries, so a bind-time modifier that is not retained — an ignored VARCHAR length, say - * — does not reappear. - * - * history: - * - unstable: v2.0.0 - * - * @param type The logical type. - * @param out_count Receives the number of parameters. - * @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_logical_type_get_param_count(duckdb_v2_logical_type_handle type, - idx_t *out_count, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns one value parameter of a logical type. - * - * out_name receives a borrowed view of the parameter name — a STRUCT field name, a UNION member name, "collation" — or - * an empty name for a positional parameter. A non-empty view is valid until the logical type is destroyed. out_value - * receives an owned value, destroyed via value_destroy: child types come back as TYPE values (unwrap them with - * value_get_type), DECIMAL width and scale as UINTEGER, ARRAY size as BIGINT, and ENUM dictionary entries and - * collations as VARCHAR. An out-of-range index returns ERROR_INPUT_INVALID. Each call allocates one owned value. - * - * history: - * - unstable: v2.0.0 - * - * @param type The logical type. - * @param index The parameter index, in [0, param_count). - * @param out_name Receives a borrowed pointer to the parameter name, or NULL with a zero length for a positional - * parameter. - * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be - * null-terminated. - * @param out_value Receives the owned parameter 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_logical_type_get_param(duckdb_v2_logical_type_handle type, idx_t index, - const char **out_name, idx_t *out_name_length, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Creates a logical type that is an alias of another logical type. - * - * The alias keeps the base type's internal representation, so executing against it needs no special handling, while - * remaining logically distinct from the base type. Intended for custom type bind callbacks, where both the base type - * and the name come from the bind info. - * - * The alias is not registered anywhere, so this works through any factory. An empty alias name returns - * ERROR_INPUT_INVALID. - * - * history: - * - unstable: v2.0.0 - * - * @param factory The factory to resolve the type in. - * @param base_type The logical type to alias. Typically the base type supplied in the custom type bind info. - * @param alias_name The name for the resulting type. Typically the name of the custom type being constructed, also - * available from the bind info. - * @param alias_name_length The length of `alias_name` in bytes. `alias_name` must be valid UTF-8, need not be - * null-terminated, and may be NULL only when this is 0. - * @param out_type Receives the new type: the base type's internal representation under the given alias name. - * @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_factory_create_type_with_alias(duckdb_v2_factory_handle factory, - duckdb_v2_logical_type_handle base_type, - const char *alias_name, idx_t alias_name_length, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Creates the common type of a set of logical types. - * - * The common type is the type every input implicitly casts to, resolved by the same rule a SQL list literal and - * value_create_list follow: INTEGER and BIGINT resolve to BIGINT, and DECIMAL(4,1) and DECIMAL(5,4) to DECIMAL(7,4). - * The types are combined pairwise from left to right, and the result is not guaranteed to be independent of their - * order. - * - * A connection's or a callback's factory also applies the casts that extensions registered, while an instance's factory - * knows only the built-in ones, so the two can resolve the same set differently. A single type resolves to a copy of - * itself. - * - * Returns ERROR_INPUT_INVALID for an empty set, for a NULL entry and for ANY, and ERROR_QUERY_NOT_IMPLEMENTED when the - * types have no common type. - * - * history: - * - unstable: v2.0.0 - * - * @param factory The factory to resolve the type in. - * @param types An array of type_count logical types. Borrowed. - * @param type_count The number of types. Must be at least 1. - * @param out_type Receives the new logical type handle. - * @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_factory_create_common_type(duckdb_v2_factory_handle factory, - const duckdb_v2_logical_type_handle *types, - idx_t type_count, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); -#endif - -/* --- Struct definitions for logical_type --- */ - -/* ============================================================================ - * MODULE: macro - * ============================================================================ */ - -/* --- Enums for macro --- */ - -//! The kind of a macro function, deciding how its body is read. Pass one to `duckdb_v2_macro_function_create()`. -typedef enum DUCKDB_V2_MACRO_FUNCTION_TYPE { - //! A scalar macro. The body is a single expression, and the macro is called like a scalar function. - DUCKDB_V2_MACRO_FUNCTION_TYPE_SCALAR = 0, - - //! A table macro. The body is a single SELECT query, and the macro is called like a table function. - DUCKDB_V2_MACRO_FUNCTION_TYPE_TABLE = 1, - DUCKDB_V2_MACRO_FUNCTION_TYPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_MACRO_FUNCTION_TYPE; - -/* --- Struct forward declarations for macro --- */ - -/* --- Types for macro --- */ - -/*! - * An owned opaque handle to a macro function being built. Created with `duckdb_v2_macro_function_create()`, configured - * with `duckdb_v2_macro_function_set_name()`, `duckdb_v2_macro_function_set_body()` and the signature obtained via - * `duckdb_v2_macro_function_get_signature()`, made available with `duckdb_v2_extension_register_macro_function()`, and - * destroyed with `duckdb_v2_macro_function_destroy()`. - */ -typedef struct _duckdb_v2_macro_function { - void *internal_ptr; -} * duckdb_v2_macro_function_handle; - -/* --- Constants for macro --- */ - -/* --- Function pointer typedefs for macro --- */ - -/* --- Functions for macro --- */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_get_docs(duckdb_v2_scalar_function_handle function, + duckdb_v2_function_docs_handle *docs, + duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new macro function through a factory. - * - * The macro function starts out empty: configure it with the setter functions and the signature obtained via - * `duckdb_v2_macro_function_get_signature()`, then make it available with - * `duckdb_v2_extension_register_macro_function()`. The caller owns the returned handle and must destroy it with - * `duckdb_v2_macro_function_destroy()`, also after registration. + * Returns the function's signature so it can be configured. * - * The macro function can only be registered on the database the factory belongs to. + * Add parameters with `duckdb_v2_function_signature_add_parameter()` and set the return type with + * `duckdb_v2_function_signature_set_return_type()`. The signature is modified in place; the function must be given a + * signature with a return type before registration. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the macro function through. - * @param type Whether the macro is a scalar or a table macro. - * @param function On success, receives the newly created macro function. Owned by the caller. + * @param function The function to get the signature of. + * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. * @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_macro_function_create(duckdb_v2_factory_handle factory, - DUCKDB_V2_MACRO_FUNCTION_TYPE type, - duckdb_v2_macro_function_handle *function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_get_signature(duckdb_v2_scalar_function_handle function, + duckdb_v2_function_signature_handle *sig, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the macro function, as SQL calls it. + * Sets arbitrary user data on the scalar function. * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * Associates an opaque pointer with the function, retrievable from the callbacks via + * `duckdb_v2_function_bind_get_user_data()`, `duckdb_v2_scalar_function_init_get_user_data()` and + * `duckdb_v2_scalar_function_exec_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, + * invoked when the data is no longer needed. * * history: * - unstable: v2.0.0 * - * @param function The macro function to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. + * @param function The function to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. * @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_macro_function_set_name(duckdb_v2_macro_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_user_data(duckdb_v2_scalar_function_handle function, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the body of the macro function, as SQL text. + * Sets a property on the scalar function. * - * For a scalar macro the body is a single expression, for a table macro a single SELECT query. It refers to the - * parameters by name. The body is parsed at registration, which fails on a syntax error; names in it are resolved only - * when the macro is called, as with SQL `CREATE MACRO`. The body is borrowed and copied. Calling this again replaces - * the previous body. A body must be set before registration. + * Configures a function property that influences planning and execution, such as stability, NULL handling, fallibility + * or collation handling. The value must be one of the `DUCKDB_V2_FUNCTION_PROPERTY_VALUE` entries belonging to `key`; + * passing a value that does not belong to the key, or a key that is not valid for scalar functions, results in an + * error. * * history: * - unstable: v2.0.0 * - * @param function The macro function to set the body of. - * @param body The SQL text of the body. Borrowed and copied. - * @param body_length The length of `body` in bytes. `body` need not be null-terminated and may be NULL only when this - * is 0. + * @param function The function to set the property of. + * @param key The property to set. + * @param value The value to set for the property. Must belong to `key`. * @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_macro_function_set_body(duckdb_v2_macro_function_handle function, - const char *body, idx_t body_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_property(duckdb_v2_scalar_function_handle function, + DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the macro function's signature so its parameters can be declared. + * Sets a generic, named property on the scalar function. * - * Add parameters with `duckdb_v2_function_signature_add_parameter()`. A macro's parameters can always be passed by - * position or by name, so only `FUNCTION_PARAMETER_KIND_STANDARD` parameters are accepted; a macro has no variadic - * parameters. A parameter of type ANY is untyped, and a parameter with a default value can be omitted by a caller. A - * macro's result is decided by its body, so the signature cannot set a return type. Registration fails on a signature - * that does not follow these rules. The signature is modified in place. + * Generic properties are free-form `name = value` pairs that the engine or extensions can read from a function, e.g. + * `duckdb.collation.combinable = true` marks a collation function as combinable. Setting a property that is already set + * replaces its value. Reading a property that is not set yields NULL, which boolean properties treat as false. * * history: * - unstable: v2.0.0 * - * @param function The macro function to get the signature of. - * @param sig The returned signature. Borrowed and valid for the lifetime of the macro function handle. + * @param function The function to set the property of. + * @param name The name of the property, e.g. `duckdb.collation.combinable`. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param value The value of the property. Borrowed (copied in). * @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_macro_function_get_signature(duckdb_v2_macro_function_handle function, - duckdb_v2_function_signature_handle *sig, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_generic_property(duckdb_v2_scalar_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the documentation of the macro function so it can be filled in. + * Reads a generic, named property of the scalar function, as set by `duckdb_v2_scalar_function_set_generic_property()`. * - * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with - * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified - * in place and registered with the macro function. Optional. + * A property that is not set is not an error: `out_value` then receives NULL. * * history: * - unstable: v2.0.0 * - * @param function The macro function to get the documentation of. - * @param docs The returned documentation. Borrowed and valid for the lifetime of the macro function handle. + * @param function The function to read the property of. + * @param name The name of the property, e.g. `duckdb.collation.combinable`. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param out_value Receives the value of the property, owned by the caller, or NULL if the property is not set. * @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_macro_function_get_docs(duckdb_v2_macro_function_handle function, - duckdb_v2_function_docs_handle *docs, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_get_generic_property(duckdb_v2_scalar_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the macro function, making it available for use in SQL queries. + * Sets the optional resolve types callback of the scalar function. * - * The macro function is registered on the loading extension's database and attributed to the extension. Use this from - * the extension's load callback. Registration requires a name and a body that parses, and a signature that follows the - * rules of `duckdb_v2_macro_function_get_signature()`. It fails when a function of the same name already exists: a - * macro function has a single overload. The macro function must have been created through a factory of the same - * database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_macro_function_destroy()`, which does not affect the registered macro function. + * The resolve types callback is invoked during query planning for each call site of the function, before the arguments + * are cast to the parameter types of the signature. Through its `duckdb_v2_function_bind_info_handle` it can inspect + * the argument types as they were passed and constant argument values. Through its + * `duckdb_v2_scalar_function_resolve_types_info_handle` it can set a concrete return type. It cannot set "bind data", + * use the bind callback for that. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The macro function to register. + * @param function The function to set the resolve types callback of. + * @param callback The resolve types callback to set. * @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_extension_register_macro_function(duckdb_v2_extension_handle extension, - duckdb_v2_macro_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_resolve_types_callback( + duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_resolve_types_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the macro function, releasing its resources. + * Sets the optional bind callback of the scalar function. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered macro function. + * The bind callback is invoked during query planning for each call site of the function, after the resolve types + * callback and after the arguments have been cast to the parameter types of the signature. Through its + * `duckdb_v2_function_bind_info_handle` it can inspect the argument types and constant argument values. Through its + * `duckdb_v2_scalar_function_bind_info_handle` it can set "bind data" that is shared with the init and exec callbacks. + * It cannot change the types of the call site, use the resolve types callback for that. * * history: * - unstable: v2.0.0 * - * @param function The macro function to destroy. + * @param function The function to set the bind callback of. + * @param callback The bind callback to set. + * @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_macro_function_destroy(duckdb_v2_macro_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_bind_callback( + duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_bind_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for macro --- */ - -/* ============================================================================ - * MODULE: pragma - * ============================================================================ */ - -/* --- Enums for pragma --- */ - -/* --- Struct forward declarations for pragma --- */ - -/* --- Types for pragma --- */ - +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * An owned opaque handle to a custom pragma function being built. Created with `duckdb_v2_pragma_function_create()`, - * configured with the setter functions (e.g. `duckdb_v2_pragma_function_set_name()`, - * `duckdb_v2_pragma_function_set_query_callback()`, etc.) and the signature obtained via - * `duckdb_v2_pragma_function_get_signature()`, made available with `duckdb_v2_connection_register_pragma_function()` or - * `duckdb_v2_extension_register_pragma_function()`, and destroyed with `duckdb_v2_pragma_function_destroy()`. + * Sets the optional init callback of the scalar function. + * + * The init callback is invoked at the start of execution for each thread that will execute the function. It can set + * worker-local "init data", retrievable from the exec callback, to keep mutable state across invocations of the + * function. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the init callback of. + * @param callback The init callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_pragma_function { - void *internal_ptr; -} * duckdb_v2_pragma_function_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_init_callback( + duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_init_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to the result of a pragma function's "query" callback. The query callback receives this - * handle next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments and the user data, and - * uses it to set the query to run in place of the `PRAGMA` statement. + * Sets the exec callback of the scalar function. + * + * The exec callback implements the function's logic: it is invoked during query execution with a batch of input rows + * and must fill the result vector. An exec callback must be set before registration. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the exec callback of. + * @param callback The exec callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_pragma_function_query_info { - void *internal_ptr; -} * duckdb_v2_pragma_function_query_info_handle; - -/* --- Constants for pragma --- */ - -/* --- Function pointer typedefs for pragma --- */ - -typedef void (*duckdb_v2_pragma_function_query_callback_fn)(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); - -typedef void (*duckdb_v2_pragma_function_exec_callback_fn)(duckdb_v2_function_bind_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -/* --- Functions for pragma --- */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_exec_callback( + duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_exec_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new pragma function through a factory. + * Sets the optional stats callback of the scalar function. * - * The function starts out empty: configure it with the setter functions (e.g. `duckdb_v2_pragma_function_set_name()`, - * `duckdb_v2_pragma_function_set_query_callback()`, etc.) and the signature obtained via - * `duckdb_v2_pragma_function_get_signature()`, then make it available with - * `duckdb_v2_connection_register_pragma_function()` or `duckdb_v2_extension_register_pragma_function()`. The caller - * owns the returned handle and must destroy it with `duckdb_v2_pragma_function_destroy()`, also after registration. + * The stats callback is invoked during query optimization for each call site of the function, after it has been bound. + * Through its `duckdb_v2_scalar_function_stats_info_handle` it reads the statistics of the arguments and narrows the + * statistics of the result, which the engine then uses to simplify the query. A function without a stats callback gives + * the engine no statistics for its result. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the stats callback of. + * @param callback The stats callback to set. + * @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_scalar_function_set_stats_callback( + duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_stats_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the concrete return type of the call site being bound. * - * The pragma function can only be registered on the database the factory belongs to. + * Overrides the return type declared in the signature. Register the function with an ANY return type and set the + * concrete type here, derived from the argument types, to build a function whose result type depends on its input. The + * type is borrowed and copied. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the pragma function through. - * @param function On success, receives the newly created pragma function. Owned by the caller. + * @param info The resolve types info handle. + * @param return_type The return type to set. Borrowed for the call only. * @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_pragma_function_create(duckdb_v2_factory_handle factory, - duckdb_v2_pragma_function_handle *function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_resolve_types_set_return_type( + duckdb_v2_scalar_function_resolve_types_info_handle info, duckdb_v2_logical_type_handle return_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the pragma function, as the `PRAGMA` statement calls it. + * Sets the function's "bind data" from the bind callback. * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * The bind data is stored with the bound call site and retrievable from the init and exec callbacks. The opaque handle + * bundles the pointer with an optional destructor, invoked when the bind data is no longer needed, and an optional + * equality callback used when comparing two bound call sites; without one, pointer equality is used. Scalar functions + * set their bind data through this function, `duckdb_v2_function_bind_set_bind_data()` is not available to them. * * history: * - unstable: v2.0.0 * - * @param function The function to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. + * @param info The bind info handle. + * @param data Opaque handle bundling the bind data pointer plus optional destructor and equality callbacks. * @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_pragma_function_set_name(duckdb_v2_pragma_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_bind_set_bind_data( + duckdb_v2_scalar_function_bind_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the documentation of the function so it can be filled in. - * - * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with - * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified - * in place and registered with the function. Optional. + * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param function The function to get the documentation of. - * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. + * @param info The init info handle. + * @param data Receives the user data pointer, or null if none was set. * @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_pragma_function_get_docs(duckdb_v2_pragma_function_handle function, - duckdb_v2_function_docs_handle *docs, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_init_get_user_data( + duckdb_v2_scalar_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the function's signature so it can be configured. - * - * Add parameters with `duckdb_v2_function_signature_add_parameter()`. A pragma produces no value, so its signature - * cannot set a return type. A signature without parameters makes a pragma called as `PRAGMA name`. The signature is - * modified in place. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param function The function to get the signature of. - * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. + * @param info The init info handle. + * @param data Receives the bind data pointer, or null if none was set. * @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_pragma_function_get_signature(duckdb_v2_pragma_function_handle function, - duckdb_v2_function_signature_handle *sig, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_init_get_bind_data( + duckdb_v2_scalar_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the pragma function. + * Sets the function's worker-local "init data" from the init callback. * - * Associates an opaque pointer with the function, retrievable from the callbacks via - * `duckdb_v2_function_bind_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, invoked - * when the data is no longer needed. + * The init data is associated with the executing thread for the duration of the query and retrievable from the exec + * callback via `duckdb_v2_scalar_function_exec_get_init_data()`. The opaque handle bundles the pointer with an optional + * destructor, invoked when the init data is no longer needed. * * history: * - unstable: v2.0.0 * - * @param function The function to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param info The init info handle. + * @param data Opaque handle bundling the init data pointer plus an optional destructor. * @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_pragma_function_set_user_data(duckdb_v2_pragma_function_handle function, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_init_set_init_data( + duckdb_v2_scalar_function_init_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the query callback of the pragma function, making it a query pragma. - * - * The query callback is invoked before the `PRAGMA` statement is bound, and must set a SQL string through - * `duckdb_v2_pragma_function_query_set_query()`. The string is parsed and its statements run in place of the `PRAGMA` - * statement. A pragma function has either a query callback or an exec callback; registration fails when both or neither - * are set. + * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param function The function to set the query callback of. - * @param callback The query callback to set. + * @param info The exec info handle. + * @param data Receives the user data pointer, or null if none was set. * @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_pragma_function_set_query_callback( - duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_query_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_user_data( + duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the exec callback of the pragma function, making it an exec pragma. - * - * The exec callback is invoked when the `PRAGMA` statement executes, and runs for its side effects: the statement - * produces no rows. A pragma function has either a query callback or an exec callback; registration fails when both or - * neither are set. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param function The function to set the exec callback of. - * @param callback The exec callback to set. + * @param info The exec info handle. + * @param data Receives the bind data pointer, or null if none was set. * @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_pragma_function_set_exec_callback( - duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_bind_data( + duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the SQL to run in place of the `PRAGMA` statement. - * - * The query may hold several statements, separated by semicolons. It is borrowed and copied. Calling this again - * replaces the previous query. The query callback must set a query. + * Retrieves the worker-local init data set by the function's init callback. * * history: * - unstable: v2.0.0 * - * @param info The query info handle. - * @param query The SQL to run. Borrowed and copied. - * @param query_length The length of `query` in bytes. `query` need not be null-terminated and may be NULL only when - * this is 0. + * @param info The exec info handle. + * @param data Receives the init data pointer for the executing thread, or null if none was set. * @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_pragma_function_query_set_query(duckdb_v2_pragma_function_query_info_handle info, - const char *query, idx_t query_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_init_data( + duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the pragma function, making it available to the `PRAGMA` statement. - * - * The function is registered on the connection's database, visible to every connection, in the connection's - * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. Registration requires a name and exactly one of a query callback or an exec callback, and fails - * when a pragma of the same name already exists. The pragma function must have been created through a factory of the - * same database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_pragma_function_destroy()`, which does not affect the registered function. + * Returns how many rows this execution must produce. The exec callback must write exactly this many rows to the result + * vector. Note that this may be less than a full vector: with all-constant arguments the function is invoked for a + * single row and the result is expanded by the engine. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param function The pragma function to register. + * @param info The exec info handle. + * @param count Receives the number of rows. * @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_register_pragma_function(duckdb_v2_connection_handle conn, - duckdb_v2_pragma_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_row_count( + duckdb_v2_scalar_function_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the pragma function, making it available to the `PRAGMA` statement. + * Returns how many argument vectors this invocation carries, split into the four parts of the argument list. * - * The function is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. Registration requires a name and exactly one of a query callback or an exec callback, and - * fails when a pragma of the same name already exists. The pragma function must have been created through a factory of - * the same database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_pragma_function_destroy()`, which does not affect the registered function. + * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the + * vectors are at the same indices. Valid indices for `duckdb_v2_scalar_function_exec_get_arg()` are [0, the sum of the + * four counts). Every out-parameter may be NULL, in which case nothing is written to it. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The pragma function to register. + * @param info The exec info handle. + * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. + * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has + * none. + * @param named_fixed Optional. Receives the number of named-only parameters. + * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. * @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_extension_register_pragma_function(duckdb_v2_extension_handle extension, - duckdb_v2_pragma_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_arg_count( + duckdb_v2_scalar_function_exec_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, + idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the pragma function, releasing its resources. + * Retrieves the argument vector at the given index. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered function. + * The index is the one the bind callback used for the argument, e.g. the index + * `duckdb_v2_function_bind_get_arg_index()` found for a name. The vector holds the argument's values for the current + * batch; use `duckdb_v2_scalar_function_exec_get_row_count()` for the number of rows. Fails if the index is out of + * bounds. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param function The function to destroy. + * @param info The exec info handle. + * @param index The index of the argument. + * @param vector Receives the borrowed argument vector. + * @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_pragma_function_destroy(duckdb_v2_pragma_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_arg(duckdb_v2_scalar_function_exec_info_handle info, + idx_t index, duckdb_v2_vector_handle *vector, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for pragma --- */ - -/* ============================================================================ - * MODULE: replacement scan - * ============================================================================ */ - -/* --- Enums for replacement scan --- */ - -/* --- Struct forward declarations for replacement scan --- */ - -/* --- Types for replacement scan --- */ - +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * An owned opaque handle to a replacement scan being built. Created with `duckdb_v2_replacement_scan_create()`, - * configured with `duckdb_v2_replacement_scan_set_callback()` and `duckdb_v2_replacement_scan_set_user_data()`, made - * available with `duckdb_v2_connection_register_replacement_scan()`, `duckdb_v2_instance_register_replacement_scan()` - * or `duckdb_v2_extension_register_replacement_scan()`, and destroyed with `duckdb_v2_replacement_scan_destroy()`. + * Retrieves the result vector the exec callback must write into. + * + * The callback must write one entry per input row; use `duckdb_v2_scalar_function_exec_get_row_count()` for the number + * of rows. Borrowed; valid only for the duration of the callback. + * + * history: + * - unstable: v2.0.0 + * + * @param info The exec info handle. + * @param vector Receives the borrowed result vector to write into. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_replacement_scan { - void *internal_ptr; -} * duckdb_v2_replacement_scan_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_result(duckdb_v2_scalar_function_exec_info_handle info, + duckdb_v2_vector_handle *vector, + duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to the arguments supplied to a replacement scan when the binder consults it. The callback - * receives this handle and can use it to inspect the unresolved name and to claim it by naming what to read instead. - * Valid only for the duration of the callback; the name it hands out is owned separately and outlives it. - */ -typedef struct _duckdb_v2_replacement_scan_info { - void *internal_ptr; -} * duckdb_v2_replacement_scan_info_handle; - -/* --- Constants for replacement scan --- */ - -/* --- Function pointer typedefs for replacement scan --- */ - -typedef void (*duckdb_v2_replacement_scan_callback_fn)(duckdb_v2_replacement_scan_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -/* --- Functions for replacement scan --- */ + * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The stats info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_scalar_function_stats_get_user_data( + duckdb_v2_scalar_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new replacement scan through a factory. - * - * The scan starts out empty: configure it with `duckdb_v2_replacement_scan_set_callback()` and optionally - * `duckdb_v2_replacement_scan_set_user_data()`, then make it available with - * `duckdb_v2_connection_register_replacement_scan()`, `duckdb_v2_instance_register_replacement_scan()` or - * `duckdb_v2_extension_register_replacement_scan()`. The caller owns the returned handle and must destroy it with - * `duckdb_v2_replacement_scan_destroy()`, also after registration. - * - * The scan can only be registered on the database the factory belongs to. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the scan through. - * @param scan On success, receives the newly created replacement scan. Owned by the caller. + * @param info The stats info handle. + * @param data Receives the bind data pointer, or null if none was set. * @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_replacement_scan_create(duckdb_v2_factory_handle factory, - duckdb_v2_replacement_scan_handle *scan, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_bind_data( + duckdb_v2_scalar_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback of the replacement scan. + * Returns how many arguments the call site has, split into the four parts of the argument list. * - * The callback is invoked during query planning for each table reference the catalog could not resolve. It can inspect - * the unresolved name via `duckdb_v2_replacement_scan_get_name()`, and claim the reference via - * `duckdb_v2_replacement_scan_set_function_name()`, `duckdb_v2_replacement_scan_set_collection()` or - * `duckdb_v2_replacement_scan_set_subquery()`; returning without claiming declines it. The context passed to the - * callback may be used to read settings, but not to run queries. A callback must be set before registration. + * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the + * arguments are at the same indices. Valid indices for `duckdb_v2_scalar_function_stats_get_arg_stats()` are [0, the + * sum of the four counts). Every out-parameter may be NULL, in which case nothing is written to it. * * history: * - unstable: v2.0.0 * - * @param scan The scan to set the callback of. - * @param callback The callback to set. + * @param info The stats info handle. + * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. + * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has + * none. + * @param named_fixed Optional. Receives the number of named-only parameters. + * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. * @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_replacement_scan_set_callback(duckdb_v2_replacement_scan_handle scan, - duckdb_v2_replacement_scan_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_arg_count( + duckdb_v2_scalar_function_stats_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, + idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the replacement scan. + * Retrieves the statistics of the argument at the given index. * - * Associates an opaque pointer with the scan, retrievable from the callback via - * `duckdb_v2_replacement_scan_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, - * invoked when the data is no longer needed, at the latest when the scan's scope ends. The callback may be invoked from - * several connections at once, so the data must be safe to read concurrently. + * The index is the one the bind callback used for the argument. The statistics are read-only. Fails if the index is out + * of bounds. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param scan The scan to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param info The stats info handle. + * @param index The index of the argument. + * @param stats Receives the borrowed, read-only statistics of the argument. * @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_replacement_scan_set_user_data(duckdb_v2_replacement_scan_handle scan, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_scalar_function_stats_get_arg_stats(duckdb_v2_scalar_function_stats_info_handle info, idx_t index, + duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_replacement_scan_set_user_data()`. + * Retrieves the statistics of the call site's result, for the callback to narrow. + * + * The statistics start out unknown, with every kind of value possible. Borrowed; valid only for the duration of the + * callback. * * history: * - unstable: v2.0.0 * - * @param info The info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param info The stats info handle. + * @param stats Receives the borrowed, writable statistics of the call site's result. * @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_replacement_scan_get_user_data(duckdb_v2_replacement_scan_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_result_stats( + duckdb_v2_scalar_function_stats_info_handle info, duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the name the catalog could not resolve. + * Registers the scalar function, making it available for use in SQL queries. * - * The name as written in the query, as a path: an unqualified reference has a single part, and a qualified one carries - * its catalog and schema before it -- see `duckdb_v2_qname_get_part()`. For a file-backed reference the single part is - * the path with the quotes stripped. The returned name is owned by the caller and must be destroyed via - * `duckdb_v2_qname_destroy()`; being owned, it may outlive the callback. + * The function is registered on the connection's database, visible to every connection, in the connection's + * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and + * a rollback undoes it. Registration requires a name, an exec callback, and a signature with a complete return type; an + * ANY return type is accepted only together with a resolve types callback that sets the concrete type per call site. + * The scalar function must have been created through a factory of the same database. The caller still owns the handle + * after registration and must destroy it with `duckdb_v2_scalar_function_destroy()`, which does not affect the + * registered function. * * history: * - unstable: v2.0.0 * - * @param info The info handle. - * @param name Receives the unresolved name. Owned by the caller; destroy via `duckdb_v2_qname_destroy()`. + * @param conn The connection to register on. + * @param function The scalar function to register. * @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_replacement_scan_get_name(duckdb_v2_replacement_scan_info_handle info, - duckdb_v2_qname_handle *name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_scalar_function(duckdb_v2_connection_handle conn, + duckdb_v2_scalar_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Claims the reference by naming a table function to read instead. - * - * Arguments to the function are added with `duckdb_v2_replacement_scan_add_argument()` and - * `duckdb_v2_replacement_scan_add_named_argument()`. The name is borrowed and copied, and its parts are matched - * case-insensitively. A qualified name targets a function in a particular schema or catalog, exactly as writing it out - * in SQL would. The name is not resolved here: an unknown function fails later, when the replacement is bound. Calling - * this again replaces the previous name and keeps the arguments added so far. + * Registers the scalar function, making it available for use in SQL queries. * - * The three claim forms, `duckdb_v2_replacement_scan_set_function_name()`, - * `duckdb_v2_replacement_scan_set_collection()` and `duckdb_v2_replacement_scan_set_subquery()`, are mutually - * exclusive: claiming the reference through a second, different form results in an error. + * The function is registered on the loading extension's database and attributed to the extension. Use this from the + * extension's load callback. Registration requires a name, an exec callback, and a signature with a complete return + * type; an ANY return type is accepted only together with a resolve types callback that sets the concrete type per call + * site. The scalar function must have been created through a factory of the same database. The caller still owns the + * handle after registration and must destroy it with `duckdb_v2_scalar_function_destroy()`, which does not affect the + * registered function. * * history: * - unstable: v2.0.0 * - * @param info The info handle. - * @param name The table function to read instead. Borrowed and copied. + * @param extension The loading extension. + * @param function The scalar function to register. * @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_replacement_scan_set_function_name(duckdb_v2_replacement_scan_info_handle info, - duckdb_v2_qname_handle name, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_scalar_function(duckdb_v2_extension_handle extension, + duckdb_v2_scalar_function_handle function, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Appends a positional argument to the claimed table function. + * Destroys the scalar function, releasing its resources. * - * Positional arguments are passed in the order they are added, before any named ones. The value is borrowed and copied, - * so the caller may destroy it after the call. Requires `duckdb_v2_replacement_scan_set_function_name()` to have been - * called first; otherwise the call results in an error. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered function. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_destroy(duckdb_v2_scalar_function_handle *function); +#endif + +/* --- Struct definitions for scalar --- */ + +/* ============================================================================ + * MODULE: sql_statement + * ============================================================================ */ + +/* --- Enums for sql_statement --- */ + +//! SQL statement type of a parsed statement or an executed query. +typedef enum DUCKDB_V2_STATEMENT_TYPE { + DUCKDB_V2_STATEMENT_TYPE_INVALID = 0, + DUCKDB_V2_STATEMENT_TYPE_SELECT = 1, + DUCKDB_V2_STATEMENT_TYPE_INSERT = 2, + DUCKDB_V2_STATEMENT_TYPE_UPDATE = 3, + DUCKDB_V2_STATEMENT_TYPE_CREATE = 4, + DUCKDB_V2_STATEMENT_TYPE_DELETE = 5, + DUCKDB_V2_STATEMENT_TYPE_PREPARE = 6, + DUCKDB_V2_STATEMENT_TYPE_EXECUTE = 7, + DUCKDB_V2_STATEMENT_TYPE_ALTER = 8, + DUCKDB_V2_STATEMENT_TYPE_TRANSACTION = 9, + DUCKDB_V2_STATEMENT_TYPE_COPY = 10, + DUCKDB_V2_STATEMENT_TYPE_ANALYZE = 11, + DUCKDB_V2_STATEMENT_TYPE_VARIABLE_SET = 12, + DUCKDB_V2_STATEMENT_TYPE_CREATE_FUNC = 13, + DUCKDB_V2_STATEMENT_TYPE_EXPLAIN = 14, + DUCKDB_V2_STATEMENT_TYPE_DROP = 15, + DUCKDB_V2_STATEMENT_TYPE_EXPORT = 16, + DUCKDB_V2_STATEMENT_TYPE_PRAGMA = 17, + DUCKDB_V2_STATEMENT_TYPE_VACUUM = 18, + DUCKDB_V2_STATEMENT_TYPE_CALL = 19, + DUCKDB_V2_STATEMENT_TYPE_SET = 20, + DUCKDB_V2_STATEMENT_TYPE_LOAD = 21, + DUCKDB_V2_STATEMENT_TYPE_RELATION = 22, + DUCKDB_V2_STATEMENT_TYPE_EXTENSION = 23, + DUCKDB_V2_STATEMENT_TYPE_LOGICAL_PLAN = 24, + DUCKDB_V2_STATEMENT_TYPE_ATTACH = 25, + DUCKDB_V2_STATEMENT_TYPE_DETACH = 26, + DUCKDB_V2_STATEMENT_TYPE_MULTI = 27, + DUCKDB_V2_STATEMENT_TYPE_COPY_DATABASE = 28, + DUCKDB_V2_STATEMENT_TYPE_UPDATE_EXTENSIONS = 29, + DUCKDB_V2_STATEMENT_TYPE_MERGE_INTO = 30, + DUCKDB_V2_STATEMENT_TYPE_CONNECT = 31, + DUCKDB_V2_STATEMENT_TYPE_DISCONNECT = 32, + DUCKDB_V2_STATEMENT_TYPE_EXTERNAL_RESOURCE = 33, + DUCKDB_V2_STATEMENT_TYPE_PASSTHROUGH = 34, + DUCKDB_V2_STATEMENT_TYPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_STATEMENT_TYPE; + +/* --- Struct forward declarations for sql_statement --- */ + +/* --- Types for sql_statement --- */ + +/*! + * An opaque, owned handle to a single parsed SQL statement, produced by statement_iterator_next. statement_execute runs + * it without consuming it; the caller always destroys it via sql_statement_destroy. + */ +typedef struct _duckdb_v2_sql_statement { + void *internal_ptr; +} * duckdb_v2_sql_statement_handle; + +/*! + * An opaque, owned handle to an iterator over the statements of a SQL string, produced by parse_sql. Destroy it via + * statement_iterator_destroy; statements it already yielded are independently owned and unaffected. + */ +typedef struct _duckdb_v2_statement_iterator { + void *internal_ptr; +} * duckdb_v2_statement_iterator_handle; + +/* --- Constants for sql_statement --- */ + +/* --- Function pointer typedefs for sql_statement --- */ + +/* --- Functions for sql_statement --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Parses a SQL string into an iterator over its statements. + * + * Parses and nothing more: no binding and no catalog access. The connection supplies the parser options and parser + * extensions. With apply_invalidation_policy, a parse error invalidates the connection's active transaction according + * to the transaction invalidation policy, like an error from running the statement would; pass that when the statements + * are parsed to be run. Without it, a parse error leaves the transaction usable, for callers that only inspect the + * statements, for example with `duckdb_v2_statement_bind()`. Statements are raw parser output; statement-level rewrites + * happen inside statement_execute. The SQL string is copied, so the caller may free it once this call returns. An input + * with no statements — empty, whitespace, or separators only — yields an iterator that is immediately exhausted. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection supplying the parser configuration. + * @param sql The SQL text, `sql_length` bytes long; may contain any number of statements. Need not be null-terminated. + * May be NULL only when `sql_length` is 0. + * @param sql_length The length of `sql` in bytes. + * @param apply_invalidation_policy Whether a parse error invalidates the active transaction, according to the + * transaction invalidation policy. + * @param out_iterator Receives the new iterator handle. + * @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_parse_sql(duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, + bool apply_invalidation_policy, + duckdb_v2_statement_iterator_handle *out_iterator, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Yields the next statement, or NULL when exhausted. + * + * On success *out_statement receives the next owned statement, or NULL once the iterator is exhausted — repeatedly, so + * calling again is harmless. A parse error within the input surfaces no later than the call that reaches the failing + * statement: an implementation that parses eagerly reports it from parse_sql instead and yields no statements at all, + * while an incremental one yields the statements ahead of the failure first. On failure *out_statement is set to NULL. * * history: * - unstable: v2.0.0 * - * @param info The info handle. - * @param value The argument value. Borrowed and copied. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param iterator The iterator to advance. + * @param out_statement Receives an owned statement, or NULL when the iterator is exhausted. + * @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_replacement_scan_add_argument(duckdb_v2_replacement_scan_info_handle info, - duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_iterator_next(duckdb_v2_statement_iterator_handle iterator, + duckdb_v2_sql_statement_handle *out_statement, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Appends a named argument to the claimed table function. + * Binds a parsed statement without executing, yielding its schema signature. * - * Equivalent to writing `name := value` at the call site. The name and the value are borrowed and copied, so the caller - * may destroy the value after the call. Requires `duckdb_v2_replacement_scan_set_function_name()` to have been called - * first; otherwise the call results in an error. + * Preprocesses and binds the statement exactly as execution would, but runs nothing: the result is the statement's + * signature as two schemas, not a query result. The statement is borrowed, not consumed, so it can be bound as often as + * you like and executed later. out_schema receives the output schema (result columns) and is never empty, since a + * non-SELECT reports a single status column: a BIGINT changed-rows count, or a BOOLEAN success. out_parameters, when + * non-NULL, receives the input schema (parameter types, ordered by binding index). Both are owned; destroy them via + * schema_destroy. + * + * Binding is read-only and does not disturb a live result: it begins no query, claims no cursor, reuses an active + * transaction read-only, and runs alongside a paused stream. It is single-consumer like the stepping functions, so bind + * concurrently only on a second connection. Errors of the bind itself (catalog lookups, type resolution, preprocessing) + * surface here; errors of the planning after the bind (the plan depth limit, a correlated subquery or trigger body that + * decorrelation refuses) may surface only when the statement is executed. A statement that expands into a group (a + * dynamic PIVOT, or statement-expanding DDL such as ALTER ADD COLUMN with a non-constant DEFAULT) has a schema known + * only at execution, and is reported with ERROR_INPUT_METADATA_DEFERRED; execute it instead. + * + * *out_schema and *out_parameters are set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param info The info handle. - * @param name The name of the parameter to bind the value to. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param value The argument value. Borrowed and copied. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param conn The connection supplying the catalog, transaction, and parser configuration. + * @param statement The statement to bind. Borrowed; not consumed. + * @param out_schema Receives the owned output schema (result columns). Destroy via schema_destroy. + * @param out_parameters Optional. When non-NULL, receives the owned input schema (parameter types, ordered by binding + * index). Destroy via schema_destroy. + * @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_replacement_scan_add_named_argument(duckdb_v2_replacement_scan_info_handle info, - const char *name, idx_t name_length, - duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_bind(duckdb_v2_connection_handle conn, + duckdb_v2_sql_statement_handle statement, + duckdb_v2_schema_handle *out_schema, + duckdb_v2_schema_handle *out_parameters, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Claims the reference by naming a column data collection to read instead. + * Binds a column data collection to the statement under a name. * - * The collection is borrowed, not copied: the caller keeps ownership and must keep it alive, and must not clear, reset - * or destroy it, for as long as any result reading it is live, since the result scans its buffers directly. + * Makes the collection visible to the statement as a table named `name`, by adding a common table expression to the + * parsed statement. The statement can then be bound, prepared or executed as usual; each execution reads the + * collection's contents at that moment, so a prepared statement can be executed again after the collection was cleared + * and refilled. Supported statement types are SELECT, INSERT, UPDATE, DELETE and MERGE INTO; any other type is rejected + * with `ERROR_INPUT_INVALID`. * - * A prepared statement extends that lifetime well beyond its own results. Preparing a statement over a claimed name - * captures the borrow in the plan, and since a collection claim reads no database there is nothing to invalidate that - * plan: `duckdb_v2_prepared_statement_reuses_plan()` reports true, and every later execution reuses the captured borrow - * without consulting the callback again. So dropping the name from whatever the callback resolves against does not - * release the collection, and releasing it while such a statement is live leaves the next execution reading freed - * memory. Destroy every prepared statement over a claimed name before clearing, resetting or destroying the collection - * behind it. + * A name the statement already defines as a common table expression, in its SQL text or by a prior call, is rejected + * with `ERROR_INPUT_INVALID`. The binding shadows any catalog table named `name`, as a common table expression does. * - * By default the collection's columns are named col1..colN. Pass `column_names` to name them instead. When supplied, - * `column_count` must equal the collection's column count and no name may be empty; pass NULL and 0 for the default - * names. + * By default the collection's columns are named col1..colN. Pass `column_names` to name them instead; when supplied, + * `column_count` must equal the collection's column count. Pass NULL and 0 for the default names. * - * The three claim forms, `duckdb_v2_replacement_scan_set_function_name()`, - * `duckdb_v2_replacement_scan_set_collection()` and `duckdb_v2_replacement_scan_set_subquery()`, are mutually - * exclusive: claiming the reference through a second, different form results in an error. + * The collection is borrowed: the caller keeps ownership and must keep it alive, and must not clear, reset or destroy + * it, for as long as the statement, any statement copied or prepared from it, or any result executing it is live. An + * empty collection is a valid binding. Several collections can be bound under distinct names. * * history: * - unstable: v2.0.0 * - * @param info The info handle. - * @param collection The collection to read instead. Borrowed; the caller keeps ownership and must keep it alive. - * @param column_names Optional. An array of `column_count` column names, in order. Pass NULL for the default names + * @param statement The statement to bind the collection to. Modified in place. + * @param name The non-empty name the statement refers to the collection by. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param collection The collection to bind. Borrowed; the caller keeps ownership and must keep it alive. + * @param column_names Optional. An array of `column_count` names for the collection's columns, in order. Pass NULL for * col1..colN. * @param column_names_lengths Byte lengths of the entries in `column_names`; element i is the length of * `column_names[i]`. May be NULL only when `column_names` is NULL. - * @param column_count The number of names in `column_names`. Must equal the collection's column count, or 0 for the - * default names. + * @param column_count The number of names in `column_names`. 0 for the default names; otherwise the collection's column + * count. * @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_replacement_scan_set_collection( - duckdb_v2_replacement_scan_info_handle info, duckdb_v2_column_data_collection_handle collection, - const char *const *column_names, const idx_t *column_names_lengths, idx_t column_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_add_collection(duckdb_v2_sql_statement_handle statement, + const char *name, idx_t name_length, + duckdb_v2_column_data_collection_handle collection, + const char *const *column_names, + const idx_t *column_names_lengths, idx_t column_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Claims the reference by naming a query to read instead. - * - * The text is parsed at the call and must contain exactly one SELECT statement: a syntax error, several statements or a - * statement of another kind results in an error. The text is borrowed for the call only. Prefer - * `duckdb_v2_replacement_scan_set_function_name()` when a single table function call suffices, as it avoids the parse - * and keeps the plan flatter. + * Returns the statement's type as classified by the parser. * - * The three claim forms, `duckdb_v2_replacement_scan_set_function_name()`, - * `duckdb_v2_replacement_scan_set_collection()` and `duckdb_v2_replacement_scan_set_subquery()`, are mutually - * exclusive: claiming the reference through a second, different form results in an error. + * This gives the type before the statement-level rewrites that `duckdb_v2_statement_execute()` applies, if any. So a + * PRAGMA reports PRAGMA even where execution rewrites it into a SELECT or a CALL. + * `duckdb_v2_result_get_statement_type()` on the executed result reports the rewritten type of a statement that + * rewrites into one. A statement the parser expands into a group reports MULTI, here and on its result. Its parts are + * not visible here, and statement_bind reports ERROR_INPUT_METADATA_DEFERRED for it. * * history: * - unstable: v2.0.0 * - * @param info The info handle. - * @param sql The SELECT statement to read instead. Borrowed for the call only. - * @param sql_length The length of `sql` in bytes. `sql` need not be null-terminated and may be NULL only when this is - * 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param statement The statement. + * @param out_type Receives the statement type. + * @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_replacement_scan_set_subquery(duckdb_v2_replacement_scan_info_handle info, - const char *sql, idx_t sql_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_type(duckdb_v2_sql_statement_handle statement, + DUCKDB_V2_STATEMENT_TYPE *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the alias the claimed replacement is bound under. + * Borrows the statement's own SQL text. * - * Optional, and independent of the claim form. An alias written in the query takes precedence over this one; without - * either, the table name of the reference is used, which for a file-backed reference is the path. The alias is borrowed - * and copied. + * The slice of the parsed string that belongs to this statement. A trailing terminator and the whitespace after it are + * included, whitespace and comments before the first token are not. The statement holds its own copy, so the view + * outlives the SQL string passed to parse_sql and the iterator, and stays valid until the statement is destroyed. A + * statement produced by a parser extension that overrides parsing carries whatever text the extension recorded. * * history: * - unstable: v2.0.0 * - * @param info The info handle. - * @param alias The alias to bind the replacement under. Borrowed and copied. - * @param alias_length The length of `alias` in bytes. `alias` must be valid UTF-8, need not be null-terminated, and may - * be NULL only when this is 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param statement The statement. + * @param out_text Receives a borrowed pointer to the statement text, valid until the statement is destroyed. + * @param out_text_length Receives the length of `*out_text` in bytes. `*out_text` is not guaranteed to be + * null-terminated. + * @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_replacement_scan_set_alias(duckdb_v2_replacement_scan_info_handle info, - const char *alias, idx_t alias_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_text(duckdb_v2_sql_statement_handle statement, + const char **out_text, idx_t *out_text_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the replacement scan, making it consulted for names the catalog cannot resolve. + * Returns the number of distinct parameters the statement declares. * - * The scan is visible only to queries on this connection and is released when the connection is destroyed. It is - * consulted before every instance-wide scan, so it can claim a name that a built-in scan would otherwise take. - * Registration requires a callback. Scans are consulted in registration order within their scope, connection-scoped - * ones before instance-wide ones, and the first to claim a name wins. A scan cannot be registered twice, and a - * registered scan cannot be unregistered: it lives until its scope ends. The scan must have been created through a - * factory of the same database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_replacement_scan_destroy()`, which does not affect the registered scan. + * This counts the parameters the parser found ($1, ?, $name, ...), so it needs no catalog and no binding; only the + * parameter types wait for `duckdb_v2_statement_bind()`. Repeated uses of one parameter count once. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param scan The replacement scan to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param statement The statement. + * @param out_count Receives the number of distinct parameters. + * @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_connection_register_replacement_scan(duckdb_v2_connection_handle conn, - duckdb_v2_replacement_scan_handle scan, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_count(duckdb_v2_sql_statement_handle statement, + idx_t *out_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the replacement scan, making it consulted for names the catalog cannot resolve. + * Borrows the name of one parameter, in binding order. * - * The scan is visible to every connection to the instance and lives until the instance is destroyed. Registering it - * while queries are binding on other connections is not thread-safe: register before issuing queries. Registration - * requires a callback. Scans are consulted in registration order within their scope, connection-scoped ones before - * instance-wide ones, and the first to claim a name wins. A scan cannot be registered twice, and a registered scan - * cannot be unregistered: it lives until its scope ends. The scan must have been created through a factory of the same - * database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_replacement_scan_destroy()`, which does not affect the registered scan. + * Parse-time metadata. Positions follow the parameters' binding indices, the order of `duckdb_v2_statement_bind()`'s + * parameter schema, so position i here names field i there. The name is the binding key that + * `duckdb_v2_statement_execute()` accepts: "1", "2", ... for a positional parameter ($1 or ?), the identifier for a + * named one ($name). Positional indices may be gapped ($1 and $3 without $2), in which case the names are "1" and "3" + * at positions 0 and 1. The view is valid until the statement is destroyed. An index outside [0, count) is rejected + * with ERROR_INPUT_OUT_OF_RANGE. * * history: * - unstable: v2.0.0 * - * @param instance The instance to register on. - * @param scan The replacement scan to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param statement The statement. + * @param index Zero-based position in binding order. + * @param out_name Receives a borrowed pointer to the parameter name, valid until the statement is destroyed. + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. + * @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_instance_register_replacement_scan(duckdb_v2_instance_handle instance, - duckdb_v2_replacement_scan_handle scan, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_name(duckdb_v2_sql_statement_handle statement, + idx_t index, const char **out_name, + idx_t *out_name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the replacement scan, making it consulted for names the catalog cannot resolve. + * Destroys a statement handle. * - * The scan is visible to every connection to the loading extension's instance and lives until the instance is - * destroyed. Use this from the extension's load callback. Registration requires a callback. Scans are consulted in - * registration order within their scope, connection-scoped ones before instance-wide ones, and the first to claim a - * name wins. A scan cannot be registered twice, and a registered scan cannot be unregistered: it lives until its scope - * ends. The scan must have been created through a factory of the same database. The caller still owns the handle after - * registration and must destroy it with `duckdb_v2_replacement_scan_destroy()`, which does not affect the registered - * scan. + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. statement_execute does not consume a + * statement, so every statement is destroyed here once it is no longer needed. On success the slot is set to nullptr. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param scan The replacement scan to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param statement The statement to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_replacement_scan(duckdb_v2_extension_handle extension, - duckdb_v2_replacement_scan_handle scan, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_destroy(duckdb_v2_sql_statement_handle *statement); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the replacement scan, releasing its resources. + * Destroys a statement iterator handle. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered scan. + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. Statements already yielded are independently + * owned and stay valid. On success the slot is set to nullptr. * * history: * - unstable: v2.0.0 * - * @param scan The scan to destroy. + * @param iterator The iterator to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_destroy(duckdb_v2_replacement_scan_handle *scan); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_iterator_destroy(duckdb_v2_statement_iterator_handle *iterator); #endif -/* --- Struct definitions for replacement scan --- */ +/* --- Struct definitions for sql_statement --- */ /* ============================================================================ - * MODULE: scalar + * MODULE: vector * ============================================================================ */ -/* --- Enums for scalar --- */ - -/* --- Struct forward declarations for scalar --- */ - -/* --- Types for scalar --- */ +/* --- Enums for vector --- */ /*! - * An owned opaque handle to a custom scalar function being built. Created with `duckdb_v2_scalar_function_create()`, - * configured with the setter functions (e.g. `duckdb_v2_scalar_function_set_name()`, - * `duckdb_v2_scalar_function_set_exec_callback()`, etc.) and the signature obtained via - * `duckdb_v2_scalar_function_get_signature()`, made available with `duckdb_v2_connection_register_scalar_function()` or - * `duckdb_v2_extension_register_scalar_function()`, and destroyed with `duckdb_v2_scalar_function_destroy()`. + * Internal representation of a vector, with FSST / SEQUENCE / SHREDDED collapsed into OTHER: the view getter rejects + * those and requires an explicit vector_flatten first. OTHER is the 0-value, so a zero-initialized out-param reads as + * "unspecified, needs flatten" rather than silently looking like FLAT. */ -typedef struct _duckdb_v2_scalar_function { - void *internal_ptr; -} * duckdb_v2_scalar_function_handle; +typedef enum DUCKDB_V2_VECTOR_TYPE { + //! Default for zero-init. Covers FSST / SEQUENCE / SHREDDED — call vector_flatten first. + DUCKDB_V2_VECTOR_TYPE_OTHER = 0, -/*! - * A borrowed opaque handle to the result of a scalar function's "resolve types" phase. The "resolve types" callback - * receives this handle next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments and the - * user data, and can use it to set the return type of the call site being bound. - */ -typedef struct _duckdb_v2_scalar_function_resolve_types_info { - void *internal_ptr; -} * duckdb_v2_scalar_function_resolve_types_info_handle; + //! Standard per-row storage. + DUCKDB_V2_VECTOR_TYPE_FLAT = 1, -/*! - * A borrowed opaque handle to the result of a scalar function's "bind" phase. The "bind" callback receives this handle - * next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments and the user data, and can use - * it to set the bind data of the call site being bound. - */ -typedef struct _duckdb_v2_scalar_function_bind_info { - void *internal_ptr; -} * duckdb_v2_scalar_function_bind_info_handle; + //! A single value applies to every row in the vector. + DUCKDB_V2_VECTOR_TYPE_CONSTANT = 2, -/*! - * A borrowed opaque handle to the arguments supplied to a scalar function during the local state initialization "init" - * phase. The "init" callback receives this handle and can use it to e.g. set up local state reusable across invocations - * of the "exec" execution callback. - */ -typedef struct _duckdb_v2_scalar_function_init_info { - void *internal_ptr; -} * duckdb_v2_scalar_function_init_info_handle; + //! Data + selection vector indirection into another vector. + DUCKDB_V2_VECTOR_TYPE_DICTIONARY = 3, + DUCKDB_V2_VECTOR_TYPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_VECTOR_TYPE; -/*! - * A borrowed opaque handle to the arguments supplied to a scalar function during the execution "exec" phase. The "exec" - * callback receives this handle and can use it to e.g. access the input argument vectors, retrieve the number of rows - * to process, and write results to the output vector. - */ -typedef struct _duckdb_v2_scalar_function_exec_info { - void *internal_ptr; -} * duckdb_v2_scalar_function_exec_info_handle; +/* --- Struct forward declarations for vector --- */ -/*! - * A borrowed opaque handle to the arguments supplied to a scalar function during the "stats" phase of query - * optimization. The "stats" callback receives this handle and can use it to read the statistics of the arguments of the - * call site and narrow the statistics of its result. - */ -typedef struct _duckdb_v2_scalar_function_stats_info { - void *internal_ptr; -} * duckdb_v2_scalar_function_stats_info_handle; +typedef struct duckdb_v2_vector_view duckdb_v2_vector_view; -/* --- Constants for scalar --- */ +typedef struct duckdb_v2_list_entry duckdb_v2_list_entry; -/* --- Function pointer typedefs for scalar --- */ +typedef struct duckdb_v2_hugeint_t duckdb_v2_hugeint_t; -typedef void (*duckdb_v2_scalar_function_resolve_types_callback_fn)( - 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); +typedef struct duckdb_v2_uhugeint_t duckdb_v2_uhugeint_t; -typedef void (*duckdb_v2_scalar_function_bind_callback_fn)(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); +typedef struct duckdb_v2_interval_t duckdb_v2_interval_t; -typedef void (*duckdb_v2_scalar_function_init_callback_fn)(duckdb_v2_scalar_function_init_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); +/* --- Types for vector --- */ -typedef void (*duckdb_v2_scalar_function_exec_callback_fn)(duckdb_v2_scalar_function_exec_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); +/* --- Constants for vector --- */ -typedef void (*duckdb_v2_scalar_function_stats_callback_fn)(duckdb_v2_scalar_function_stats_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); +/* --- Function pointer typedefs for vector --- */ -/* --- Functions for scalar --- */ +/* --- Functions for vector --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new scalar function through a factory. - * - * The function starts out empty: configure it with the setter functions (e.g. `duckdb_v2_scalar_function_set_name()`, - * `duckdb_v2_scalar_function_set_exec_callback()`, etc.) and the signature obtained via - * `duckdb_v2_scalar_function_get_signature()`, then make it available with - * `duckdb_v2_connection_register_scalar_function()` or `duckdb_v2_extension_register_scalar_function()`. The caller - * owns the returned handle and must destroy it with `duckdb_v2_scalar_function_destroy()`, also after registration. + * Returns the internal representation kind: flat, constant, or dictionary. * - * The scalar function can only be registered on the database the factory belongs to. + * Reports VECTOR_TYPE_OTHER for FSST / SEQUENCE / SHREDDED vectors, which must be passed through vector_flatten before + * vector_get_view will read them. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the scalar function through. - * @param function On success, receives the newly created scalar function. Owned by the caller. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_type Receives the representation kind. + * @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_scalar_function_create(duckdb_v2_factory_handle factory, - duckdb_v2_scalar_function_handle *function, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_vector_type(duckdb_v2_vector_handle vector, + DUCKDB_V2_VECTOR_TYPE *out_type, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the scalar function. + * Returns the vector's logical type. * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * The returned logical type is the same type that was passed to vector_reference, or the type that was set on creation. + * It is caller-owned; destroy it via logical_type_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_type Receives the caller-owned logical type handle. Destroy via logical_type_destroy. + * @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_scalar_function_set_name(duckdb_v2_scalar_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_logical_type(duckdb_v2_vector_handle vector, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the schema of the system catalog that the scalar function is registered in. + * Reads a vector as a unified view of data, validity, selection, and count. * - * The schema is borrowed and copied. Calling this again replaces the previous schema. Without a schema the function is - * registered in the default schema. The schema must exist when the function is registered, e.g. `collations`, whose - * functions are the string collations of the database. + * Populates out_view with borrowed pointers, valid until the owning chunk is destroyed. view.data addresses the + * vector's elements, to be cast to the layout its logical type implies: a typed leaf array for the primitives, + * hugeint_t / uhugeint_t / interval_t for those kinds, bytes for VARCHAR / BLOB / BIT / BIGNUM, list_entry for LIST and + * MAP, and nothing at all for ARRAY / STRUCT / UNION, whose data lives in their children. + * + * DECIMAL and ENUM are typed leaf arrays too, over a storage tier that follows from the type; both mappings are + * contract. A DECIMAL of width <= 4 stores int16, <= 9 int32, <= 18 int64, and <= 38 int128, boundaries inclusive, with + * the width and scale available from logical_type_get_param. An ENUM stores its dictionary indices as uint8 for a + * dictionary of at most 255 entries, uint16 for at most 65535, and uint32 beyond that, boundaries inclusive and an + * empty dictionary uint8; logical_type_get_param resolves an index to its entry. + * + * Rejects VECTOR_TYPE_OTHER; call vector_flatten first. + * + * Reading a DICTIONARY vector has one side effect: the dictionary's underlying child is flattened in place if it is not + * already FLAT. The parent vector stays DICTIONARY, and only the child's storage shape changes, but any pointer + * previously borrowed into that child — from an earlier vector_get_view on a vector aliasing the same buffer, say — is + * invalidated. This is the only mutation vector_get_view performs; compare vector_flatten, which materializes the whole + * vector to FLAT. * * history: * - unstable: v2.0.0 * - * @param function The function to set the schema of. - * @param schema The name of the schema. Borrowed and copied. - * @param schema_length The length of `schema` in bytes. `schema` must be valid UTF-8, need not be null-terminated, and - * may be NULL only when this is 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to read. + * @param out_view Receives the view. Its pointers are borrowed and valid until the owning chunk is destroyed. + * @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_scalar_function_set_schema(duckdb_v2_scalar_function_handle function, - const char *schema, idx_t schema_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_view(duckdb_v2_vector_handle vector, duckdb_v2_vector_view *out_view, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the documentation of the function so it can be filled in. + * Returns the number of elements in the vector. * - * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with - * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified - * in place, describes this overload only, and is registered with the function. Optional. + * The size is the number of logical elements the vector represents, which for a nested kind can differ from the size of + * its children. An ARRAY vector of size 10 whose array size is 3, for instance, has 10 logical elements while its + * single child vector has 30. * * history: * - unstable: v2.0.0 * - * @param function The function to get the documentation of. - * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_size Receives the number of elements. + * @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_scalar_function_get_docs(duckdb_v2_scalar_function_handle function, - duckdb_v2_function_docs_handle *docs, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_size(duckdb_v2_vector_handle vector, idx_t *out_size, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the function's signature so it can be configured. + * Sets the number of elements in the vector. * - * Add parameters with `duckdb_v2_function_signature_add_parameter()` and set the return type with - * `duckdb_v2_function_signature_set_return_type()`. The signature is modified in place; the function must be given a - * signature with a return type before registration. + * The counterpart of vector_get_size: it declares how many logical elements the vector now holds. It reserves enough + * space for size logical elements. + * + * history: + * - unstable: v2.0.0 + * + * @param vector The vector. + * @param size The new number of logical elements. + * @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_vector_set_size(duckdb_v2_vector_handle vector, idx_t size, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Reads one cell of a vector as an owned value. + * + * The total fallback reader. It reads any logical row of any vector representation without flattening — FLAT, CONSTANT, + * DICTIONARY, and the compressed kinds the view getter rejects — and covers every type kind, including those with no + * committed view layout (today VARIANT and GEOMETRY), where it is the only way to reach a cell. + * + * Each call allocates one owned value, which makes this a single-cell bridge rather than a per-row loop primitive; use + * vector_get_view on hot paths. The row index is logical and bounds-checked against vector_get_size. The returned value + * is caller-owned; destroy it via value_destroy. + * + * history: + * - unstable: v2.0.0 + * + * @param vector The vector to read from. + * @param row The logical row index, in [0, vector_get_size). + * @param out_value Receives the owned cell 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_vector_get_value(duckdb_v2_vector_handle vector, idx_t row, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Writes one cell of a FLAT vector from a value. + * + * The total fallback writer. It covers every type kind, including those with no committed view layout (today VARIANT + * and GEOMETRY), where it is the only way to write a cell. The value is borrowed and copied in, then cast to the + * vector's type through the non-strict default cast; a cast failure surfaces from the call. A NULL value clears the + * row's validity. + * + * Requires a FLAT vector: constant, dictionary, and compressed representations are not row-addressable, so call + * vector_flatten first. Each call performs one value write, which makes this a single-cell bridge rather than a per-row + * loop primitive; use the typed mutable-data paths on hot paths. The row index is logical and bounds-checked against + * vector_get_size. * * history: * - unstable: v2.0.0 * - * @param function The function to get the signature of. - * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to write to. + * @param row The logical row index, in [0, vector_get_size). + * @param value The borrowed value to write. Copied in; cast to the vector's type. + * @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_scalar_function_get_signature(duckdb_v2_scalar_function_handle function, - duckdb_v2_function_signature_handle *sig, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_set_value(duckdb_v2_vector_handle vector, idx_t row, + duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the scalar function. + * Returns a mutable pointer to the data of a FLAT or CONSTANT vector. * - * Associates an opaque pointer with the function, retrievable from the callbacks via - * `duckdb_v2_function_bind_get_user_data()`, `duckdb_v2_scalar_function_init_get_user_data()` and - * `duckdb_v2_scalar_function_exec_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, - * invoked when the data is no longer needed. + * Any other representation returns ERROR_INPUT_INVALID. The pointer is valid until the owning chunk is destroyed, and + * the vector's storage shape must not change — through a flatten, say — while it is in use. + * + * When writing VARCHAR values, the caller must ensure that the bytes contain valid UTF-8. * * history: * - unstable: v2.0.0 * - * @param function The function to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_data Receives a mutable pointer to the data. + * @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_scalar_function_set_user_data(duckdb_v2_scalar_function_handle function, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_data_mutable(duckdb_v2_vector_handle vector, void **out_data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets a property on the scalar function. + * Forces a vector into FLAT representation, in place. * - * Configures a function property that influences planning and execution, such as stability, NULL handling, fallibility - * or collation handling. The value must be one of the `DUCKDB_V2_FUNCTION_PROPERTY_VALUE` entries belonging to `key`; - * passing a value that does not belong to the key, or a key that is not valid for scalar functions, results in an - * error. + * A no-op for a vector that is already FLAT. For a CONSTANT, DICTIONARY, FSST, SEQUENCE, or SHREDDED vector it + * materializes the per-row data and switches the representation to FLAT. Call it before vector_get_view if you would + * rather not handle CONSTANT and DICTIONARY semantics in the view; it is required for any vector reporting + * VECTOR_TYPE_OTHER. * * history: * - unstable: v2.0.0 * - * @param function The function to set the property of. - * @param key The property to set. - * @param value The value to set for the property. Must belong to `key`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to flatten. + * @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_scalar_function_set_property(duckdb_v2_scalar_function_handle function, - DUCKDB_V2_FUNCTION_PROPERTY_KEY key, - DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_flatten(duckdb_v2_vector_handle vector, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets a generic, named property on the scalar function. + * Casts every row of a vector into another vector, using a factory. * - * Generic properties are free-form `name = value` pairs that the engine or extensions can read from a function, e.g. - * `duckdb.collation.combinable = true` marks a collation function as combinable. Setting a property that is already set - * replaces its value. Reading a property that is not set yields NULL, which boolean properties treat as false. + * The conversion is the one SQL `CAST` / `TRY_CAST` performs, registered custom casts included, from the type of + * `source` to the type of `target`. It covers as many rows as `source` holds (`duckdb_v2_vector_get_size()`), of any + * representation. `target` is replaced by the result, as `duckdb_v2_vector_reference()` would, taking its size: data + * and views taken from it beforehand do not survive the call, and nothing it held before carries over. In + * CAST_MODE_NORMAL a row that does not convert fails the call with the engine's conversion error, and the contents of + * `target` are unspecified. In CAST_MODE_TRY such rows are NULL in `target` instead and the call succeeds; compare the + * validity of `source` and `target` to find them. `cast_err` then receives the conversion error of one of them, e.g. to + * report why the cast did not convert every row. + * + * A connection's or callback's factory casts with that client's cast functions and settings (e.g. TimeZone). An + * instance's factory supports only the built-in casts, with default settings. `source` and `target` must be different + * vectors; `target` is typically a vector of a data chunk created by the caller, or the result vector of a callback. * * history: * - unstable: v2.0.0 * - * @param function The function to set the property of. - * @param name The name of the property, e.g. `duckdb.collation.combinable`. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param value The value of the property. Borrowed (copied in). - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory supplying the cast functions. + * @param source The vector to cast. Borrowed for the call only. + * @param target The vector to write the cast rows into. Its logical type is the target type. + * @param mode Whether a row that does not convert fails the call, or becomes NULL. + * @param out_converted Optional. Receives whether every row converted. Always true when a CAST_MODE_NORMAL cast + * succeeds. + * @param cast_err Optional. When a CAST_MODE_TRY cast succeeds without converting every row, receives an opaque info + * handle with the conversion error of one row that did not convert, which the caller must destroy via + * error_info_destroy. Otherwise receives NULL. + * @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_scalar_function_set_generic_property(duckdb_v2_scalar_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_cast(duckdb_v2_factory_handle factory, duckdb_v2_vector_handle source, + duckdb_v2_vector_handle target, DUCKDB_V2_CAST_MODE mode, + bool *out_converted, duckdb_v2_error_info_handle *cast_err, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reads a generic, named property of the scalar function, as set by `duckdb_v2_scalar_function_set_generic_property()`. + * Repoints a vector at another vector's data, without copying. * - * A property that is not set is not an error: `out_value` then receives NULL. + * `vector` takes on the storage of `source`: no data moves, and the two alias the same buffers until one of them is + * reset or re-referenced. Works for any type, including nested types. The source's logical type must equal the + * vector's; a mismatch returns ERROR_INPUT_INVALID. The source's data must outlive every read of `vector`. Use it to + * hand an already-materialized vector straight to an output vector without a per-row copy. * * history: * - unstable: v2.0.0 * - * @param function The function to read the property of. - * @param name The name of the property, e.g. `duckdb.collation.combinable`. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param out_value Receives the value of the property, owned by the caller, or NULL if the property is not set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to repoint at the source's data. + * @param source The vector whose data to reference. Its logical type must equal the vector's. + * @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_scalar_function_get_generic_property(duckdb_v2_scalar_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_reference(duckdb_v2_vector_handle vector, duckdb_v2_vector_handle source, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional resolve types callback of the scalar function. + * Turns the vector into a CONSTANT vector holding the given value. * - * The resolve types callback is invoked during query planning for each call site of the function, before the arguments - * are cast to the parameter types of the signature. Through its `duckdb_v2_function_bind_info_handle` it can inspect - * the argument types as they were passed and constant argument values. Through its - * `duckdb_v2_scalar_function_resolve_types_info_handle` it can set a concrete return type. It cannot set "bind data", - * use the bind callback for that. + * Afterwards the vector holds a single element that applies to every logical row; write it through + * vector_get_data_mutable, which returns a pointer to that one element. For a STRUCT vector the change propagates to + * every child. The value's logical type must equal the vector's; a mismatch returns ERROR_INPUT_INVALID. * * history: * - unstable: v2.0.0 * - * @param function The function to set the resolve types callback of. - * @param callback The resolve types callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to make constant. + * @param value The value every row takes. Its logical type must equal the vector's. + * @param count The number of elements in the vector. + * @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_scalar_function_set_resolve_types_callback( - duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_resolve_types_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_make_constant(duckdb_v2_vector_handle vector, + duckdb_v2_value_handle value, idx_t count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional bind callback of the scalar function. + * Sets a vector to a SEQUENCE representation. * - * The bind callback is invoked during query planning for each call site of the function, after the resolve types - * callback and after the arguments have been cast to the parameter types of the signature. Through its - * `duckdb_v2_function_bind_info_handle` it can inspect the argument types and constant argument values. Through its - * `duckdb_v2_scalar_function_bind_info_handle` it can set "bind data" that is shared with the init and exec callbacks. - * It cannot change the types of the call site, use the resolve types callback for that. + * Afterwards the vector represents the arithmetic sequence start, start+increment, start+2*increment, ... over count + * elements. No data pointer is involved; the three parameters describe the sequence completely. * * history: * - unstable: v2.0.0 * - * @param function The function to set the bind callback of. - * @param callback The bind callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to turn into a sequence. + * @param start The first value of the sequence. + * @param increment The step between consecutive values. + * @param count The number of elements in the sequence. + * @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_scalar_function_set_bind_callback( - duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_bind_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_make_sequence(duckdb_v2_vector_handle vector, int64_t start, + int64_t increment, idx_t count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional init callback of the scalar function. + * Sets one row of a FLAT vector to NULL, nested children included. * - * The init callback is invoked at the start of execution for each thread that will execute the function. It can set - * worker-local "init data", retrievable from the exec callback, to keep mutable state across invocations of the - * function. + * Clears the row's validity and broadcasts the NULL recursively to every descendant element under that row — STRUCT + * fields, and ARRAY elements strided by the array size — maintaining DuckDB's nested NULL invariant: when a STRUCT or + * ARRAY row is NULL, every descendant element under it must be NULL too. LIST children are left untouched, since their + * consumers gate on the list's own validity. Which kinds propagate is normative DuckDB behavior that evolves with the + * type system, which makes this the total NULL write path: equivalent to vector_set_value with a NULL value, without + * the per-call value allocation. + * + * Requires a FLAT vector: constant, dictionary, and compressed representations are not row-addressable, so call + * vector_flatten first. The row index is logical and bounds-checked against vector_get_size. * * history: * - unstable: v2.0.0 * - * @param function The function to set the init callback of. - * @param callback The init callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to write to. + * @param row The logical row index, in [0, vector_get_size). + * @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_scalar_function_set_init_callback( - duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_init_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_set_null(duckdb_v2_vector_handle vector, idx_t row, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the exec callback of the scalar function. + * Returns a mutable pointer to the validity mask of a FLAT vector. * - * The exec callback implements the function's logic: it is invoked during query execution with a batch of input rows - * and must fill the result vector. An exec callback must be set before registration. + * Allocates the mask on first use, so the returned pointer is always non-null. Each uint64_t word covers 64 rows: bit N + * of word W is row W*64+N. A set bit means valid; a cleared bit means NULL. + * + * A raw mask write marks only this vector's rows. Clearing a STRUCT or ARRAY parent bit leaves the descendant elements + * untouched, which violates DuckDB's nested NULL invariant — a NULL STRUCT or ARRAY row requires NULL descendants — so + * set nested rows NULL through vector_set_null instead. When writing nested masks raw anyway, invalidate the child + * masks up front and mark elements valid as the values are written. * * history: * - unstable: v2.0.0 * - * @param function The function to set the exec callback of. - * @param callback The exec callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_validity Receives a mutable pointer to the validity mask. + * @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_scalar_function_set_exec_callback( - duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_flat_get_validity_mutable(duckdb_v2_vector_handle vector, + uint64_t **out_validity, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional stats callback of the scalar function. + * Sets the validity of a CONSTANT vector. * - * The stats callback is invoked during query optimization for each call site of the function, after it has been bound. - * Through its `duckdb_v2_scalar_function_stats_info_handle` it reads the statistics of the arguments and narrows the - * statistics of the result, which the engine then uses to simplify the query. A function without a stats callback gives - * the engine no statistics for its result. + * A constant vector holds a single element, so one flag decides whether every row reads as the value or as NULL. * * history: * - unstable: v2.0.0 * - * @param function The function to set the stats callback of. - * @param callback The stats callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The constant vector. + * @param validity True to mark the vector's single element valid, false to mark it NULL. + * @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_scalar_function_set_stats_callback( - duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_stats_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_constant_set_valid(duckdb_v2_vector_handle vector, bool validity, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the concrete return type of the call site being bound. + * Borrows a string-backed vector's arena for writing. * - * Overrides the return type declared in the signature. Register the function with an ANY return type and set the - * concrete type here, derived from the argument types, to build a function whose result type depends on its input. The - * type is borrowed and copied. + * Allocates the arena on first use. Valid for VARCHAR, BLOB, BIT, and BIGNUM vectors, and returns ERROR_INPUT_INVALID + * for anything else. This call is the single string-ness check, which is why arena_allocate itself performs none. The + * arena is borrowed — never destroy it — and stays valid until the vector is flattened, reallocated, or destroyed. * * history: * - unstable: v2.0.0 * - * @param info The resolve types info handle. - * @param return_type The return type to set. Borrowed for the call only. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The string-backed vector whose arena to borrow. + * @param out_arena Receives the borrowed arena handle. + * @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_scalar_function_resolve_types_set_return_type( - duckdb_v2_scalar_function_resolve_types_info_handle info, duckdb_v2_logical_type_handle return_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_arena(duckdb_v2_vector_handle vector, + duckdb_v2_arena_handle *out_arena, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the function's "bind data" from the bind callback. + * Returns the number of child vectors a nested vector exposes. * - * The bind data is stored with the bound call site and retrievable from the init and exec callbacks. The opaque handle - * bundles the pointer with an optional destructor, invoked when the bind data is no longer needed, and an optional - * equality callback used when comparing two bound call sites; without one, pointer equality is used. Scalar functions - * set their bind data through this function, `duckdb_v2_function_bind_set_bind_data()` is not available to them. + * 1 for LIST, MAP and ARRAY; the field count for STRUCT; member_count + 1 for UNION, the tag plus the members; and 0 + * for any non-nested kind. vector_get_child documents what each index addresses. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param data Opaque handle bundling the bind data pointer plus optional destructor and equality callbacks. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_count Receives the number of child vectors. + * @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_scalar_function_bind_set_bind_data( - duckdb_v2_scalar_function_bind_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_child_count(duckdb_v2_vector_handle vector, idx_t *out_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. + * Borrows a child vector by index. + * + * What each index addresses, by kind: LIST and ARRAY expose [0] = the elements; MAP [0] = the entries, a STRUCT(key, + * value) whose children are the keys and the values; STRUCT and TUPLE [i] = field i; and UNION [0] = the tag with + * [1..N] = the members. Note that value_get_child diverges on UNION, exposing only the active member. + * + * The returned child is borrowed and lives as long as the owning chunk. Returns ERROR_INPUT_INVALID if the vector has + * no children, or if the index is out of range. * * history: * - unstable: v2.0.0 * - * @param info The init info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The nested vector to descend into. + * @param index The child index, in [0, vector_get_child_count). + * @param out_child Receives the borrowed child vector. + * @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_scalar_function_init_get_user_data( - duckdb_v2_scalar_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_child(duckdb_v2_vector_handle vector, idx_t index, + duckdb_v2_vector_handle *out_child, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Decodes BIGNUM storage bytes into a caller-supplied magnitude buffer + sign flag. + * + * in_data and in_length are the value's raw storage bytes, exactly as they sit in a vector's bignum payload or as + * value_get_blob reports them for a BIGNUM value. Those bytes are opaque: the storage encoding is not a committed part + * of this API, and this function is the only thing that interprets them. + * + * Writes the big-endian magnitude bytes into out_data and the sign flag into out_is_negative; reconstruct the integer + * as (-1)**out_is_negative * unsigned_big_endian(out_data[0..out_length]). Materializing the bytes is unavoidable, + * since a negative bignum stores its magnitude bit-inverted, but the buffer belongs to the caller: this function never + * allocates and hands back nothing to free. + * + * Pass out_data = NULL to size the buffer without decoding. out_length then receives the exact number of magnitude + * bytes and out_is_negative the sign, and out_capacity is ignored. The size comes straight out of the storage header, + * so the query is O(1) and exact — a size call followed by a decode call never needs a retry loop. + * + * With out_data != NULL, out_capacity must be at least out_length bytes, or the call returns ERROR_INPUT_OBJECT_SIZE + * with out_length set to the required size and out_data left untouched. On success exactly out_length bytes are + * written, and the rest of the buffer is not modified. + * + * Returns ERROR_INPUT_INVALID if in_data is NULL, or if in_length is too short to hold a bignum header. * * history: * - unstable: v2.0.0 * - * @param info The init info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param in_data The value's raw BIGNUM storage bytes. + * @param in_length Size of in_data in bytes. + * @param out_data Caller-owned buffer receiving the magnitude bytes, or NULL to only report the required size in + * out_length. + * @param out_capacity Bytes available in out_data. Ignored when out_data is NULL. + * @param out_length Receives the magnitude size in bytes, written on success and on ERROR_INPUT_OBJECT_SIZE. + * @param out_is_negative Receives true if the value is negative, false otherwise. + * @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_scalar_function_init_get_bind_data( - duckdb_v2_scalar_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_bignum_decode(const uint8_t *in_data, idx_t in_length, uint8_t *out_data, + idx_t out_capacity, idx_t *out_length, bool *out_is_negative, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the function's worker-local "init data" from the init callback. + * Encodes a magnitude + sign flag into BIGNUM storage bytes. * - * The init data is associated with the executing thread for the duration of the query and retrievable from the exec - * callback via `duckdb_v2_scalar_function_exec_get_init_data()`. The opaque handle bundles the pointer with an optional - * destructor, invoked when the init data is no longer needed. + * The inverse of bignum_decode. in_data and in_length are the big-endian magnitude bytes and is_negative the sign; + * out_data receives the raw storage bytes for that integer, in the form a BIGNUM vector payload expects. Those bytes + * are opaque: the storage encoding is not a committed part of this API. + * + * Pass out_data = NULL to size the buffer without encoding. out_length then receives the exact number of storage bytes, + * and out_capacity is ignored. The size is a fixed function of in_length, so the query is O(1) and exact. + * + * With out_data != NULL, out_capacity must be at least out_length bytes, or the call returns ERROR_INPUT_OBJECT_SIZE + * with out_length set to the required size and out_data left untouched. On success exactly out_length bytes are + * written, and the rest of the buffer is not modified. + * + * The magnitude must be canonical, matching what bignum_decode produces: in_length >= 1 with no leading zero bytes, so + * the value zero is the single byte 0x00 with is_negative = false. A NULL in_data, an in_length of 0, a leading zero + * byte, or a negative zero returns ERROR_INPUT_INVALID; a magnitude beyond the maximum bignum width returns + * ERROR_INPUT_OUT_OF_RANGE. * * history: * - unstable: v2.0.0 * - * @param info The init info handle. - * @param data Opaque handle bundling the init data pointer plus an optional destructor. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param in_data Big-endian magnitude bytes, with no leading zero bytes. + * @param in_length Size of in_data in bytes. Must be >= 1. + * @param is_negative True to encode a negative value. + * @param out_data Caller-owned buffer receiving the storage bytes, or NULL to only report the required size in + * out_length. + * @param out_capacity Bytes available in out_data. Ignored when out_data is NULL. + * @param out_length Receives the storage size in bytes — written on success and on ERROR_INPUT_OBJECT_SIZE. + * @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_scalar_function_init_set_init_data( - duckdb_v2_scalar_function_init_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_bignum_encode(const uint8_t *in_data, idx_t in_length, bool is_negative, + uint8_t *out_data, idx_t out_capacity, idx_t *out_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. + * Validates all `text_length` bytes of `text` as UTF-8, including bytes after embedded NUL characters. + * + * Returns ERROR_INPUT_INVALID if any of: + * - text is NULL and text_length is nonzero. + * - The input contains malformed UTF-8. + * + * A NULL text with a zero length is valid. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param text The bytes to validate. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. + * @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_scalar_function_exec_get_user_data( - duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_validate_utf8(const char *text, idx_t text_length, + duckdb_v2_error_info_handle *err); #endif +/* --- Struct definitions for vector --- */ + +struct duckdb_v2_vector_view { + const void *data; + const uint64_t *validity; + const duckdb_v2_sel_t *sel; + idx_t count; +}; + +struct duckdb_v2_list_entry { + idx_t offset; + idx_t length; +}; + +struct duckdb_v2_hugeint_t { + uint64_t lower; + int64_t upper; +}; + +struct duckdb_v2_uhugeint_t { + uint64_t lower; + uint64_t upper; +}; + +struct duckdb_v2_interval_t { + int32_t months; + int32_t days; + int64_t micros; +}; + +/* ============================================================================ + * MODULE: prepared_statement + * ============================================================================ */ + +/* --- Enums for prepared_statement --- */ + +/* --- Struct forward declarations for prepared_statement --- */ + +/* --- Types for prepared_statement --- */ + +/*! + * An owned handle to a statement bound and planned once, executable repeatedly via + * `duckdb_v2_prepared_statement_execute()`. Construct with `duckdb_v2_prepared_statement_create()` and destroy with + * `duckdb_v2_prepared_statement_destroy()`. It keeps its connection's session alive, so it stays usable across + * executions and even after the connection is disconnected. + */ +typedef struct _duckdb_v2_prepared_statement { + void *internal_ptr; +} * duckdb_v2_prepared_statement_handle; + +/* --- Constants for prepared_statement --- */ + +/* --- Function pointer typedefs for prepared_statement --- */ + +/* --- Functions for prepared_statement --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Prepares a parsed statement into a reusable handle. Non-consuming. + * + * Copies the statement's AST, then binds and plans it once. Binder and catalog errors surface here, exactly as they + * would from `duckdb_v2_statement_execute()`. The statement is borrowed rather than consumed, since a copy is what gets + * prepared, so it can be prepared again or executed directly; the caller destroys it with + * `duckdb_v2_sql_statement_destroy()`. + * + * By default this succeeds for any preparable statement, whether or not its plan will be reused; ask + * `duckdb_v2_prepared_statement_reuses_plan()` which one you got. Setting `require_cacheable` instead fails with + * `ERROR_INPUT_INVALID` when the plan would not be reused, so a caller who wants the handle only for the speedup finds + * out here rather than after silently taking the slow path. + * + * A statement that DuckDB expands into several, such as a dynamic PIVOT, is kept as written and expanded again at each + * execution, in the transaction state of that execution. It runs nothing here, its plan is never reused, and its + * result's metadata is deferred as for `duckdb_v2_statement_execute()`. Parameters on such a statement are refused with + * `ERROR_INPUT_INVALID`. + * + * Refuses with `ERROR_RESOURCE_IN_USE` while a statement on the connection is still running. Drain, destroy, or + * interrupt that result first, or prepare on another connection. `*out_prepared` is set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param conn The connection supplying the catalog, transaction, and parser state. The prepared statement belongs to + * it. + * @param statement The statement to prepare. Borrowed and copied, not consumed; destroy it with + * `duckdb_v2_sql_statement_destroy()`. + * @param require_cacheable When true, fail with `ERROR_INPUT_INVALID` unless the prepared plan will be reused across + * executions, as `duckdb_v2_prepared_statement_reuses_plan()` would report it. + * @param out_prepared On success, receives the new prepared statement. Owned by the caller; destroy via + * `duckdb_v2_prepared_statement_destroy()`. * @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_scalar_function_exec_get_bind_data( - duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_create(duckdb_v2_connection_handle conn, + duckdb_v2_sql_statement_handle statement, + bool require_cacheable, + duckdb_v2_prepared_statement_handle *out_prepared, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the worker-local init data set by the function's init callback. + * Executes a prepared statement, streaming its result. Non-consuming. + * + * Returns a result without executing anything: execution happens incrementally as the result is stepped or drained, + * exactly as with `duckdb_v2_statement_execute()`. The handle returned is an ordinary result, with identical behaviour + * throughout -- streaming, draining, the changed-row count of a DML statement, the output schema, the statement type, + * and the result type. + * + * `parameter_values` binds the statement's parameters as constants for this execution. Binding is positional by default + * ($1 = element 0); supply `parameter_names` to bind by name instead, where a non-empty entry binds its value to that + * named parameter ($name, matched case-insensitively) and an empty entry stays positional. Pass NULL for both arrays, + * or a count of 0, for a statement without parameters. Both arrays are borrowed and copied in, so the caller still owns + * and destroys them. A key set that does not match the statement's parameters is rejected with `ERROR_INPUT_INVALID`, + * with one exception: a named parameter left without a value reads the session variable of the same name (`SET + * VARIABLE`) when one exists. + * + * Not consumed: execute the same handle again, with the same values or different ones, as often as you like. Values are + * bound per execution and nothing carries over between them. A catalog change since the statement was prepared, or a + * parameter type that differs from the one the cached plan assumed, triggers a re-bind that is invisible apart from its + * cost. + * + * Refuses with `ERROR_RESOURCE_IN_USE` while a statement on the connection is still running; drain, destroy, or + * interrupt that result first, or execute on another connection. A failed execution, at any stage, leaves the prepared + * statement usable. `*out_result` is set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the init data pointer for the executing thread, or null if none was set. + * @param prepared The prepared statement to execute. Borrowed; not consumed. + * @param parameter_names Optional. An array of `parameter_count` parameter names; a non-empty entry binds its value to + * the named parameter ($name, case-insensitive), an empty entry (NULL or zero length) keeps it positional ($1 = element + * 0). Pass NULL to bind everything positionally. + * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of + * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. + * @param parameter_values Optional. An array of `parameter_count` values. Each binds by name when `parameter_names` + * supplies one, and positionally ($1 = element 0) otherwise. Borrowed and copied in. Pass NULL for a statement without + * parameters. + * @param parameter_count The number of entries in `parameter_names` and `parameter_values`. Pass 0 for a statement + * without parameters. + * @param out_result On success, receives the new result. Owned by the caller; destroy via `duckdb_v2_result_destroy()`. * @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_scalar_function_exec_get_init_data( - duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute( + duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns how many rows this execution must produce. The exec callback must write exactly this many rows to the result - * vector. Note that this may be less than a full vector: with all-constant arguments the function is invoked for a - * single row and the result is expanded by the engine. + * Reports whether the prepared statement reuses its compiled plan across executions. + * + * True when executions reuse the plan built at prepare time, provided the supplied values match the planned parameter + * types and nothing the plan depends on has changed; false when the statement re-binds on every execution, making it no + * faster than `duckdb_v2_statement_execute()`. A plan is reused only when all parameter types were resolved at prepare + * time and the plan is cacheable: `SELECT 42` reuses, `SELECT $1::INTEGER + 1` reuses, a statement reading a base table + * does not (it re-binds so a catalog change is picked up), and `SELECT $1 + $2` does not (the types are unknown until + * values arrive). + * + * A static property of the built plan, fixed when the statement was prepared and independent of the values later passed + * to `duckdb_v2_prepared_statement_execute()`. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param count Receives the number of rows. + * @param prepared The prepared statement to inspect. + * @param out_reuses Receives true when the compiled plan is reused across executions, false when the statement re-binds + * each time. * @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_scalar_function_exec_get_row_count( - duckdb_v2_scalar_function_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_reuses_plan(duckdb_v2_prepared_statement_handle prepared, + bool *out_reuses, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns how many argument vectors this invocation carries, split into the four parts of the argument list. + * Destroys a prepared statement. * - * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the - * vectors are at the same indices. Valid indices for `duckdb_v2_scalar_function_exec_get_arg()` are [0, the sum of the - * four counts). Every out-parameter may be NULL, in which case nothing is written to it. + * Null-safe: passing NULL, or a slot already set to NULL, is a no-op. A result produced by + * `duckdb_v2_prepared_statement_execute()` is independently owned and keeps the session alive itself, so the prepared + * statement may be destroyed while results made from it are still live. On success the slot is set to NULL. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. - * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has - * none. - * @param named_fixed Optional. Receives the number of named-only parameters. - * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param prepared The prepared statement to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_arg_count( - duckdb_v2_scalar_function_exec_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, - idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_destroy(duckdb_v2_prepared_statement_handle *prepared); #endif +/* --- Struct definitions for prepared_statement --- */ + +/* ============================================================================ + * MODULE: query_result + * ============================================================================ */ + +/* --- Enums for query_result --- */ + +/*! + * Shape of a query result. QUERY_RESULT carries rows and columns; CHANGED_ROWS carries an affected row count, as an + * INSERT, UPDATE, or DELETE without RETURNING produces; NOTHING covers DDL and other statements with no row output. + */ +typedef enum DUCKDB_V2_RESULT_TYPE { + DUCKDB_V2_RESULT_TYPE_QUERY_RESULT = 0, + DUCKDB_V2_RESULT_TYPE_CHANGED_ROWS = 1, + DUCKDB_V2_RESULT_TYPE_NOTHING = 2, + DUCKDB_V2_RESULT_TYPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_RESULT_TYPE; + +/*! + * Outcome of a result_step call. WAITING is the 0-value, so a zero-initialized out-param reads as "no work product yet" + * rather than CHUNK, the same convention VECTOR_TYPE_OTHER follows. The four states are the ones a consumer acts on; + * they are deliberately not a projection of any internal enum. + */ +typedef enum DUCKDB_V2_RESULT_STEP_STATUS { + //! No chunk yet; step again, or block in result_wait. + DUCKDB_V2_RESULT_STEP_STATUS_WAITING = 0, + + //! A caller-owned chunk was written to *out_chunk, or an array to *out_array. + DUCKDB_V2_RESULT_STEP_STATUS_CHUNK = 1, + + //! Stream exhausted. Sticky. + DUCKDB_V2_RESULT_STEP_STATUS_FINISHED = 2, + + //! Query was interrupted. Sticky. + DUCKDB_V2_RESULT_STEP_STATUS_CANCELLED = 3, + DUCKDB_V2_RESULT_STEP_STATUS_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_RESULT_STEP_STATUS; + +/* --- Struct forward declarations for query_result --- */ + +/* --- Types for query_result --- */ + +/* --- Constants for query_result --- */ + +/* --- Function pointer typedefs for query_result --- */ + +/* --- Functions for query_result --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the argument vector at the given index. + * Executes a parsed statement on the connection, streaming its result. Non-consuming. * - * The index is the one the bind callback used for the argument, e.g. the index - * `duckdb_v2_function_bind_get_arg_index()` found for a name. The vector holds the argument's values for the current - * batch; use `duckdb_v2_scalar_function_exec_get_row_count()` for the number of rows. Fails if the index is out of - * bounds. Borrowed; valid only for the duration of the callback. + * Takes a statement produced by the sql_statement module (parse_sql / statement_iterator_next), preprocesses and + * prepares it, and returns a result handle without executing anything: execution happens incrementally as the result is + * stepped (result_step) or drained (result_fetch_chunk). This call reports only the errors detectable at prepare time — + * binder, catalog, pragma preprocessing — while errors raised during execution surface from the stepping functions. + * + * The statement is borrowed, not consumed, since a copy is what executes. It can be executed again, for example with a + * different set of values, and the caller destroys it with sql_statement_destroy. + * + * parameter_values binds the statement's parameters as constants for this execution. Binding is positional by default: + * the i-th value binds $(i+1), matching SQL's own convention, so dense $1..$N and ? placeholders work directly. Supply + * parameter_names to bind by name instead — a non-empty name binds its value to that named parameter ($name, matched + * case-insensitively), while an empty entry leaves that value positional. The parameter schema from statement_bind + * lists the names to use. Both arrays are borrowed and copied in; the caller still owns and destroys them. Pass NULL + * for both, or a count of 0, for an unparameterized statement. A key set that does not match the statement's parameters + * — names for a positional statement, or the reverse — is rejected with ERROR_INPUT_INVALID, and named and positional + * parameters cannot be mixed within one statement. Parameters and statement expansion are mutually exclusive: passing + * values for a statement that preprocesses into a group is rejected with ERROR_INPUT_INVALID. + * + * DuckDB can expand one statement into a group: a dynamic PIVOT, or statement-expanding DDL such as ALTER ... ADD + * COLUMN with a non-constant DEFAULT. The group executes as one result through the same steps, and the stream surfaces + * the rows of the first row-producing statement of the group. A row-producing statement followed by another cannot be + * served as a single result and reports ERROR_QUERY_NOT_IMPLEMENTED; no known expansion produces one. + * + * One running statement per connection: this refuses with ERROR_RESOURCE_IN_USE while a statement on the connection is + * still running. Drain, destroy, or interrupt that result first, or open another connection. + * + * Schema metadata — result type, statement type, column count, names, logical types — is available on the returned + * handle immediately, before the first step. + * + * *out_result is set to nullptr on failure. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param index The index of the argument. - * @param vector Receives the borrowed argument vector. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param conn The connection on which to execute the statement. + * @param statement The statement to execute. Borrowed and copied; not consumed. Destroy it with sql_statement_destroy. + * @param parameter_names Optional. An array of parameter_count parameter names; a non-empty entry binds its value to + * the named parameter ($name, case-insensitive), an empty entry (NULL or zero length) keeps it positional ($1 = element + * 0). Pass NULL for all-positional binding. Named and positional parameters cannot be mixed within one statement. + * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of + * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. + * @param parameter_values Optional. An array of parameter_count value handles. Each binds by name when parameter_names + * supplies one, otherwise positionally ($1 = element 0). Borrowed (copied in). Pass NULL for an unparameterized + * statement. + * @param parameter_count The number of parameters in parameter_names and parameter_values. Pass 0 for an + * unparameterized statement. + * @param out_result Receives the new result handle. + * @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_scalar_function_exec_get_arg(duckdb_v2_scalar_function_exec_info_handle info, - idx_t index, duckdb_v2_vector_handle *vector, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute( + duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the result vector the exec callback must write into. + * Destroys a result handle. * - * The callback must write one entry per input row; use `duckdb_v2_scalar_function_exec_get_row_count()` for the number - * of rows. Borrowed; valid only for the duration of the callback. + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. Frees the memory the result owns and releases + * the connection for its next query. Safe at any point in the stream's life. Destroying a result before its statement + * ended (drained, or stepped to FINISHED) aborts the statement. On autocommit, its writes are rolled back. Inside a + * transaction, a statement that may write invalidates the transaction, and a read-only statement just stops. Chunks + * already fetched are caller-owned and stay valid. On success the slot is set to nullptr. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param vector Receives the borrowed result vector to write into. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param result The result to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_result(duckdb_v2_scalar_function_exec_info_handle info, - duckdb_v2_vector_handle *vector, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_destroy(duckdb_v2_result_handle *result); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. + * Runs one bounded unit of query execution and returns without blocking. + * + * The streaming primitive: a step does a bounded amount of execution work, mostly without blocking, and returns control + * to the caller, so an event loop stays responsive and can interleave other work between steps. The conveniences — + * result_wait, result_fetch_chunk, result_drain — block, and are for synchronous callers. out_status reports the + * outcome: + * + * - CHUNK: *out_chunk receives a caller-owned chunk (destroy via data_chunk_destroy). Written only for this status; + * nullptr otherwise. + * - WAITING: no chunk yet, but work was done. Transient: keep stepping and it resolves to CHUNK, FINISHED, CANCELLED, + * or an error. Block in result_wait rather than busy-stepping. + * - FINISHED: stream exhausted. Sticky. + * - CANCELLED: query interrupted via connection_interrupt. Sticky. Cancellation is a status here, not an error; + * result_fetch_chunk, which has no status out-param, reports it as ERROR_RUNTIME_INTERRUPT. + * + * Execution errors come back as the return code plus err, never as a status; out_status is then unspecified and + * *out_chunk is nullptr. Errors are sticky, so later steps report the same code. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param result The result to step. + * @param out_chunk Receives an owned chunk if *out_status is CHUNK; set to nullptr otherwise. + * @param out_status Receives the step status. + * @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_scalar_function_stats_get_user_data( - duckdb_v2_scalar_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_step(duckdb_v2_result_handle result, + duckdb_v2_data_chunk_handle *out_chunk, + DUCKDB_V2_RESULT_STEP_STATUS *out_status, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Blocks until the next chunk is available and returns it. + * + * A convenience over result_step: blocks until a chunk is produced or the stream ends. On success *out_chunk receives a + * caller-owned chunk (destroy via data_chunk_destroy), or nullptr at end-of-stream. End-of-stream is sticky, so later + * calls keep succeeding with *out_chunk set to nullptr. + * + * An interrupted query returns ERROR_RUNTIME_INTERRUPT — the same event result_step reports as status CANCELLED, + * carried on the error channel because this function has no status out-param. + * + * On failure *out_chunk is set to nullptr. Errors are sticky, so later calls report the same code. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param result The result to fetch from. + * @param out_chunk Receives an owned chunk, or nullptr at end-of-stream. + * @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_scalar_function_stats_get_bind_data( - duckdb_v2_scalar_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_fetch_chunk(duckdb_v2_result_handle result, + duckdb_v2_data_chunk_handle *out_chunk, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns how many arguments the call site has, split into the four parts of the argument list. + * Blocks until result_step can make progress. * - * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the - * arguments are at the same indices. Valid indices for `duckdb_v2_scalar_function_stats_get_arg_stats()` are [0, the - * sum of the four counts). Every out-parameter may be NULL, in which case nothing is written to it. + * A convenience over result_step: blocks until a step is worth issuing again, that is, until a unit of execution work + * can run on the calling thread. Never produces or consumes chunks. Waiting on a terminal result — FINISHED, CANCELLED, + * or a sticky error — returns immediately; it is a no-op, never an error. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. - * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has - * none. - * @param named_fixed Optional. Receives the number of named-only parameters. - * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param result The result to wait on. + * @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_scalar_function_stats_get_arg_count( - duckdb_v2_scalar_function_stats_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, - idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_wait(duckdb_v2_result_handle result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the statistics of the argument at the given index. + * Renders the result as a box table, consuming it. * - * The index is the one the bind callback used for the argument. The statistics are read-only. Fails if the index is out - * of bounds. Borrowed; valid only for the duration of the callback. + * Drains the result into a column data collection and renders it with the same renderer the DuckDB CLI uses, so every + * client displays results identically without reimplementing table formatting. The result is consumed by transfer: the + * slot is set to NULL on success and on failure alike. A partially consumed result is accepted, and the remainder is + * what gets rendered. + * + * The whole remaining result materializes in memory before rendering. max_rows bounds what is DISPLAYED, not what is + * read, so with limit 0 the footer's row count is exact. A caller who cannot afford full materialization should bound + * the query itself (e.g. LIMIT n) and pass n as limit; the footer then renders "? rows" whenever the result fills that + * bound, since the true total is unknown at that point. + * + * Zero selects the renderer default for each sizing knob: max_rows 20, max_width the probed terminal width or 80 when + * that is unavailable, max_col_width 20. An empty null_value renders NULL cells as the default "NULL" text. + * + * The rendered text goes to sink rather than being returned: a box can be large, and this way nothing allocates a + * buffer the caller has to free. The sink is called exactly once with the whole box, so its view carries the full + * length — write it straight to a stream, or copy it into your own string. sink must not be NULL. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param index The index of the argument. - * @param stats Receives the borrowed, read-only statistics of the argument. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param result The result to render; consumed and set to NULL. Left intact only when the call rejects null arguments. + * @param max_rows Maximum rows displayed; 0 selects the renderer default (20). + * @param max_width Maximum total width in characters; 0 selects the renderer default. + * @param max_col_width Maximum width of one column; 0 selects the renderer default (20). + * @param null_value Text rendered for NULL cells; empty selects "NULL". + * @param null_value_length The length of `null_value` in bytes. `null_value` need not be null-terminated and may be + * NULL only when this is 0. + * @param render_mode 0 renders rows (records down the page); 1 renders columns; other values are rejected with + * INVALID_INPUT. + * @param limit The row limit the caller applied to the query before rendering; 0 means none. When the materialized + * result holds exactly this many rows the true total is unknown, so the footer renders "? rows" instead of an exact + * count. + * @param sink Receives the whole rendered box in a single call. Borrowed for the duration of that call; see text_sink + * for the full contract. + * @param user_data Opaque pointer passed through to sink untouched. May be NULL. + * @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_scalar_function_stats_get_arg_stats(duckdb_v2_scalar_function_stats_info_handle info, idx_t index, - duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_render_box(duckdb_v2_result_handle *result, idx_t max_rows, + idx_t max_width, idx_t max_col_width, const char *null_value, + idx_t null_value_length, idx_t render_mode, idx_t limit, + duckdb_v2_text_sink_fn sink, void *user_data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the statistics of the call site's result, for the callback to narrow. + * Runs the result to completion and reports the changed-row count. * - * The statistics start out unknown, with every kind of value possible. Borrowed; valid only for the duration of the - * callback. + * A convenience over result_step: blocks until the stream is fully consumed, so every side effect is applied. Rows of a + * row-producing result are discarded. For a CHANGED_ROWS result *out_rows_changed receives the affected row count; for + * every other result type, and for a stream whose Count chunk was already consumed, it receives 0. + * + * The result type (result_get_result_type) is prepare-time metadata, so a caller can choose between consuming rows and + * draining without inspecting the SQL. Draining an already FINISHED result succeeds. Cancellation surfaces as + * ERROR_RUNTIME_INTERRUPT; errors are sticky, and on failure *out_rows_changed is unspecified. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param stats Receives the borrowed, writable statistics of the call site's result. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param result The result to drain. + * @param out_rows_changed Receives the affected row count for CHANGED_ROWS results, 0 otherwise. + * @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_scalar_function_stats_get_result_stats( - duckdb_v2_scalar_function_stats_info_handle info, duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_drain(duckdb_v2_result_handle result, idx_t *out_rows_changed, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the scalar function, making it available for use in SQL queries. + * Returns the shape of the result: query, changed rows, or nothing. * - * The function is registered on the connection's database, visible to every connection, in the connection's - * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. Registration requires a name, an exec callback, and a signature with a complete return type; an - * ANY return type is accepted only together with a resolve types callback that sets the concrete type per call site. - * The scalar function must have been created through a factory of the same database. The caller still owns the handle - * after registration and must destroy it with `duckdb_v2_scalar_function_destroy()`, which does not affect the - * registered function. + * QUERY_RESULT for statements that produce rows (SELECT, RETURNING, EXPLAIN), CHANGED_ROWS for an INSERT, UPDATE, or + * DELETE without RETURNING, NOTHING for DDL and other statements with no row output. + * + * Prepare-time metadata: available from statement_execute on, except for a statement that expands into a group, where + * it fails with ERROR_INPUT_METADATA_DEFERRED until stepping has bound the row-producing statement, or the group ended + * without one. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param function The scalar function to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param result The result. + * @param out_type Receives the result shape. + * @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_connection_register_scalar_function(duckdb_v2_connection_handle conn, - duckdb_v2_scalar_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_get_result_type(duckdb_v2_result_handle result, + DUCKDB_V2_RESULT_TYPE *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the scalar function, making it available for use in SQL queries. + * Returns the SQL statement type that produced the result. * - * The function is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. Registration requires a name, an exec callback, and a signature with a complete return - * type; an ANY return type is accepted only together with a resolve types callback that sets the concrete type per call - * site. The scalar function must have been created through a factory of the same database. The caller still owns the - * handle after registration and must destroy it with `duckdb_v2_scalar_function_destroy()`, which does not affect the - * registered function. + * Prepare-time metadata: available from statement_execute on. A statement that expands into a group reports its type as + * written: MULTI, or PRAGMA for a pragma such as IMPORT DATABASE. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The scalar function to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param result The result. + * @param out_type Receives the statement type. + * @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_extension_register_scalar_function(duckdb_v2_extension_handle extension, - duckdb_v2_scalar_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_get_statement_type(duckdb_v2_result_handle result, + DUCKDB_V2_STATEMENT_TYPE *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the scalar function, releasing its resources. + * Returns the result's output schema as a single schema handle. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered function. + * Builds an owned schema of the result's column names and types into *out_schema; destroy it via schema_destroy. + * Prepare-time metadata, available before the first step, or for an expanding statement once stepping has bound the + * row-producing statement (before that it fails with ERROR_INPUT_METADATA_DEFERRED). Never empty: a non-SELECT reports + * a single status column, either a BIGINT changed-rows count or a BOOLEAN success. + * + * This schema is the authoritative source for the column types of the chunks the result produces; vectors do not carry + * their own type. + * + * *out_schema is set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param function The function to destroy. + * @param result The result. + * @param out_schema Receives the owned output schema. Destroy via schema_destroy. + * @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_scalar_function_destroy(duckdb_v2_scalar_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_get_schema(duckdb_v2_result_handle result, + duckdb_v2_schema_handle *out_schema, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for scalar --- */ +/* --- Struct definitions for query_result --- */ /* ============================================================================ - * MODULE: sql_statement + * MODULE: table * ============================================================================ */ -/* --- Enums for sql_statement --- */ +/* --- Enums for table --- */ -//! SQL statement type of a parsed statement or an executed query. -typedef enum DUCKDB_V2_STATEMENT_TYPE { - DUCKDB_V2_STATEMENT_TYPE_INVALID = 0, - DUCKDB_V2_STATEMENT_TYPE_SELECT = 1, - DUCKDB_V2_STATEMENT_TYPE_INSERT = 2, - DUCKDB_V2_STATEMENT_TYPE_UPDATE = 3, - DUCKDB_V2_STATEMENT_TYPE_CREATE = 4, - DUCKDB_V2_STATEMENT_TYPE_DELETE = 5, - DUCKDB_V2_STATEMENT_TYPE_PREPARE = 6, - DUCKDB_V2_STATEMENT_TYPE_EXECUTE = 7, - DUCKDB_V2_STATEMENT_TYPE_ALTER = 8, - DUCKDB_V2_STATEMENT_TYPE_TRANSACTION = 9, - DUCKDB_V2_STATEMENT_TYPE_COPY = 10, - DUCKDB_V2_STATEMENT_TYPE_ANALYZE = 11, - DUCKDB_V2_STATEMENT_TYPE_VARIABLE_SET = 12, - DUCKDB_V2_STATEMENT_TYPE_CREATE_FUNC = 13, - DUCKDB_V2_STATEMENT_TYPE_EXPLAIN = 14, - DUCKDB_V2_STATEMENT_TYPE_DROP = 15, - DUCKDB_V2_STATEMENT_TYPE_EXPORT = 16, - DUCKDB_V2_STATEMENT_TYPE_PRAGMA = 17, - DUCKDB_V2_STATEMENT_TYPE_VACUUM = 18, - DUCKDB_V2_STATEMENT_TYPE_CALL = 19, - DUCKDB_V2_STATEMENT_TYPE_SET = 20, - DUCKDB_V2_STATEMENT_TYPE_LOAD = 21, - DUCKDB_V2_STATEMENT_TYPE_RELATION = 22, - DUCKDB_V2_STATEMENT_TYPE_EXTENSION = 23, - DUCKDB_V2_STATEMENT_TYPE_LOGICAL_PLAN = 24, - DUCKDB_V2_STATEMENT_TYPE_ATTACH = 25, - DUCKDB_V2_STATEMENT_TYPE_DETACH = 26, - DUCKDB_V2_STATEMENT_TYPE_MULTI = 27, - DUCKDB_V2_STATEMENT_TYPE_COPY_DATABASE = 28, - DUCKDB_V2_STATEMENT_TYPE_UPDATE_EXTENSIONS = 29, - DUCKDB_V2_STATEMENT_TYPE_MERGE_INTO = 30, - DUCKDB_V2_STATEMENT_TYPE_CONNECT = 31, - DUCKDB_V2_STATEMENT_TYPE_DISCONNECT = 32, - DUCKDB_V2_STATEMENT_TYPE_EXTERNAL_RESOURCE = 33, - DUCKDB_V2_STATEMENT_TYPE_PASSTHROUGH = 34, - DUCKDB_V2_STATEMENT_TYPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_STATEMENT_TYPE; +/*! + * Whether a table function's scan is partitioned by a given set of columns, and how. Reported by + * `duckdb_v2_table_function_set_partitioning_callback()` via + * `duckdb_v2_table_function_partitioning_set_partition_info()`. + */ +typedef enum DUCKDB_V2_TABLE_PARTITION_INFO { + //! The scan is not known to be partitioned by the requested columns. + DUCKDB_V2_TABLE_PARTITION_INFO_NOT_PARTITIONED = 0, -/* --- Struct forward declarations for sql_statement --- */ + //! Each partition the scan produces carries exactly one distinct value for the requested columns. + DUCKDB_V2_TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS = 1, + + //! The partitions the scan produces overlap only at their boundaries. + DUCKDB_V2_TABLE_PARTITION_INFO_OVERLAPPING_PARTITIONS = 2, + + //! The partitions the scan produces are disjoint ranges. + DUCKDB_V2_TABLE_PARTITION_INFO_DISJOINT_PARTITIONS = 3, + DUCKDB_V2_TABLE_PARTITION_INFO_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_TABLE_PARTITION_INFO; + +/*! + * A column a table function can produce next to the columns it declares in bind. A query asks for it by name, but it is + * not part of the function's result columns. Declared with `duckdb_v2_table_function_add_virtual_column()`. In the + * column lists of the scan (e.g. `duckdb_v2_data_source_exec_get_column_index()`), a virtual column is identified by + * 2^63 plus its value in this enum. + */ +typedef enum DUCKDB_V2_TABLE_VIRTUAL_COLUMN { + /*! + * `file_row_number`, a BIGINT holding the position of the row within the file it was read from, counting from 0. A + * function that reads a single file produces it when it is wrapped in a multi-file function (see + * `duckdb_v2_multi_file_function_create()`), which is where the name of the file comes from. + */ + DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER = 0, + DUCKDB_V2_TABLE_VIRTUAL_COLUMN_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_TABLE_VIRTUAL_COLUMN; + +/* --- Struct forward declarations for table --- */ + +/* --- Types for table --- */ + +/*! + * An owned opaque handle to a custom table function being built. Created with `duckdb_v2_table_function_create()`, + * configured with the setter functions (e.g. `duckdb_v2_table_function_set_name()`, + * `duckdb_v2_table_function_set_data_source()`, etc.) and the signature obtained via + * `duckdb_v2_table_function_get_signature()`, made available with `duckdb_v2_connection_register_table_function()` or + * `duckdb_v2_extension_register_table_function()`, and destroyed with `duckdb_v2_table_function_destroy()`. + */ +typedef struct _duckdb_v2_table_function { + void *internal_ptr; +} * duckdb_v2_table_function_handle; -/* --- Types for sql_statement --- */ +/*! + * A borrowed opaque handle to the result of a table function's "bind" phase. The "bind" callback receives this handle + * next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments, the user data and the bind + * data. It must use this handle to declare the columns the function returns, and can use it to hint at the number of + * rows the scan will produce. + */ +typedef struct _duckdb_v2_table_function_bind_info { + void *internal_ptr; +} * duckdb_v2_table_function_bind_info_handle; /*! - * An opaque, owned handle to a single parsed SQL statement, produced by statement_iterator_next. statement_execute runs - * it without consuming it; the caller always destroys it via sql_statement_destroy. + * A borrowed opaque handle to the arguments supplied to a table function during the "filter pushdown" phase of query + * optimization. The "filter pushdown" callback receives this handle and can use it to inspect the filter predicates the + * query applies to the function's rows, and to accept the ones it will apply itself. */ -typedef struct _duckdb_v2_sql_statement { +typedef struct _duckdb_v2_table_function_filter_pushdown_info { void *internal_ptr; -} * duckdb_v2_sql_statement_handle; +} * duckdb_v2_table_function_filter_pushdown_info_handle; /*! - * An opaque, owned handle to an iterator over the statements of a SQL string, produced by parse_sql. Destroy it via - * statement_iterator_destroy; statements it already yielded are independently owned and unaffected. + * A borrowed opaque handle to the arguments supplied to a table function during the "stats" phase of query + * optimization. The engine invokes the callback once per column the query reads, and the callback can use the handle to + * find out which column is asked about and to report what it knows about the column's values (its minimum and maximum, + * whether it holds NULLs, ...) by narrowing the statistics of that column. */ -typedef struct _duckdb_v2_statement_iterator { +typedef struct _duckdb_v2_table_function_stats_info { void *internal_ptr; -} * duckdb_v2_statement_iterator_handle; +} * duckdb_v2_table_function_stats_info_handle; -/* --- Constants for sql_statement --- */ +/*! + * A borrowed opaque handle to the arguments supplied to a table function during the "partitioning" phase of query + * optimization. The engine invokes the callback once per candidate `GROUP BY` column set, before execution starts, to + * decide whether the scan can feed a partitioned aggregate directly instead of hashing. + */ +typedef struct _duckdb_v2_table_function_partitioning_info { + void *internal_ptr; +} * duckdb_v2_table_function_partitioning_info_handle; -/* --- Function pointer typedefs for sql_statement --- */ +/*! + * A borrowed opaque handle to the arguments supplied to a table function when the engine asks it to describe a bound + * call. The "get bind info" callback receives this handle, and can use it to describe the call in more detail than its + * columns: with identifiers of its columns (e.g. field ids), and with options - key-value facts about what the call + * reads. + */ +typedef struct _duckdb_v2_table_function_get_bind_info_info { + void *internal_ptr; +} * duckdb_v2_table_function_get_bind_info_info_handle; -/* --- Functions for sql_statement --- */ +/*! + * A borrowed opaque handle to the arguments supplied to a table function when the engine describes a bound call of it + * in a query plan, e.g. for `EXPLAIN`. The "to string" callback receives this handle and can use it to report the + * key-value pairs the plan shows for the scan. + */ +typedef struct _duckdb_v2_table_function_to_string_info { + void *internal_ptr; +} * duckdb_v2_table_function_to_string_info_handle; -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Parses a SQL string into an iterator over its statements. - * - * Parses and nothing more: no binding and no catalog access. The connection supplies the parser options and parser - * extensions. With apply_invalidation_policy, a parse error invalidates the connection's active transaction according - * to the transaction invalidation policy, like an error from running the statement would; pass that when the statements - * are parsed to be run. Without it, a parse error leaves the transaction usable, for callers that only inspect the - * statements, for example with `duckdb_v2_statement_bind()`. Statements are raw parser output; statement-level rewrites - * happen inside statement_execute. The SQL string is copied, so the caller may free it once this call returns. An input - * with no statements — empty, whitespace, or separators only — yields an iterator that is immediately exhausted. - * - * history: - * - unstable: v2.0.0 - * - * @param conn The connection supplying the parser configuration. - * @param sql The SQL text, `sql_length` bytes long; may contain any number of statements. Need not be null-terminated. - * May be NULL only when `sql_length` is 0. - * @param sql_length The length of `sql` in bytes. - * @param apply_invalidation_policy Whether a parse error invalidates the active transaction, according to the - * transaction invalidation policy. - * @param out_iterator Receives the new iterator handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR + * An owned opaque handle to a multi-file table function being built. A multi-file function wraps an already registered + * table function that reads a single file, and adds everything that is needed to read many files at once on top of it: + * globbing, lists of files, hive partitioning, the `filename` column, `union_by_name` and the like. Created with + * `duckdb_v2_multi_file_function_create()`, configured with the setter functions (e.g. + * `duckdb_v2_multi_file_function_set_name()`, `duckdb_v2_multi_file_function_set_single_file_function()`), made + * available with `duckdb_v2_connection_register_multi_file_function()` or + * `duckdb_v2_extension_register_multi_file_function()`, and destroyed with `duckdb_v2_multi_file_function_destroy()`. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_parse_sql(duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, - bool apply_invalidation_policy, - duckdb_v2_statement_iterator_handle *out_iterator, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_multi_file_function { + void *internal_ptr; +} * duckdb_v2_multi_file_function_handle; + +/* --- Constants for table --- */ + +/* --- Function pointer typedefs for table --- */ + +typedef void (*duckdb_v2_table_function_bind_callback_fn)(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); + +typedef void (*duckdb_v2_table_function_filter_pushdown_callback_fn)( + duckdb_v2_table_function_filter_pushdown_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_table_function_partitioning_callback_fn)( + duckdb_v2_table_function_partitioning_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_table_function_get_bind_info_callback_fn)( + duckdb_v2_table_function_get_bind_info_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_table_function_stats_callback_fn)(duckdb_v2_table_function_stats_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_table_function_to_string_callback_fn)(duckdb_v2_table_function_to_string_info_handle info, + duckdb_v2_error_info_handle *err); + +/* --- Functions for table --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Yields the next statement, or NULL when exhausted. + * Creates a new table function through a factory. * - * On success *out_statement receives the next owned statement, or NULL once the iterator is exhausted — repeatedly, so - * calling again is harmless. A parse error within the input surfaces no later than the call that reaches the failing - * statement: an implementation that parses eagerly reports it from parse_sql instead and yields no statements at all, - * while an incremental one yields the statements ahead of the failure first. On failure *out_statement is set to NULL. + * The function starts out empty: configure it with the setter functions (e.g. `duckdb_v2_table_function_set_name()`, + * `duckdb_v2_table_function_set_data_source()`, etc.) and the signature obtained via + * `duckdb_v2_table_function_get_signature()`, then make it available with + * `duckdb_v2_connection_register_table_function()` or `duckdb_v2_extension_register_table_function()`. The caller owns + * the returned handle and must destroy it with `duckdb_v2_table_function_destroy()`, also after registration. + * + * The table function can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param iterator The iterator to advance. - * @param out_statement Receives an owned statement, or NULL when the iterator is exhausted. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param factory The factory to create the table function through. + * @param function On success, receives the newly created table function. Owned by the caller. + * @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_statement_iterator_next(duckdb_v2_statement_iterator_handle iterator, - duckdb_v2_sql_statement_handle *out_statement, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_table_function_handle *function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Binds a parsed statement without executing, yielding its schema signature. - * - * Preprocesses and binds the statement exactly as execution would, but runs nothing: the result is the statement's - * signature as two schemas, not a query result. The statement is borrowed, not consumed, so it can be bound as often as - * you like and executed later. out_schema receives the output schema (result columns) and is never empty, since a - * non-SELECT reports a single status column: a BIGINT changed-rows count, or a BOOLEAN success. out_parameters, when - * non-NULL, receives the input schema (parameter types, ordered by binding index). Both are owned; destroy them via - * schema_destroy. - * - * Binding is read-only and does not disturb a live result: it begins no query, claims no cursor, reuses an active - * transaction read-only, and runs alongside a paused stream. It is single-consumer like the stepping functions, so bind - * concurrently only on a second connection. Errors of the bind itself (catalog lookups, type resolution, preprocessing) - * surface here; errors of the planning after the bind (the plan depth limit, a correlated subquery or trigger body that - * decorrelation refuses) may surface only when the statement is executed. A statement that expands into a group (a - * dynamic PIVOT, or statement-expanding DDL such as ALTER ADD COLUMN with a non-constant DEFAULT) has a schema known - * only at execution, and is reported with ERROR_INPUT_METADATA_DEFERRED; execute it instead. + * Sets the name of the table function. * - * *out_schema and *out_parameters are set to NULL on failure. + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param conn The connection supplying the catalog, transaction, and parser configuration. - * @param statement The statement to bind. Borrowed; not consumed. - * @param out_schema Receives the owned output schema (result columns). Destroy via schema_destroy. - * @param out_parameters Optional. When non-NULL, receives the owned input schema (parameter types, ordered by binding - * index). Destroy via schema_destroy. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @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_statement_bind(duckdb_v2_connection_handle conn, - duckdb_v2_sql_statement_handle statement, - duckdb_v2_schema_handle *out_schema, - duckdb_v2_schema_handle *out_parameters, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_name(duckdb_v2_table_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Binds a column data collection to the statement under a name. - * - * Makes the collection visible to the statement as a table named `name`, by adding a common table expression to the - * parsed statement. The statement can then be bound, prepared or executed as usual; each execution reads the - * collection's contents at that moment, so a prepared statement can be executed again after the collection was cleared - * and refilled. Supported statement types are SELECT, INSERT, UPDATE, DELETE and MERGE INTO; any other type is rejected - * with `ERROR_INPUT_INVALID`. - * - * A name the statement already defines as a common table expression, in its SQL text or by a prior call, is rejected - * with `ERROR_INPUT_INVALID`. The binding shadows any catalog table named `name`, as a common table expression does. - * - * By default the collection's columns are named col1..colN. Pass `column_names` to name them instead; when supplied, - * `column_count` must equal the collection's column count. Pass NULL and 0 for the default names. + * Returns the documentation of the function so it can be filled in. * - * The collection is borrowed: the caller keeps ownership and must keep it alive, and must not clear, reset or destroy - * it, for as long as the statement, any statement copied or prepared from it, or any result executing it is live. An - * empty collection is a valid binding. Several collections can be bound under distinct names. + * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with + * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified + * in place, describes this overload only, and is registered with the function. Optional. * * history: * - unstable: v2.0.0 * - * @param statement The statement to bind the collection to. Modified in place. - * @param name The non-empty name the statement refers to the collection by. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param collection The collection to bind. Borrowed; the caller keeps ownership and must keep it alive. - * @param column_names Optional. An array of `column_count` names for the collection's columns, in order. Pass NULL for - * col1..colN. - * @param column_names_lengths Byte lengths of the entries in `column_names`; element i is the length of - * `column_names[i]`. May be NULL only when `column_names` is NULL. - * @param column_count The number of names in `column_names`. 0 for the default names; otherwise the collection's column - * count. + * @param function The function to get the documentation of. + * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. * @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_statement_add_collection(duckdb_v2_sql_statement_handle statement, - const char *name, idx_t name_length, - duckdb_v2_column_data_collection_handle collection, - const char *const *column_names, - const idx_t *column_names_lengths, idx_t column_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_docs(duckdb_v2_table_function_handle function, + duckdb_v2_function_docs_handle *docs, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the statement's type as classified by the parser. + * Returns the function's signature so it can be configured. * - * This gives the type before the statement-level rewrites that `duckdb_v2_statement_execute()` applies, if any. So a - * PRAGMA reports PRAGMA even where execution rewrites it into a SELECT or a CALL. - * `duckdb_v2_result_get_statement_type()` on the executed result reports the rewritten type of a statement that - * rewrites into one. A statement the parser expands into a group reports MULTI, here and on its result. Its parts are - * not visible here, and statement_bind reports ERROR_INPUT_METADATA_DEFERRED for it. + * Add parameters with `duckdb_v2_function_signature_add_parameter()`. The signature is modified in place. A table + * function declares the columns it returns from its bind callback instead of through a return type, so registration + * rejects a signature whose return type was set with `duckdb_v2_function_signature_set_return_type()`. * * history: * - unstable: v2.0.0 * - * @param statement The statement. - * @param out_type Receives the statement type. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to get the signature of. + * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. + * @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_sql_statement_get_type(duckdb_v2_sql_statement_handle statement, - DUCKDB_V2_STATEMENT_TYPE *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_signature(duckdb_v2_table_function_handle function, + duckdb_v2_function_signature_handle *sig, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the statement's own SQL text. + * Sets arbitrary user data on the table function. * - * The slice of the parsed string that belongs to this statement. A trailing terminator and the whitespace after it are - * included, whitespace and comments before the first token are not. The statement holds its own copy, so the view - * outlives the SQL string passed to parse_sql and the iterator, and stays valid until the statement is destroyed. A - * statement produced by a parser extension that overrides parsing carries whatever text the extension recorded. + * Associates an opaque pointer with the function, retrievable from the callbacks via + * `duckdb_v2_function_bind_get_user_data()`, `duckdb_v2_data_source_init_global_get_user_data()`, + * `duckdb_v2_data_source_exec_get_user_data()` and their counterparts on the other phases. The opaque handle bundles + * the pointer with an optional destructor, invoked when the data is no longer needed. * * history: * - unstable: v2.0.0 * - * @param statement The statement. - * @param out_text Receives a borrowed pointer to the statement text, valid until the statement is destroyed. - * @param out_text_length Receives the length of `*out_text` in bytes. `*out_text` is not guaranteed to be - * null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @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_sql_statement_get_text(duckdb_v2_sql_statement_handle statement, - const char **out_text, idx_t *out_text_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_user_data(duckdb_v2_table_function_handle function, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of distinct parameters the statement declares. + * Sets the bind callback of the table function. * - * This counts the parameters the parser found ($1, ?, $name, ...), so it needs no catalog and no binding; only the - * parameter types wait for `duckdb_v2_statement_bind()`. Repeated uses of one parameter count once. + * The bind callback is invoked during query planning for each call site of the function. It must declare the columns + * the function returns via `duckdb_v2_table_function_bind_add_result_column()`. Through its + * `duckdb_v2_function_bind_info_handle` it can also inspect the constant argument values and set "bind data" that is + * shared with all later callbacks. A bind callback must be set before registration. * * history: * - unstable: v2.0.0 * - * @param statement The statement. - * @param out_count Receives the number of distinct parameters. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the bind callback of. + * @param callback The bind callback to set. + * @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_sql_statement_get_parameter_count(duckdb_v2_sql_statement_handle statement, - idx_t *out_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_bind_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_bind_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the name of one parameter, in binding order. + * Sets whether the table function supports projection pushdown. Defaults to false. * - * Parse-time metadata. Positions follow the parameters' binding indices, the order of `duckdb_v2_statement_bind()`'s - * parameter schema, so position i here names field i there. The name is the binding key that - * `duckdb_v2_statement_execute()` accepts: "1", "2", ... for a positional parameter ($1 or ?), the identifier for a - * named one ($name). Positional indices may be gapped ($1 and $3 without $2), in which case the names are "1" and "3" - * at positions 0 and 1. The view is valid until the statement is destroyed. An index outside [0, count) is rejected - * with ERROR_INPUT_OUT_OF_RANGE. + * With projection pushdown, the engine asks the function for only the columns a query actually uses: the exec + * callback's output chunk holds one vector per requested column rather than one per column declared in bind, and the + * global init, local init and exec callbacks can look up which declared column each vector stands for via e.g. + * `duckdb_v2_data_source_exec_get_column_index()`. Without it the output chunk always holds every declared column, and + * the engine drops the unused ones itself. * * history: * - unstable: v2.0.0 * - * @param statement The statement. - * @param index Zero-based position in binding order. - * @param out_name Receives a borrowed pointer to the parameter name, valid until the statement is destroyed. - * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be - * null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to configure. + * @param enable Whether the function supports projection pushdown. + * @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_sql_statement_get_parameter_name(duckdb_v2_sql_statement_handle statement, - idx_t index, const char **out_name, - idx_t *out_name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_projection_pushdown(duckdb_v2_table_function_handle function, + bool enable, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a statement handle. + * Declares that the table function can produce the given virtual column. * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. statement_execute does not consume a - * statement, so every statement is destroyed here once it is no longer needed. On success the slot is set to nullptr. + * A virtual column is not one of the columns declared in bind: the query asks for it by name, and the function only + * produces it when it is asked for. It then takes up a vector of the exec callback's output chunk, like any other + * column the scan produces. This requires projection pushdown (see + * `duckdb_v2_table_function_set_projection_pushdown()`), which is what lets the engine ask for it. The global init, + * local init and exec callbacks recognize the vector by its column index, which is 2^63 plus the value of the + * `DUCKDB_V2_TABLE_VIRTUAL_COLUMN` (see e.g. `duckdb_v2_data_source_exec_get_column_index()`). * * history: * - unstable: v2.0.0 * - * @param statement The statement to destroy. + * @param function The function to configure. + * @param column The virtual column the function can produce. + * @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_sql_statement_destroy(duckdb_v2_sql_statement_handle *statement); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_add_virtual_column(duckdb_v2_table_function_handle function, + DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a statement iterator handle. + * Sets the optional filter pushdown callback of the table function. * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. Statements already yielded are independently - * owned and stay valid. On success the slot is set to nullptr. + * The filter pushdown callback is invoked while the query is optimized, after the bind callback and before any init + * callback, with the filter predicates the query applies to the function's rows. Each predicate is a bound expression + * the callback can inspect with the `expression` functions; the callback accepts the predicates it will apply itself + * via `duckdb_v2_table_function_filter_pushdown_accept()`, typically after recording what they select in the bind data. + * The engine then stops applying the accepted predicates and keeps applying the rest above the scan, so accepting a + * predicate is a promise to filter the rows exactly as it would have. The optimizer may invoke the callback more than + * once for the same query, each time with the predicates not yet accepted; it is not invoked when there are none. + * + * A function that also has projection pushdown (see `duckdb_v2_table_function_set_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, in the same form, with the column references resolved by + * `duckdb_v2_table_function_filter_pushdown_get_column_index()` as at optimization time. This is how the callback of a + * function wrapped in a multi-file function sees the predicates, which the optimizer only offers to the wrapper. 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 but does not have to understand them, and accepting one has no effect. The scan keeps the + * columns the predicates are applied to. * * history: * - unstable: v2.0.0 * - * @param iterator The iterator to destroy. + * @param function The function to set the filter pushdown callback of. + * @param callback The filter pushdown callback to set. + * @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_statement_iterator_destroy(duckdb_v2_statement_iterator_handle *iterator); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_filter_pushdown_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_filter_pushdown_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for sql_statement --- */ - -/* ============================================================================ - * MODULE: vector - * ============================================================================ */ - -/* --- Enums for vector --- */ - -/*! - * Internal representation of a vector, with FSST / SEQUENCE / SHREDDED collapsed into OTHER: the view getter rejects - * those and requires an explicit vector_flatten first. OTHER is the 0-value, so a zero-initialized out-param reads as - * "unspecified, needs flatten" rather than silently looking like FLAT. - */ -typedef enum DUCKDB_V2_VECTOR_TYPE { - //! Default for zero-init. Covers FSST / SEQUENCE / SHREDDED — call vector_flatten first. - DUCKDB_V2_VECTOR_TYPE_OTHER = 0, - - //! Standard per-row storage. - DUCKDB_V2_VECTOR_TYPE_FLAT = 1, - - //! A single value applies to every row in the vector. - DUCKDB_V2_VECTOR_TYPE_CONSTANT = 2, - - //! Data + selection vector indirection into another vector. - DUCKDB_V2_VECTOR_TYPE_DICTIONARY = 3, - DUCKDB_V2_VECTOR_TYPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_VECTOR_TYPE; - -/* --- Struct forward declarations for vector --- */ - -typedef struct duckdb_v2_vector_view duckdb_v2_vector_view; - -typedef struct duckdb_v2_list_entry duckdb_v2_list_entry; - -typedef struct duckdb_v2_hugeint_t duckdb_v2_hugeint_t; - -typedef struct duckdb_v2_uhugeint_t duckdb_v2_uhugeint_t; - -typedef struct duckdb_v2_interval_t duckdb_v2_interval_t; - -/* --- Types for vector --- */ - -/* --- Constants for vector --- */ - -/* --- Function pointer typedefs for vector --- */ - -/* --- Functions for vector --- */ - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the internal representation kind: flat, constant, or dictionary. + * Sets the optional "partitioning" callback of the table function. * - * Reports VECTOR_TYPE_OTHER for FSST / SEQUENCE / SHREDDED vectors, which must be passed through vector_flatten before - * vector_get_view will read them. + * The callback tells the query optimizer, for a candidate `GROUP BY` column set, whether every partition the scan + * produces carries exactly one distinct value for those columns; only `TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS` + * unlocks the partitioned aggregate optimization; any other result, or leaving this callback unset, keeps the regular + * hash aggregate. It runs on the planning thread, before execution starts, and must be deterministic for a given column + * set since it may be called on a plan the optimizer later discards. Registration fails unless + * `duckdb_v2_data_source_set_partition_data_callback()` is set too, since the engine asks that callback for the + * partitioning column values once this one claims single-value partitions. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_type Receives the representation kind. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the partitioning callback of. + * @param callback The partitioning callback to set. + * @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_vector_get_vector_type(duckdb_v2_vector_handle vector, - DUCKDB_V2_VECTOR_TYPE *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_partitioning_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_partitioning_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the vector's logical type. + * Sets the optional stats callback of the table function. * - * The returned logical type is the same type that was passed to vector_reference, or the type that was set on creation. - * It is caller-owned; destroy it via logical_type_destroy. + * The stats callback is invoked during query optimization once for each declared column the query reads, when the + * engine wants to know about the column's values without reading them - e.g. to prune a scan whose filter no value can + * satisfy, to answer `min()` / `max()` from the statistics, or to estimate the selectivity of a filter. Through its + * `duckdb_v2_table_function_stats_info_handle` the callback narrows the statistics of that column (see + * `duckdb_v2_table_function_stats_get_result_stats()`): its minimum and maximum, whether it holds NULLs, the statistics + * of the children of a nested column, ... Leaving the statistics unchanged tells the engine nothing about the column. + * The statistics must hold for every row the call produces: a bound that excludes a value the scan then produces leads + * to wrong results. A function without a stats callback gives the engine no statistics for its columns. The callback is + * only asked about whole declared columns, never about virtual columns or about fields extracted from a column. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_type Receives the caller-owned logical type handle. Destroy via logical_type_destroy. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the stats callback of. + * @param callback The stats callback to set. + * @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_vector_get_logical_type(duckdb_v2_vector_handle vector, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_stats_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_stats_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reads a vector as a unified view of data, validity, selection, and count. - * - * Populates out_view with borrowed pointers, valid until the owning chunk is destroyed. view.data addresses the - * vector's elements, to be cast to the layout its logical type implies: a typed leaf array for the primitives, - * hugeint_t / uhugeint_t / interval_t for those kinds, bytes for VARCHAR / BLOB / BIT / BIGNUM, list_entry for LIST and - * MAP, and nothing at all for ARRAY / STRUCT / UNION, whose data lives in their children. - * - * DECIMAL and ENUM are typed leaf arrays too, over a storage tier that follows from the type; both mappings are - * contract. A DECIMAL of width <= 4 stores int16, <= 9 int32, <= 18 int64, and <= 38 int128, boundaries inclusive, with - * the width and scale available from logical_type_get_param. An ENUM stores its dictionary indices as uint8 for a - * dictionary of at most 255 entries, uint16 for at most 65535, and uint32 beyond that, boundaries inclusive and an - * empty dictionary uint8; logical_type_get_param resolves an index to its entry. - * - * Rejects VECTOR_TYPE_OTHER; call vector_flatten first. + * Declares one of the columns the function returns. * - * Reading a DICTIONARY vector has one side effect: the dictionary's underlying child is flattened in place if it is not - * already FLAT. The parent vector stays DICTIONARY, and only the child's storage shape changes, but any pointer - * previously borrowed into that child — from an earlier vector_get_view on a vector aliasing the same buffer, say — is - * invalidated. This is the only mutation vector_get_view performs; compare vector_flatten, which materializes the whole - * vector to FLAT. + * Call this once per column, in order: the columns declared here are the columns of the table the function produces, + * and the vectors of the output chunk the exec callback fills follow the same order. At least one column must be + * declared. The type must be a fully defined concrete type; ANY is rejected, as a result column carries data. The name + * and type are borrowed and copied. * * history: * - unstable: v2.0.0 * - * @param vector The vector to read. - * @param out_view Receives the view. Its pointers are borrowed and valid until the owning chunk is destroyed. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param name The name of the column. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param type The type of the column. Borrowed and copied. + * @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_vector_get_view(duckdb_v2_vector_handle vector, duckdb_v2_vector_view *out_view, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_add_result_column( + duckdb_v2_table_function_bind_info_handle info, const char *name, idx_t name_length, + duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of elements in the vector. + * Sets the estimated number of rows the scan will produce. * - * The size is the number of logical elements the vector represents, which for a nested kind can differ from the size of - * its children. An ARRAY vector of size 10 whose array size is 3, for instance, has 10 logical elements while its - * single child vector has 30. + * The estimate is a hint for the optimizer, not a limit: producing a different number of rows is not an error. Without + * it, the optimizer falls back on its own defaults. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_size Receives the number of elements. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param cardinality The estimated number of rows. + * @param is_exact Whether the estimate is exact, which also makes it an upper bound on the row count. + * @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_vector_get_size(duckdb_v2_vector_handle vector, idx_t *out_size, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_set_cardinality( + duckdb_v2_table_function_bind_info_handle info, idx_t cardinality, bool is_exact, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the number of elements in the vector. + * Sets the order guarantee of the rows this call of the function produces. Defaults to + * `ORDER_PRESERVATION_INSERTION_ORDER`. * - * The counterpart of vector_get_size: it declares how many logical elements the vector now holds. It reserves enough - * space for size logical elements. + * With `ORDER_PRESERVATION_NO_ORDER`, a scan that reports more than one thread via + * `duckdb_v2_data_source_init_global_set_max_threads()` runs in parallel into query results, INSERT and COPY without a + * `duckdb_v2_data_source_set_partition_data_callback()`, and the rows arrive in no particular order. With insertion + * order kept, those consumers need the partition data callback to run in parallel. Fails with `ERROR_INPUT_INVALID` + * when order is not one of the enum's declared values. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param size The new number of logical elements. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param order The order guarantee of the produced rows. + * @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_vector_set_size(duckdb_v2_vector_handle vector, idx_t size, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_set_order_preservation( + duckdb_v2_table_function_bind_info_handle info, DUCKDB_V2_ORDER_PRESERVATION order, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reads one cell of a vector as an owned value. - * - * The total fallback reader. It reads any logical row of any vector representation without flattening — FLAT, CONSTANT, - * DICTIONARY, and the compressed kinds the view getter rejects — and covers every type kind, including those with no - * committed view layout (today VARIANT and GEOMETRY), where it is the only way to reach a cell. - * - * Each call allocates one owned value, which makes this a single-cell bridge rather than a per-row loop primitive; use - * vector_get_view on hot paths. The row index is logical and bounds-checked against vector_get_size. The returned value - * is caller-owned; destroy it via value_destroy. + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`, or null if none was set. * * history: * - unstable: v2.0.0 * - * @param vector The vector to read from. - * @param row The logical row index, in [0, vector_get_size). - * @param out_value Receives the owned cell value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param data Receives the user data pointer. + * @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_vector_get_value(duckdb_v2_vector_handle vector, idx_t row, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_user_data( + duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Writes one cell of a FLAT vector from a value. - * - * The total fallback writer. It covers every type kind, including those with no committed view layout (today VARIANT - * and GEOMETRY), where it is the only way to write a cell. The value is borrowed and copied in, then cast to the - * vector's type through the non-strict default cast; a cast failure surfaces from the call. A NULL value clears the - * row's validity. + * Retrieves the bind data set via `duckdb_v2_function_bind_set_bind_data()`, or null if none was set. * - * Requires a FLAT vector: constant, dictionary, and compressed representations are not row-addressable, so call - * vector_flatten first. Each call performs one value write, which makes this a single-cell bridge rather than a per-row - * loop primitive; use the typed mutable-data paths on hot paths. The row index is logical and bounds-checked against - * vector_get_size. + * This is the same object the init and exec callbacks later receive, so a predicate the callback accepts can be + * recorded in it for the scan to apply. * * history: * - unstable: v2.0.0 * - * @param vector The vector to write to. - * @param row The logical row index, in [0, vector_get_size). - * @param value The borrowed value to write. Copied in; cast to the vector's type. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param data Receives the bind data pointer. + * @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_vector_set_value(duckdb_v2_vector_handle vector, idx_t row, - duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_bind_data( + duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns a mutable pointer to the data of a FLAT or CONSTANT vector. - * - * Any other representation returns ERROR_INPUT_INVALID. The pointer is valid until the owning chunk is destroyed, and - * the vector's storage shape must not change — through a flatten, say — while it is in use. + * Returns the number of filter predicates offered to the function. * - * When writing VARCHAR values, the caller must ensure that the bytes contain valid UTF-8. + * The predicates are combined with `AND`: every row the scan produces must satisfy all of them. Valid indices for + * `duckdb_v2_table_function_filter_pushdown_get_filter()` and `duckdb_v2_table_function_filter_pushdown_accept()` are + * `0` up to (but excluding) this count. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_data Receives a mutable pointer to the data. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param count Receives the number of predicates. + * @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_vector_get_data_mutable(duckdb_v2_vector_handle vector, void **out_data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_filter_count( + duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Forces a vector into FLAT representation, in place. + * Retrieves the filter predicate at the given index. * - * A no-op for a vector that is already FLAT. For a CONSTANT, DICTIONARY, FSST, SEQUENCE, or SHREDDED vector it - * materializes the per-row data and switches the representation to FLAT. Call it before vector_get_view if you would - * rather not handle CONSTANT and DICTIONARY semantics in the view; it is required for any vector reporting - * VECTOR_TYPE_OTHER. + * Fails if the index is out of bounds. The predicate is a bound expression evaluating to `BOOLEAN`; inspect it with + * `duckdb_v2_expression_get_type()` and the other `expression` functions, and resolve the column references it contains + * via `duckdb_v2_table_function_filter_pushdown_get_column_index()`. Borrowed; valid only for the duration of the + * callback. * * history: * - unstable: v2.0.0 * - * @param vector The vector to flatten. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param index The index of the predicate to retrieve. + * @param filter Receives the borrowed predicate. + * @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_vector_flatten(duckdb_v2_vector_handle vector, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_filter( + duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, duckdb_v2_expression_handle *filter, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Casts every row of a vector into another vector, using a factory. - * - * The conversion is the one SQL `CAST` / `TRY_CAST` performs, registered custom casts included, from the type of - * `source` to the type of `target`. It covers as many rows as `source` holds (`duckdb_v2_vector_get_size()`), of any - * representation. `target` is replaced by the result, as `duckdb_v2_vector_reference()` would, taking its size: data - * and views taken from it beforehand do not survive the call, and nothing it held before carries over. In - * CAST_MODE_NORMAL a row that does not convert fails the call with the engine's conversion error, and the contents of - * `target` are unspecified. In CAST_MODE_TRY such rows are NULL in `target` instead and the call succeeds; compare the - * validity of `source` and `target` to find them. `cast_err` then receives the conversion error of one of them, e.g. to - * report why the cast did not convert every row. + * Accepts the filter predicate at the given index: the function will apply it itself. * - * A connection's or callback's factory casts with that client's cast functions and settings (e.g. TimeZone). An - * instance's factory supports only the built-in casts, with default settings. `source` and `target` must be different - * vectors; `target` is typically a vector of a data chunk created by the caller, or the result vector of a callback. + * The engine stops applying an accepted predicate, so the scan must produce only rows that satisfy it, or the query + * returns rows it should not. Predicates left unaccepted are applied by the engine as usual, so a callback that + * recognizes nothing can simply return. Fails if the index is out of bounds. * * history: * - unstable: v2.0.0 * - * @param factory The factory supplying the cast functions. - * @param source The vector to cast. Borrowed for the call only. - * @param target The vector to write the cast rows into. Its logical type is the target type. - * @param mode Whether a row that does not convert fails the call, or becomes NULL. - * @param out_converted Optional. Receives whether every row converted. Always true when a CAST_MODE_NORMAL cast - * succeeds. - * @param cast_err Optional. When a CAST_MODE_TRY cast succeeds without converting every row, receives an opaque info - * handle with the conversion error of one row that did not convert, which the caller must destroy via - * error_info_destroy. Otherwise receives NULL. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param index The index of the predicate to accept. + * @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_vector_cast(duckdb_v2_factory_handle factory, duckdb_v2_vector_handle source, - duckdb_v2_vector_handle target, DUCKDB_V2_CAST_MODE mode, - bool *out_converted, duckdb_v2_error_info_handle *cast_err, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_accept( + duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Repoints a vector at another vector's data, without copying. + * Returns the number of columns the predicates can refer to. * - * `vector` takes on the storage of `source`: no data moves, and the two alias the same buffers until one of them is - * reset or re-referenced. Works for any type, including nested types. The source's logical type must equal the - * vector's; a mismatch returns ERROR_INPUT_INVALID. The source's data must outlive every read of `vector`. Use it to - * hand an already-materialized vector straight to an output vector without a per-row copy. + * A column reference inside a predicate (`duckdb_v2_expression_column_ref_get_index()`) indexes the columns the query + * reads from the function, not the columns declared in bind. Valid indices for + * `duckdb_v2_table_function_filter_pushdown_get_column_index()` are `0` up to (but excluding) this count. * * history: * - unstable: v2.0.0 * - * @param vector The vector to repoint at the source's data. - * @param source The vector whose data to reference. Its logical type must equal the vector's. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param count Receives the number of referable columns. + * @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_vector_reference(duckdb_v2_vector_handle vector, duckdb_v2_vector_handle source, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_column_count( + duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Turns the vector into a CONSTANT vector holding the given value. + * Resolves a column reference found in a predicate to the declared column it refers to. * - * Afterwards the vector holds a single element that applies to every logical row; write it through - * vector_get_data_mutable, which returns a pointer to that one element. For a STRUCT vector the change propagates to - * every child. The value's logical type must equal the vector's; a mismatch returns ERROR_INPUT_INVALID. + * Takes the index a `EXPRESSION_TYPE_BOUND_COLUMN_REF` node reports and returns the index of the column among the ones + * declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration order. Fails if the index is out of + * bounds. * * history: * - unstable: v2.0.0 * - * @param vector The vector to make constant. - * @param value The value every row takes. Its logical type must equal the vector's. - * @param count The number of elements in the vector. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param index The column index reported by a column reference node. + * @param column_index Receives the index of the declared column. + * @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_vector_make_constant(duckdb_v2_vector_handle vector, - duckdb_v2_value_handle value, idx_t count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_column_index( + duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets a vector to a SEQUENCE representation. - * - * Afterwards the vector represents the arithmetic sequence start, start+increment, start+2*increment, ... over count - * elements. No data pointer is involved; the three parameters describe the sequence completely. + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param vector The vector to turn into a sequence. - * @param start The first value of the sequence. - * @param increment The step between consecutive values. - * @param count The number of elements in the sequence. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partitioning info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_vector_make_sequence(duckdb_v2_vector_handle vector, int64_t start, - int64_t increment, idx_t count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_user_data( + duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets one row of a FLAT vector to NULL, nested children included. - * - * Clears the row's validity and broadcasts the NULL recursively to every descendant element under that row — STRUCT - * fields, and ARRAY elements strided by the array size — maintaining DuckDB's nested NULL invariant: when a STRUCT or - * ARRAY row is NULL, every descendant element under it must be NULL too. LIST children are left untouched, since their - * consumers gate on the list's own validity. Which kinds propagate is normative DuckDB behavior that evolves with the - * type system, which makes this the total NULL write path: equivalent to vector_set_value with a NULL value, without - * the per-call value allocation. - * - * Requires a FLAT vector: constant, dictionary, and compressed representations are not row-addressable, so call - * vector_flatten first. The row index is logical and bounds-checked against vector_get_size. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param vector The vector to write to. - * @param row The logical row index, in [0, vector_get_size). - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partitioning info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_vector_set_null(duckdb_v2_vector_handle vector, idx_t row, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_bind_data( + duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns a mutable pointer to the validity mask of a FLAT vector. - * - * Allocates the mask on first use, so the returned pointer is always non-null. Each uint64_t word covers 64 rows: bit N - * of word W is row W*64+N. A set bit means valid; a cleared bit means NULL. + * Returns the number of columns the optimizer is asking about: the candidate `GROUP BY` column set. * - * A raw mask write marks only this vector's rows. Clearing a STRUCT or ARRAY parent bit leaves the descendant elements - * untouched, which violates DuckDB's nested NULL invariant — a NULL STRUCT or ARRAY row requires NULL descendants — so - * set nested rows NULL through vector_set_null instead. When writing nested masks raw anyway, invalidate the child - * masks up front and mark elements valid as the values are written. + * Valid indices for `duckdb_v2_table_function_partitioning_get_partition_column_index()` are `0` up to (but excluding) + * this count. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_validity Receives a mutable pointer to the validity mask. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partitioning info handle. + * @param count Receives the number of columns in the candidate set. + * @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_vector_flat_get_validity_mutable(duckdb_v2_vector_handle vector, - uint64_t **out_validity, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_partition_column_count( + duckdb_v2_table_function_partitioning_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the validity of a CONSTANT vector. + * Returns which declared column the candidate `GROUP BY` column at the given index stands for. * - * A constant vector holds a single element, so one flag decides whether every row reads as the value or as NULL. + * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration + * order. Fails if the index is out of bounds. * * history: * - unstable: v2.0.0 * - * @param vector The constant vector. - * @param validity True to mark the vector's single element valid, false to mark it NULL. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partitioning info handle. + * @param index The index of the candidate column. + * @param column_index Receives the index of the declared column. + * @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_vector_constant_set_valid(duckdb_v2_vector_handle vector, bool validity, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_partition_column_index( + duckdb_v2_table_function_partitioning_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows a string-backed vector's arena for writing. + * Reports whether every partition the scan produces carries exactly one distinct value for the candidate `GROUP BY` + * column set. * - * Allocates the arena on first use. Valid for VARCHAR, BLOB, BIT, and BIGNUM vectors, and returns ERROR_INPUT_INVALID - * for anything else. This call is the single string-ness check, which is why arena_allocate itself performs none. The - * arena is borrowed — never destroy it — and stays valid until the vector is flattened, reallocated, or destroyed. + * Only `TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS` unlocks the partitioned aggregate optimization; any other value + * keeps the regular hash aggregate. A callback that never calls this is treated as reporting + * `TABLE_PARTITION_INFO_NOT_PARTITIONED`. Fails with `ERROR_INPUT_INVALID` when partition_info is not one of the enum's + * declared values. * * history: * - unstable: v2.0.0 * - * @param vector The string-backed vector whose arena to borrow. - * @param out_arena Receives the borrowed arena handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partitioning info handle. + * @param partition_info Whether, and how, the scan is partitioned by the candidate column set. + * @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_vector_get_arena(duckdb_v2_vector_handle vector, - duckdb_v2_arena_handle *out_arena, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_set_partition_info( + duckdb_v2_table_function_partitioning_info_handle info, DUCKDB_V2_TABLE_PARTITION_INFO partition_info, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of child vectors a nested vector exposes. - * - * 1 for LIST, MAP and ARRAY; the field count for STRUCT; member_count + 1 for UNION, the tag plus the members; and 0 - * for any non-nested kind. vector_get_child documents what each index addresses. + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_count Receives the number of child vectors. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_vector_get_child_count(duckdb_v2_vector_handle vector, idx_t *out_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_user_data( + duckdb_v2_table_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows a child vector by index. - * - * What each index addresses, by kind: LIST and ARRAY expose [0] = the elements; MAP [0] = the entries, a STRUCT(key, - * value) whose children are the keys and the values; STRUCT and TUPLE [i] = field i; and UNION [0] = the tag with - * [1..N] = the members. Note that value_get_child diverges on UNION, exposing only the active member. - * - * The returned child is borrowed and lives as long as the owning chunk. Returns ERROR_INPUT_INVALID if the vector has - * no children, or if the index is out of range. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param vector The nested vector to descend into. - * @param index The child index, in [0, vector_get_child_count). - * @param out_child Receives the borrowed child vector. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_vector_get_child(duckdb_v2_vector_handle vector, idx_t index, - duckdb_v2_vector_handle *out_child, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_bind_data( + duckdb_v2_table_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Decodes BIGNUM storage bytes into a caller-supplied magnitude buffer + sign flag. - * - * in_data and in_length are the value's raw storage bytes, exactly as they sit in a vector's bignum payload or as - * value_get_blob reports them for a BIGNUM value. Those bytes are opaque: the storage encoding is not a committed part - * of this API, and this function is the only thing that interprets them. - * - * Writes the big-endian magnitude bytes into out_data and the sign flag into out_is_negative; reconstruct the integer - * as (-1)**out_is_negative * unsigned_big_endian(out_data[0..out_length]). Materializing the bytes is unavoidable, - * since a negative bignum stores its magnitude bit-inverted, but the buffer belongs to the caller: this function never - * allocates and hands back nothing to free. - * - * Pass out_data = NULL to size the buffer without decoding. out_length then receives the exact number of magnitude - * bytes and out_is_negative the sign, and out_capacity is ignored. The size comes straight out of the storage header, - * so the query is O(1) and exact — a size call followed by a decode call never needs a retry loop. - * - * With out_data != NULL, out_capacity must be at least out_length bytes, or the call returns ERROR_INPUT_OBJECT_SIZE - * with out_length set to the required size and out_data left untouched. On success exactly out_length bytes are - * written, and the rest of the buffer is not modified. + * Returns which declared column the statistics describe. * - * Returns ERROR_INPUT_INVALID if in_data is NULL, or if in_length is too short to hold a bignum header. + * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration + * order. It is never the index of a virtual column or of a field extracted from a column; the callback is not asked + * about those. * * history: * - unstable: v2.0.0 * - * @param in_data The value's raw BIGNUM storage bytes. - * @param in_length Size of in_data in bytes. - * @param out_data Caller-owned buffer receiving the magnitude bytes, or NULL to only report the required size in - * out_length. - * @param out_capacity Bytes available in out_data. Ignored when out_data is NULL. - * @param out_length Receives the magnitude size in bytes, written on success and on ERROR_INPUT_OBJECT_SIZE. - * @param out_is_negative Receives true if the value is negative, false otherwise. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param column_index Receives the index of the declared column. + * @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_bignum_decode(const uint8_t *in_data, idx_t in_length, uint8_t *out_data, - idx_t out_capacity, idx_t *out_length, bool *out_is_negative, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_column_index( + duckdb_v2_table_function_stats_info_handle info, idx_t *column_index, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Encodes a magnitude + sign flag into BIGNUM storage bytes. - * - * The inverse of bignum_decode. in_data and in_length are the big-endian magnitude bytes and is_negative the sign; - * out_data receives the raw storage bytes for that integer, in the form a BIGNUM vector payload expects. Those bytes - * are opaque: the storage encoding is not a committed part of this API. - * - * Pass out_data = NULL to size the buffer without encoding. out_length then receives the exact number of storage bytes, - * and out_capacity is ignored. The size is a fixed function of in_length, so the query is O(1) and exact. - * - * With out_data != NULL, out_capacity must be at least out_length bytes, or the call returns ERROR_INPUT_OBJECT_SIZE - * with out_length set to the required size and out_data left untouched. On success exactly out_length bytes are - * written, and the rest of the buffer is not modified. + * Retrieves the statistics of the column, for the callback to narrow. * - * The magnitude must be canonical, matching what bignum_decode produces: in_length >= 1 with no leading zero bytes, so - * the value zero is the single byte 0x00 with is_negative = false. A NULL in_data, an in_length of 0, a leading zero - * byte, or a negative zero returns ERROR_INPUT_INVALID; a magnitude beyond the maximum bignum width returns - * ERROR_INPUT_OUT_OF_RANGE. + * The statistics start out unknown, with every kind of value possible, and are of the column's type as the bind + * callback declared it. The callback narrows them with `duckdb_v2_stats_set_value()`, from a STRUCT value in the shape + * `duckdb_v2_stats_get_value()` returns - e.g. `{'min': 20, 'max': 30, 'has_null': false}` for an INTEGER column, or + * the statistics of the fields of a STRUCT column under `child_stats` - and with `duckdb_v2_stats_set_can_have_null()` + * / `duckdb_v2_stats_set_can_have_valid()`. Statistics built with `duckdb_v2_stats_create()`, e.g. combined from the + * files of a scan with `duckdb_v2_stats_merge()`, are copied in with `duckdb_v2_stats_assign()`. They describe every + * value the scan produces for the column. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param in_data Big-endian magnitude bytes, with no leading zero bytes. - * @param in_length Size of in_data in bytes. Must be >= 1. - * @param is_negative True to encode a negative value. - * @param out_data Caller-owned buffer receiving the storage bytes, or NULL to only report the required size in - * out_length. - * @param out_capacity Bytes available in out_data. Ignored when out_data is NULL. - * @param out_length Receives the storage size in bytes — written on success and on ERROR_INPUT_OBJECT_SIZE. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param stats Receives the borrowed, writable statistics of the column. + * @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_bignum_encode(const uint8_t *in_data, idx_t in_length, bool is_negative, - uint8_t *out_data, idx_t out_capacity, idx_t *out_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_result_stats( + duckdb_v2_table_function_stats_info_handle info, duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Validates all `text_length` bytes of `text` as UTF-8, including bytes after embedded NUL characters. - * - * Returns ERROR_INPUT_INVALID if any of: - * - text is NULL and text_length is nonzero. - * - The input contains malformed UTF-8. + * Registers the table function, making it available for use in SQL queries. * - * A NULL text with a zero length is valid. + * The function is registered on the connection's database, visible to every connection, in the connection's + * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and + * a rollback undoes it. Registration requires a name, a bind callback and an exec callback, and rejects a signature + * that declares a return type, since a table function declares the columns it returns from its bind callback. The table + * function must have been created through a factory of the same database. The caller still owns the handle after + * registration and must destroy it with `duckdb_v2_table_function_destroy()`, which does not affect the registered + * function. * * history: * - unstable: v2.0.0 * - * @param text The bytes to validate. - * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this - * is 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param conn The connection to register on. + * @param function The table function to register. + * @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_validate_utf8(const char *text, idx_t text_length, - duckdb_v2_error_info_handle *err); -#endif - -/* --- Struct definitions for vector --- */ - -struct duckdb_v2_vector_view { - const void *data; - const uint64_t *validity; - const duckdb_v2_sel_t *sel; - idx_t count; -}; - -struct duckdb_v2_list_entry { - idx_t offset; - idx_t length; -}; - -struct duckdb_v2_hugeint_t { - uint64_t lower; - int64_t upper; -}; - -struct duckdb_v2_uhugeint_t { - uint64_t lower; - uint64_t upper; -}; - -struct duckdb_v2_interval_t { - int32_t months; - int32_t days; - int64_t micros; -}; - -/* ============================================================================ - * MODULE: prepared_statement - * ============================================================================ */ - -/* --- Enums for prepared_statement --- */ - -/* --- Struct forward declarations for prepared_statement --- */ - -/* --- Types for prepared_statement --- */ - -/*! - * An owned handle to a statement bound and planned once, executable repeatedly via - * `duckdb_v2_prepared_statement_execute()`. Construct with `duckdb_v2_prepared_statement_create()` and destroy with - * `duckdb_v2_prepared_statement_destroy()`. It keeps its connection's session alive, so it stays usable across - * executions and even after the connection is disconnected. - */ -typedef struct _duckdb_v2_prepared_statement { - void *internal_ptr; -} * duckdb_v2_prepared_statement_handle; - -/* --- Constants for prepared_statement --- */ - -/* --- Function pointer typedefs for prepared_statement --- */ - -/* --- Functions for prepared_statement --- */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_table_function(duckdb_v2_connection_handle conn, + duckdb_v2_table_function_handle function, + duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Prepares a parsed statement into a reusable handle. Non-consuming. - * - * Copies the statement's AST, then binds and plans it once. Binder and catalog errors surface here, exactly as they - * would from `duckdb_v2_statement_execute()`. The statement is borrowed rather than consumed, since a copy is what gets - * prepared, so it can be prepared again or executed directly; the caller destroys it with - * `duckdb_v2_sql_statement_destroy()`. - * - * By default this succeeds for any preparable statement, whether or not its plan will be reused; ask - * `duckdb_v2_prepared_statement_reuses_plan()` which one you got. Setting `require_cacheable` instead fails with - * `ERROR_INPUT_INVALID` when the plan would not be reused, so a caller who wants the handle only for the speedup finds - * out here rather than after silently taking the slow path. - * - * A statement that DuckDB expands into several, such as a dynamic PIVOT, is kept as written and expanded again at each - * execution, in the transaction state of that execution. It runs nothing here, its plan is never reused, and its - * result's metadata is deferred as for `duckdb_v2_statement_execute()`. Parameters on such a statement are refused with - * `ERROR_INPUT_INVALID`. + * Registers the table function, making it available for use in SQL queries. * - * Refuses with `ERROR_RESOURCE_IN_USE` while a statement on the connection is still running. Drain, destroy, or - * interrupt that result first, or prepare on another connection. `*out_prepared` is set to NULL on failure. + * The function is registered on the loading extension's database and attributed to the extension. Use this from the + * extension's load callback. Registration requires a name, a bind callback and an exec callback, and rejects a + * signature that declares a return type, since a table function declares the columns it returns from its bind callback. + * The table function must have been created through a factory of the same database. The caller still owns the handle + * after registration and must destroy it with `duckdb_v2_table_function_destroy()`, which does not affect the + * registered function. * * history: * - unstable: v2.0.0 * - * @param conn The connection supplying the catalog, transaction, and parser state. The prepared statement belongs to - * it. - * @param statement The statement to prepare. Borrowed and copied, not consumed; destroy it with - * `duckdb_v2_sql_statement_destroy()`. - * @param require_cacheable When true, fail with `ERROR_INPUT_INVALID` unless the prepared plan will be reused across - * executions, as `duckdb_v2_prepared_statement_reuses_plan()` would report it. - * @param out_prepared On success, receives the new prepared statement. Owned by the caller; destroy via - * `duckdb_v2_prepared_statement_destroy()`. + * @param extension The loading extension. + * @param function The table function to register. * @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_prepared_statement_create(duckdb_v2_connection_handle conn, - duckdb_v2_sql_statement_handle statement, - bool require_cacheable, - duckdb_v2_prepared_statement_handle *out_prepared, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_table_function(duckdb_v2_extension_handle extension, + duckdb_v2_table_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Executes a prepared statement, streaming its result. Non-consuming. + * Destroys the table function, releasing its resources. * - * Returns a result without executing anything: execution happens incrementally as the result is stepped or drained, - * exactly as with `duckdb_v2_statement_execute()`. The handle returned is an ordinary result, with identical behaviour - * throughout -- streaming, draining, the changed-row count of a DML statement, the output schema, the statement type, - * and the result type. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered function. * - * `parameter_values` binds the statement's parameters as constants for this execution. Binding is positional by default - * ($1 = element 0); supply `parameter_names` to bind by name instead, where a non-empty entry binds its value to that - * named parameter ($name, matched case-insensitively) and an empty entry stays positional. Pass NULL for both arrays, - * or a count of 0, for a statement without parameters. Both arrays are borrowed and copied in, so the caller still owns - * and destroys them. A key set that does not match the statement's parameters is rejected with `ERROR_INPUT_INVALID`, - * with one exception: a named parameter left without a value reads the session variable of the same name (`SET - * VARIABLE`) when one exists. + * history: + * - unstable: v2.0.0 * - * Not consumed: execute the same handle again, with the same values or different ones, as often as you like. Values are - * bound per execution and nothing carries over between them. A catalog change since the statement was prepared, or a - * parameter type that differs from the one the cached plan assumed, triggers a re-bind that is invisible apart from its - * cost. + * @param function The function to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_destroy(duckdb_v2_table_function_handle *function); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the optional "get bind info" callback of the table function. * - * Refuses with `ERROR_RESOURCE_IN_USE` while a statement on the connection is still running; drain, destroy, or - * interrupt that result first, or execute on another connection. A failed execution, at any stage, leaves the prepared - * statement usable. `*out_result` is set to NULL on failure. + * The engine invokes the callback with the bind data of a bound call when it needs to know more about the call than its + * columns. E.g. a multi-file function registered with `duckdb_v2_connection_register_multi_file_function()` or + * `duckdb_v2_extension_register_multi_file_function()` asks the function it wraps for every file it binds: it maps the + * columns of the files onto the columns of its scan by the identifiers the callback reports, and exposes the options it + * reports as the metadata of the reader of the file. The callback may be invoked more than once for the same bind data, + * so it should only report what the bind already determined. * * history: * - unstable: v2.0.0 * - * @param prepared The prepared statement to execute. Borrowed; not consumed. - * @param parameter_names Optional. An array of `parameter_count` parameter names; a non-empty entry binds its value to - * the named parameter ($name, case-insensitive), an empty entry (NULL or zero length) keeps it positional ($1 = element - * 0). Pass NULL to bind everything positionally. - * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of - * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. - * @param parameter_values Optional. An array of `parameter_count` values. Each binds by name when `parameter_names` - * supplies one, and positionally ($1 = element 0) otherwise. Borrowed and copied in. Pass NULL for a statement without - * parameters. - * @param parameter_count The number of entries in `parameter_names` and `parameter_values`. Pass 0 for a statement - * without parameters. - * @param out_result On success, receives the new result. Owned by the caller; destroy via `duckdb_v2_result_destroy()`. + * @param function The function to set the callback of. + * @param callback The "get bind info" callback to set. * @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_prepared_statement_execute( - duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, - const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, - duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_get_bind_info_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_get_bind_info_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports whether the prepared statement reuses its compiled plan across executions. - * - * True when executions reuse the plan built at prepare time, provided the supplied values match the planned parameter - * types and nothing the plan depends on has changed; false when the statement re-binds on every execution, making it no - * faster than `duckdb_v2_statement_execute()`. A plan is reused only when all parameter types were resolved at prepare - * time and the plan is cacheable: `SELECT 42` reuses, `SELECT $1::INTEGER + 1` reuses, a statement reading a base table - * does not (it re-binds so a catalog change is picked up), and `SELECT $1 + $2` does not (the types are unknown until - * values arrive). - * - * A static property of the built plan, fixed when the statement was prepared and independent of the values later passed - * to `duckdb_v2_prepared_statement_execute()`. + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param prepared The prepared statement to inspect. - * @param out_reuses Receives true when the compiled plan is reused across executions, false when the statement re-binds - * each time. + * @param info The get bind info handle. + * @param data Receives the user data pointer, or null if none was set. * @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_prepared_statement_reuses_plan(duckdb_v2_prepared_statement_handle prepared, - bool *out_reuses, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_get_user_data( + duckdb_v2_table_function_get_bind_info_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a prepared statement. - * - * Null-safe: passing NULL, or a slot already set to NULL, is a no-op. A result produced by - * `duckdb_v2_prepared_statement_execute()` is independently owned and keeps the session alive itself, so the prepared - * statement may be destroyed while results made from it are still live. On success the slot is set to NULL. + * Retrieves the bind data the function's bind callback set for the bound call being described. * * history: * - unstable: v2.0.0 * - * @param prepared The prepared statement to destroy. + * @param info The get bind info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_prepared_statement_destroy(duckdb_v2_prepared_statement_handle *prepared); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_get_bind_data( + duckdb_v2_table_function_get_bind_info_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for prepared_statement --- */ - -/* ============================================================================ - * MODULE: query_result - * ============================================================================ */ - -/* --- Enums for query_result --- */ - -/*! - * Shape of a query result. QUERY_RESULT carries rows and columns; CHANGED_ROWS carries an affected row count, as an - * INSERT, UPDATE, or DELETE without RETURNING produces; NOTHING covers DDL and other statements with no row output. - */ -typedef enum DUCKDB_V2_RESULT_TYPE { - DUCKDB_V2_RESULT_TYPE_QUERY_RESULT = 0, - DUCKDB_V2_RESULT_TYPE_CHANGED_ROWS = 1, - DUCKDB_V2_RESULT_TYPE_NOTHING = 2, - DUCKDB_V2_RESULT_TYPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_RESULT_TYPE; - +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Outcome of a result_step call. WAITING is the 0-value, so a zero-initialized out-param reads as "no work product yet" - * rather than CHUNK, the same convention VECTOR_TYPE_OTHER follows. The four states are the ones a consumer acts on; - * they are deliberately not a projection of any internal enum. + * Attaches an identifier to a result column of the bound call, or to a field nested inside one. + * + * A multi-file reader can then map the columns of every file onto the columns of its scan by identifier rather than by + * name - e.g. by the field ids of a file format that carries them, so that renamed columns and fields are still found. + * An identifier is an INTEGER field id or a VARCHAR name. + * + * The nested field is addressed by a path of child indexes, starting at the result column at `column_index`: 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. An empty path addresses the result column itself. Setting an identifier again for the same + * column or field replaces it. Fails with `ERROR_INPUT_INVALID` when the column index is out of range, or the path does + * not address a nested field of the column's type. + * + * history: + * - unstable: v2.0.0 + * + * @param info The get bind info handle. + * @param column_index The index of the result column, in the order the bind callback declared the columns. + * @param child_path The path of child indexes addressing the nested field, or null for the column itself. + * @param child_path_length The number of entries in the path, 0 for the column itself. + * @param identifier The identifier, an INTEGER or VARCHAR value. Borrowed and copied. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR */ -typedef enum DUCKDB_V2_RESULT_STEP_STATUS { - //! No chunk yet; step again, or block in result_wait. - DUCKDB_V2_RESULT_STEP_STATUS_WAITING = 0, - - //! A caller-owned chunk was written to *out_chunk, or an array to *out_array. - DUCKDB_V2_RESULT_STEP_STATUS_CHUNK = 1, - - //! Stream exhausted. Sticky. - DUCKDB_V2_RESULT_STEP_STATUS_FINISHED = 2, - - //! Query was interrupted. Sticky. - DUCKDB_V2_RESULT_STEP_STATUS_CANCELLED = 3, - DUCKDB_V2_RESULT_STEP_STATUS_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_RESULT_STEP_STATUS; - -/* --- Struct forward declarations for query_result --- */ - -/* --- Types for query_result --- */ - -/* --- Constants for query_result --- */ - -/* --- Function pointer typedefs for query_result --- */ - -/* --- Functions for query_result --- */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_set_column_identifier( + duckdb_v2_table_function_get_bind_info_info_handle info, idx_t column_index, const idx_t *child_path, + idx_t child_path_length, duckdb_v2_value_handle identifier, duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Executes a parsed statement on the connection, streaming its result. Non-consuming. - * - * Takes a statement produced by the sql_statement module (parse_sql / statement_iterator_next), preprocesses and - * prepares it, and returns a result handle without executing anything: execution happens incrementally as the result is - * stepped (result_step) or drained (result_fetch_chunk). This call reports only the errors detectable at prepare time — - * binder, catalog, pragma preprocessing — while errors raised during execution surface from the stepping functions. - * - * The statement is borrowed, not consumed, since a copy is what executes. It can be executed again, for example with a - * different set of values, and the caller destroys it with sql_statement_destroy. + * Sets an option describing the bound call: a key-value fact about what the call reads, e.g. a property of the file it + * reads. Setting a key again replaces its value. * - * parameter_values binds the statement's parameters as constants for this execution. Binding is positional by default: - * the i-th value binds $(i+1), matching SQL's own convention, so dense $1..$N and ? placeholders work directly. Supply - * parameter_names to bind by name instead — a non-empty name binds its value to that named parameter ($name, matched - * case-insensitively), while an empty entry leaves that value positional. The parameter schema from statement_bind - * lists the names to use. Both arrays are borrowed and copied in; the caller still owns and destroys them. Pass NULL - * for both, or a count of 0, for an unparameterized statement. A key set that does not match the statement's parameters - * — names for a positional statement, or the reverse — is rejected with ERROR_INPUT_INVALID, and named and positional - * parameters cannot be mixed within one statement. Parameters and statement expansion are mutually exclusive: passing - * values for a statement that preprocesses into a group is rejected with ERROR_INPUT_INVALID. + * A multi-file function registered with `duckdb_v2_connection_register_multi_file_function()` or + * `duckdb_v2_extension_register_multi_file_function()` exposes the options of the function it wraps as the metadata of + * the reader of each file, e.g. to a custom multi-file reader of another extension. * - * DuckDB can expand one statement into a group: a dynamic PIVOT, or statement-expanding DDL such as ALTER ... ADD - * COLUMN with a non-constant DEFAULT. The group executes as one result through the same steps, and the stream surfaces - * the rows of the first row-producing statement of the group. A row-producing statement followed by another cannot be - * served as a single result and reports ERROR_QUERY_NOT_IMPLEMENTED; no known expansion produces one. + * history: + * - unstable: v2.0.0 * - * One running statement per connection: this refuses with ERROR_RESOURCE_IN_USE while a statement on the connection is - * still running. Drain, destroy, or interrupt that result first, or open another connection. + * @param info The get bind info handle. + * @param key The key of the option. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param value The value of the option. Borrowed and copied. + * @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_table_function_get_bind_info_set_option( + duckdb_v2_table_function_get_bind_info_info_handle info, const char *key, idx_t key_length, + duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the optional "to string" callback of the table function. * - * Schema metadata — result type, statement type, column count, names, logical types — is available on the returned - * handle immediately, before the first step. + * The engine invokes the callback with the bind data of a bound call when it renders a query plan that scans the + * function, e.g. for `EXPLAIN`, `EXPLAIN ANALYZE` and the profiler, both for the logical and for the physical plan. The + * callback reports what the plan shows for the scan as key-value pairs with `duckdb_v2_table_function_to_string_set()`, + * e.g. the file or the remote table it reads. Without the callback the physical plan shows the name of the function + * under the key `Function`; with it, the plan shows what the callback reports instead, so a callback that wants the + * name shown reports it itself. The engine shows the projections, filters and estimated cardinality of the scan next to + * them either way. The callback may be invoked more than once for the same bind data, and is not invoked with the + * global state of a scan, so it should only report what the bind already determined. A function wrapped in a multi-file + * function is not asked: the plan describes the multi-file scan. * - * *out_result is set to nullptr on failure. + * With profiling enabled (including `EXPLAIN ANALYZE`), the engine also invokes the callback while the query executes, + * once per worker thread that scans the function. Calls can therefore run concurrently with the same bind data and user + * data, so the callback must not modify them without synchronization, and an error it reports there fails the query. + * Builds with assertions enabled also invoke it while executing queries without profiling. * * history: * - unstable: v2.0.0 * - * @param conn The connection on which to execute the statement. - * @param statement The statement to execute. Borrowed and copied; not consumed. Destroy it with sql_statement_destroy. - * @param parameter_names Optional. An array of parameter_count parameter names; a non-empty entry binds its value to - * the named parameter ($name, case-insensitive), an empty entry (NULL or zero length) keeps it positional ($1 = element - * 0). Pass NULL for all-positional binding. Named and positional parameters cannot be mixed within one statement. - * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of - * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. - * @param parameter_values Optional. An array of parameter_count value handles. Each binds by name when parameter_names - * supplies one, otherwise positionally ($1 = element 0). Borrowed (copied in). Pass NULL for an unparameterized - * statement. - * @param parameter_count The number of parameters in parameter_names and parameter_values. Pass 0 for an - * unparameterized statement. - * @param out_result Receives the new result handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the callback of. + * @param callback The "to string" callback to set. + * @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_statement_execute( - duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, - const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, - duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_to_string_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_to_string_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a result handle. - * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. Frees the memory the result owns and releases - * the connection for its next query. Safe at any point in the stream's life. Destroying a result before its statement - * ended (drained, or stepped to FINISHED) aborts the statement. On autocommit, its writes are rolled back. Inside a - * transaction, a statement that may write invalidates the transaction, and a read-only statement just stops. Chunks - * already fetched are caller-owned and stay valid. On success the slot is set to nullptr. + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param result The result to destroy. + * @param info The to string info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_result_destroy(duckdb_v2_result_handle *result); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_get_user_data( + duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Runs one bounded unit of query execution and returns without blocking. - * - * The streaming primitive: a step does a bounded amount of execution work, mostly without blocking, and returns control - * to the caller, so an event loop stays responsive and can interleave other work between steps. The conveniences — - * result_wait, result_fetch_chunk, result_drain — block, and are for synchronous callers. out_status reports the - * outcome: + * Retrieves the bind data the function's bind callback set for the bound call being described. * - * - CHUNK: *out_chunk receives a caller-owned chunk (destroy via data_chunk_destroy). Written only for this status; - * nullptr otherwise. - * - WAITING: no chunk yet, but work was done. Transient: keep stepping and it resolves to CHUNK, FINISHED, CANCELLED, - * or an error. Block in result_wait rather than busy-stepping. - * - FINISHED: stream exhausted. Sticky. - * - CANCELLED: query interrupted via connection_interrupt. Sticky. Cancellation is a status here, not an error; - * result_fetch_chunk, which has no status out-param, reports it as ERROR_RUNTIME_INTERRUPT. + * history: + * - unstable: v2.0.0 * - * Execution errors come back as the return code plus err, never as a status; out_status is then unspecified and - * *out_chunk is nullptr. Errors are sticky, so later steps report the same code. + * @param info The to string info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_table_function_to_string_get_bind_data( + duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Reports a key-value pair the query plan shows for the scan, e.g. `File` and the path of the file it reads. The plan + * shows the pairs in the order they were first reported; setting a key again replaces its value in place. Fails with + * `ERROR_INPUT_INVALID` when the key is empty. * * history: * - unstable: v2.0.0 * - * @param result The result to step. - * @param out_chunk Receives an owned chunk if *out_status is CHUNK; set to nullptr otherwise. - * @param out_status Receives the step status. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The to string info handle. + * @param key The key. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated. + * @param value The value. Borrowed and copied. May span several lines. + * @param value_length The length of `value` in bytes. `value` need not be null-terminated and may be NULL only when + * this is 0. + * @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_result_step(duckdb_v2_result_handle result, - duckdb_v2_data_chunk_handle *out_chunk, - DUCKDB_V2_RESULT_STEP_STATUS *out_status, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_set(duckdb_v2_table_function_to_string_info_handle info, + const char *key, idx_t key_length, + const char *value, idx_t value_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Blocks until the next chunk is available and returns it. - * - * A convenience over result_step: blocks until a chunk is produced or the stream ends. On success *out_chunk receives a - * caller-owned chunk (destroy via data_chunk_destroy), or nullptr at end-of-stream. End-of-stream is sticky, so later - * calls keep succeeding with *out_chunk set to nullptr. + * Creates a new multi-file function through a factory. * - * An interrupted query returns ERROR_RUNTIME_INTERRUPT — the same event result_step reports as status CANCELLED, - * carried on the error channel because this function has no status out-param. + * The function starts out empty: give it a name with `duckdb_v2_multi_file_function_set_name()` and the single-file + * function it wraps with `duckdb_v2_multi_file_function_set_single_file_function()`, then make it available with + * `duckdb_v2_connection_register_multi_file_function()` or `duckdb_v2_extension_register_multi_file_function()`. The + * caller owns the returned handle and must destroy it with `duckdb_v2_multi_file_function_destroy()`, also after + * registration. * - * On failure *out_chunk is set to nullptr. Errors are sticky, so later calls report the same code. + * The multi-file function can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param result The result to fetch from. - * @param out_chunk Receives an owned chunk, or nullptr at end-of-stream. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param factory The factory to create the multi-file function through. + * @param function On success, receives the newly created multi-file function. Owned by the caller. + * @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_result_fetch_chunk(duckdb_v2_result_handle result, - duckdb_v2_data_chunk_handle *out_chunk, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_multi_file_function_handle *function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Blocks until result_step can make progress. + * Sets the name of the multi-file function, as SQL will call it. * - * A convenience over result_step: blocks until a step is worth issuing again, that is, until a unit of execution work - * can run on the calling thread. Never produces or consumes chunks. Waiting on a terminal result — FINISHED, CANCELLED, - * or a sticky error — returns immediately; it is a no-op, never an error. + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param result The result to wait on. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this + * is 0. + * @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_result_wait(duckdb_v2_result_handle result, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_name(duckdb_v2_multi_file_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Renders the result as a box table, consuming it. + * Sets the name of the table function that reads a single file, which the multi-file function wraps. * - * Drains the result into a column data collection and renders it with the same renderer the DuckDB CLI uses, so every - * client displays results identically without reimplementing table formatting. The result is consumed by transfer: the - * slot is set to NULL on success and on failure alike. A partially consumed result is accepted, and the remainder is - * what gets rendered. + * The single-file function must be registered before the multi-file function is, and must take the file to read as its + * only positional parameter, of type ANY. It is bound once for every file that is read, and receives the file the way a + * multi-file function takes one: as the VARCHAR path of the file when there is nothing more to know about it, and + * otherwise as a STRUCT holding the path in its `filename` field and the options to open the file with in its other + * fields - e.g. the size of the file, as a file system reported it while globbing, or the options a caller passed along + * with the file (`read_x([{'filename': 'f.x', 'file_size': 42}])`). Opening the file with those options, set with + * `duckdb_v2_file_open_options_set_value()`, lets the file system skip work it would otherwise repeat, such as asking a + * remote store for the size of the file. A single-file function that takes a VARCHAR parameter instead is still + * accepted, and only receives the path. Every named parameter the single-file function declares is also a named + * parameter of the multi-file function, forwarded to it as given. Everything that involves several files - globbing, + * lists of files, hive partitioning, the `filename` column, `union_by_name` and the like - is provided by the + * multi-file function on top of it. The name is borrowed and copied. A single-file function must be set before + * registration. * - * The whole remaining result materializes in memory before rendering. max_rows bounds what is DISPLAYED, not what is - * read, so with limit 0 the footer's row count is exact. A caller who cannot afford full materialization should bound - * the query itself (e.g. LIMIT n) and pass n as limit; the footer then renders "? rows" whenever the result fills that - * bound, since the true total is unknown at that point. + * history: + * - unstable: v2.0.0 * - * Zero selects the renderer default for each sizing knob: max_rows 20, max_width the probed terminal width or 80 when - * that is unavailable, max_col_width 20. An empty null_value renders NULL cells as the default "NULL" text. + * @param function The function to set the single-file function of. + * @param name The name of the registered single-file table function. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this + * is 0. + * @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_multi_file_function_set_single_file_function(duckdb_v2_multi_file_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets how the files the function reads are referred to in messages, e.g. "Avro" or "JSON". * - * The rendered text goes to sink rather than being returned: a box can be large, and this way nothing allocates a - * buffer the caller has to free. The sink is called exactly once with the whole box, so its view carries the full - * length — write it straight to a stream, or copy it into your own string. sink must not be NULL. + * Optional: without it, the files are referred to by the name of the multi-file function. The name is borrowed and + * copied. * * history: * - unstable: v2.0.0 * - * @param result The result to render; consumed and set to NULL. Left intact only when the call rejects null arguments. - * @param max_rows Maximum rows displayed; 0 selects the renderer default (20). - * @param max_width Maximum total width in characters; 0 selects the renderer default. - * @param max_col_width Maximum width of one column; 0 selects the renderer default (20). - * @param null_value Text rendered for NULL cells; empty selects "NULL". - * @param null_value_length The length of `null_value` in bytes. `null_value` need not be null-terminated and may be + * @param function The function to set the reader type of. + * @param reader_type The reader type. Borrowed and copied. + * @param reader_type_length The length of `reader_type` in bytes. `reader_type` need not be null-terminated and may be * NULL only when this is 0. - * @param render_mode 0 renders rows (records down the page); 1 renders columns; other values are rejected with - * INVALID_INPUT. - * @param limit The row limit the caller applied to the query before rendering; 0 means none. When the materialized - * result holds exactly this many rows the true total is unknown, so the footer renders "? rows" instead of an exact - * count. - * @param sink Receives the whole rendered box in a single call. Borrowed for the duration of that call; see text_sink - * for the full contract. - * @param user_data Opaque pointer passed through to sink untouched. May be NULL. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @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_result_render_box(duckdb_v2_result_handle *result, idx_t max_rows, - idx_t max_width, idx_t max_col_width, const char *null_value, - idx_t null_value_length, idx_t render_mode, idx_t limit, - duckdb_v2_text_sink_fn sink, void *user_data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_multi_file_function_set_reader_type(duckdb_v2_multi_file_function_handle function, const char *reader_type, + idx_t reader_type_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Runs the result to completion and reports the changed-row count. - * - * A convenience over result_step: blocks until the stream is fully consumed, so every side effect is applied. Rows of a - * row-producing result are discarded. For a CHANGED_ROWS result *out_rows_changed receives the affected row count; for - * every other result type, and for a stream whose Count chunk was already consumed, it receives 0. + * Sets the file extension of the files the function reads, e.g. "avro". * - * The result type (result_get_result_type) is prepare-time metadata, so a caller can choose between consuming rows and - * draining without inspecting the SQL. Draining an already FINISHED result succeeds. Cancellation surfaces as - * ERROR_RUNTIME_INTERRUPT; errors are sticky, and on failure *out_rows_changed is unspecified. + * Optional. With a file extension, a path that names a directory rather than a file reads the files with that extension + * inside it. Without one, the paths passed to the function must match at least one file. The extension is given without + * a leading dot, and is borrowed and copied. * * history: * - unstable: v2.0.0 - * - * @param result The result to drain. - * @param out_rows_changed Receives the affected row count for CHANGED_ROWS results, 0 otherwise. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * + * @param function The function to set the file extension of. + * @param extension The file extension, without a leading dot. Borrowed and copied. + * @param extension_length The length of `extension` in bytes. `extension` need not be null-terminated and may be NULL + * only when this is 0. + * @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_result_drain(duckdb_v2_result_handle result, idx_t *out_rows_changed, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_multi_file_function_set_file_extension(duckdb_v2_multi_file_function_handle function, const char *extension, + idx_t extension_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the shape of the result: query, changed rows, or nothing. - * - * QUERY_RESULT for statements that produce rows (SELECT, RETURNING, EXPLAIN), CHANGED_ROWS for an INSERT, UPDATE, or - * DELETE without RETURNING, NOTHING for DDL and other statements with no row output. + * Registers the multi-file function, making it available for use in SQL queries. * - * Prepare-time metadata: available from statement_execute on, except for a statement that expands into a group, where - * it fails with ERROR_INPUT_METADATA_DEFERRED until stepping has bound the row-producing statement, or the group ended - * without one. + * The function is registered on the connection's database, visible to every connection, in the connection's + * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and + * a rollback undoes it. It can then be called with the path of a single file, a glob pattern, or a list of either, and + * accepts the options every multi-file function accepts (e.g. `filename`, `hive_partitioning`, `union_by_name`) next to + * the named parameters of the single-file function. Registration requires a name and a single-file function, and fails + * when no table function by that name is registered or it does not take the path of the file to read as its only + * positional parameter (see `duckdb_v2_multi_file_function_set_single_file_function()`). The multi-file function must + * have been created through a factory of the same database. The caller still owns the handle after registration and + * must destroy it with `duckdb_v2_multi_file_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param result The result. - * @param out_type Receives the result shape. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param conn The connection to register on. + * @param function The multi-file function to register. + * @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_result_get_result_type(duckdb_v2_result_handle result, - DUCKDB_V2_RESULT_TYPE *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_multi_file_function( + duckdb_v2_connection_handle conn, duckdb_v2_multi_file_function_handle function, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the SQL statement type that produced the result. + * Registers the multi-file function, making it available for use in SQL queries. * - * Prepare-time metadata: available from statement_execute on. A statement that expands into a group reports its type as - * written: MULTI, or PRAGMA for a pragma such as IMPORT DATABASE. + * The function is registered on the loading extension's database and attributed to the extension. Use this from the + * extension's load callback. It can then be called with the path of a single file, a glob pattern, or a list of either, + * and accepts the options every multi-file function accepts (e.g. `filename`, `hive_partitioning`, `union_by_name`) + * next to the named parameters of the single-file function. Registration requires a name and a single-file function, + * and fails when no table function by that name is registered or it does not take the path of the file to read as its + * only positional parameter (see `duckdb_v2_multi_file_function_set_single_file_function()`). The multi-file function + * must have been created through a factory of the same database. The caller still owns the handle after registration + * and must destroy it with `duckdb_v2_multi_file_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param result The result. - * @param out_type Receives the statement type. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param extension The loading extension. + * @param function The multi-file function to register. + * @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_result_get_statement_type(duckdb_v2_result_handle result, - DUCKDB_V2_STATEMENT_TYPE *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_multi_file_function( + duckdb_v2_extension_handle extension, duckdb_v2_multi_file_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the result's output schema as a single schema handle. - * - * Builds an owned schema of the result's column names and types into *out_schema; destroy it via schema_destroy. - * Prepare-time metadata, available before the first step, or for an expanding statement once stepping has bound the - * row-producing statement (before that it fails with ERROR_INPUT_METADATA_DEFERRED). Never empty: a non-SELECT reports - * a single status column, either a BIGINT changed-rows count or a BOOLEAN success. - * - * This schema is the authoritative source for the column types of the chunks the result produces; vectors do not carry - * their own type. + * Destroys the multi-file function, releasing its resources. * - * *out_schema is set to NULL on failure. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param result The result. - * @param out_schema Receives the owned output schema. Destroy via schema_destroy. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_get_schema(duckdb_v2_result_handle result, - duckdb_v2_schema_handle *out_schema, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_destroy(duckdb_v2_multi_file_function_handle *function); #endif -/* --- Struct definitions for query_result --- */ +/* --- Struct definitions for table --- */ /* ============================================================================ - * MODULE: table + * MODULE: value * ============================================================================ */ -/* --- Enums for table --- */ - -/*! - * Whether a table function's scan is partitioned by a given set of columns, and how. Reported by - * `duckdb_v2_table_function_set_partitioning_callback()` via - * `duckdb_v2_table_function_partitioning_set_partition_info()`. - */ -typedef enum DUCKDB_V2_TABLE_PARTITION_INFO { - //! The scan is not known to be partitioned by the requested columns. - DUCKDB_V2_TABLE_PARTITION_INFO_NOT_PARTITIONED = 0, - - //! Each partition the scan produces carries exactly one distinct value for the requested columns. - DUCKDB_V2_TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS = 1, - - //! The partitions the scan produces overlap only at their boundaries. - DUCKDB_V2_TABLE_PARTITION_INFO_OVERLAPPING_PARTITIONS = 2, - - //! The partitions the scan produces are disjoint ranges. - DUCKDB_V2_TABLE_PARTITION_INFO_DISJOINT_PARTITIONS = 3, - DUCKDB_V2_TABLE_PARTITION_INFO_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_TABLE_PARTITION_INFO; - -/*! - * A column a table function can produce next to the columns it declares in bind. A query asks for it by name, but it is - * not part of the function's result columns. Declared with `duckdb_v2_table_function_add_virtual_column()`. In the - * column lists of the scan (e.g. `duckdb_v2_table_function_exec_get_column_index()`), a virtual column is identified by - * 2^63 plus its value in this enum. - */ -typedef enum DUCKDB_V2_TABLE_VIRTUAL_COLUMN { - /*! - * `file_row_number`, a BIGINT holding the position of the row within the file it was read from, counting from 0. A - * function that reads a single file produces it when it is wrapped in a multi-file function (see - * `duckdb_v2_multi_file_function_create()`), which is where the name of the file comes from. - */ - DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER = 0, - DUCKDB_V2_TABLE_VIRTUAL_COLUMN_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_TABLE_VIRTUAL_COLUMN; - -/* --- Struct forward declarations for table --- */ - -/* --- Types for table --- */ - -/*! - * An owned opaque handle to a custom table function being built. Created with `duckdb_v2_table_function_create()`, - * configured with the setter functions (e.g. `duckdb_v2_table_function_set_name()`, - * `duckdb_v2_table_function_set_exec_callback()`, etc.) and the signature obtained via - * `duckdb_v2_table_function_get_signature()`, made available with `duckdb_v2_connection_register_table_function()` or - * `duckdb_v2_extension_register_table_function()`, and destroyed with `duckdb_v2_table_function_destroy()`. - */ -typedef struct _duckdb_v2_table_function { - void *internal_ptr; -} * duckdb_v2_table_function_handle; +/* --- Enums for value --- */ -/*! - * A borrowed opaque handle to the result of a table function's "bind" phase. The "bind" callback receives this handle - * next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments, the user data and the bind - * data. It must use this handle to declare the columns the function returns, and can use it to hint at the number of - * rows the scan will produce. - */ -typedef struct _duckdb_v2_table_function_bind_info { - void *internal_ptr; -} * duckdb_v2_table_function_bind_info_handle; +/* --- Struct forward declarations for value --- */ -/*! - * A borrowed opaque handle to the arguments supplied to a table function during the global state initialization "init - * global" phase. The "init global" callback receives this handle and can use it to e.g. set up the state shared by - * every thread scanning the function, and to declare how many threads may scan it. - */ -typedef struct _duckdb_v2_table_function_init_global_info { - void *internal_ptr; -} * duckdb_v2_table_function_init_global_info_handle; +/* --- Types for value --- */ -/*! - * A borrowed opaque handle to the arguments supplied to a table function during the local state initialization "init - * local" phase. The "init local" callback receives this handle and can use it to e.g. set up worker-local state, - * typically by claiming work from the shared global state. - */ -typedef struct _duckdb_v2_table_function_init_local_info { - void *internal_ptr; -} * duckdb_v2_table_function_init_local_info_handle; +/* --- Constants for value --- */ -/*! - * A borrowed opaque handle to the arguments supplied to a table function during the execution "exec" phase. The "exec" - * callback receives this handle and can use it to e.g. access the global and local state and write the next batch of - * rows to the output chunk. - */ -typedef struct _duckdb_v2_table_function_exec_info { - void *internal_ptr; -} * duckdb_v2_table_function_exec_info_handle; +/* --- Function pointer typedefs for value --- */ -/*! - * A borrowed opaque handle to the arguments supplied to a table function during the "progress" phase. The "progress" - * callback receives this handle and can use it to report how far the scan has advanced. - */ -typedef struct _duckdb_v2_table_function_progress_info { - void *internal_ptr; -} * duckdb_v2_table_function_progress_info_handle; +/* --- Functions for value --- */ +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to the arguments supplied to a table function during the "filter pushdown" phase of query - * optimization. The "filter pushdown" callback receives this handle and can use it to inspect the filter predicates the - * query applies to the function's rows, and to accept the ones it will apply itself. + * Destroys a value handle. + * + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. On success the slot is set to nullptr. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to destroy. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_table_function_filter_pushdown_info { - void *internal_ptr; -} * duckdb_v2_table_function_filter_pushdown_info_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_destroy(duckdb_v2_value_handle *value); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to the arguments supplied to a table function during the "partition data" phase. The engine - * invokes the callback on the worker thread that just produced a batch of rows, once per batch, only when a downstream - * operator needs to know the batch's ordering position, the values of a set of partitioning columns, or both; the - * handle reports which of those were actually requested and receives the answer. + * Returns the value as a BOOLEAN. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload as a bool. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_table_function_partition_data_info { - void *internal_ptr; -} * duckdb_v2_table_function_partition_data_info_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_bool(duckdb_v2_value_handle value, bool *out, + duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to the arguments supplied to a table function during the "stats" phase of query - * optimization. The engine invokes the callback once per column the query reads, and the callback can use the handle to - * find out which column is asked about and to report what it knows about the column's values (its minimum and maximum, - * whether it holds NULLs, ...) by narrowing the statistics of that column. + * Returns the value as a UTINYINT. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload as a uint8_t. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_table_function_stats_info { - void *internal_ptr; -} * duckdb_v2_table_function_stats_info_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_utinyint(duckdb_v2_value_handle value, uint8_t *out, + duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to the arguments supplied to a table function during the "partitioning" phase of query - * optimization. The engine invokes the callback once per candidate `GROUP BY` column set, before execution starts, to - * decide whether the scan can feed a partitioned aggregate directly instead of hashing. + * Returns the value as a USMALLINT. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload as a uint16_t. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_table_function_partitioning_info { - void *internal_ptr; -} * duckdb_v2_table_function_partitioning_info_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_usmallint(duckdb_v2_value_handle value, uint16_t *out, + duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to the arguments supplied to a table function when a scanning thread claims its next batch - * of work. The "claim batch" callback receives this handle and can use it to claim the next part of the scan from the - * shared global state for the thread's local state, and to report whether it claimed one. + * Returns the value as a UINTEGER. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload as a uint32_t. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_table_function_claim_batch_info { - void *internal_ptr; -} * duckdb_v2_table_function_claim_batch_info_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uint(duckdb_v2_value_handle value, uint32_t *out, + duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to the arguments supplied to a table function when the engine collects the metrics of a - * scan. The "metrics" callback receives this handle and can use it to report the operator metrics of the scan, e.g. how - * many row groups it read. + * Returns the value as a UBIGINT. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload as a uint64_t. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_table_function_metrics_info { - void *internal_ptr; -} * duckdb_v2_table_function_metrics_info_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_ubigint(duckdb_v2_value_handle value, uint64_t *out, + duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to the arguments supplied to a table function when the engine asks it to describe a bound - * call. The "get bind info" callback receives this handle, and can use it to describe the call in more detail than its - * columns: with identifiers of its columns (e.g. field ids), and with options - key-value facts about what the call - * reads. + * Returns the value as a UHUGEINT. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload as a uint128_t. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_table_function_get_bind_info_info { - void *internal_ptr; -} * duckdb_v2_table_function_get_bind_info_info_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uhugeint(duckdb_v2_value_handle value, duckdb_v2_uhugeint_t *out, + duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A borrowed opaque handle to the arguments supplied to a table function when the engine describes a bound call of it - * in a query plan, e.g. for `EXPLAIN`. The "to string" callback receives this handle and can use it to report the - * key-value pairs the plan shows for the scan. + * Returns the value as a TINYINT. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload as an int8_t. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_table_function_to_string_info { - void *internal_ptr; -} * duckdb_v2_table_function_to_string_info_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_tinyint(duckdb_v2_value_handle value, int8_t *out, + duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * An owned opaque handle to a multi-file table function being built. A multi-file function wraps an already registered - * table function that reads a single file, and adds everything that is needed to read many files at once on top of it: - * globbing, lists of files, hive partitioning, the `filename` column, `union_by_name` and the like. Created with - * `duckdb_v2_multi_file_function_create()`, configured with the setter functions (e.g. - * `duckdb_v2_multi_file_function_set_name()`, `duckdb_v2_multi_file_function_set_single_file_function()`), made - * available with `duckdb_v2_connection_register_multi_file_function()` or - * `duckdb_v2_extension_register_multi_file_function()`, and destroyed with `duckdb_v2_multi_file_function_destroy()`. + * Returns the value as a SMALLINT. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload as an int16_t. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_multi_file_function { - void *internal_ptr; -} * duckdb_v2_multi_file_function_handle; - -/* --- Constants for table --- */ - -/* --- Function pointer typedefs for table --- */ - -typedef void (*duckdb_v2_table_function_bind_callback_fn)(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); - -typedef void (*duckdb_v2_table_function_init_global_callback_fn)(duckdb_v2_table_function_init_global_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_init_local_callback_fn)(duckdb_v2_table_function_init_local_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_exec_callback_fn)(duckdb_v2_table_function_exec_info_handle info, - duckdb_v2_context_handle context, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_smallint(duckdb_v2_value_handle value, int16_t *out, duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_progress_callback_fn)(duckdb_v2_table_function_progress_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_metrics_callback_fn)(duckdb_v2_table_function_metrics_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_filter_pushdown_callback_fn)( - duckdb_v2_table_function_filter_pushdown_info_handle info, duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_partition_data_callback_fn)( - duckdb_v2_table_function_partition_data_info_handle info, duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_partitioning_callback_fn)( - duckdb_v2_table_function_partitioning_info_handle info, duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_claim_batch_callback_fn)(duckdb_v2_table_function_claim_batch_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_get_bind_info_callback_fn)( - duckdb_v2_table_function_get_bind_info_info_handle info, duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_stats_callback_fn)(duckdb_v2_table_function_stats_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_to_string_callback_fn)(duckdb_v2_table_function_to_string_info_handle info, - duckdb_v2_error_info_handle *err); - -/* --- Functions for table --- */ +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new table function through a factory. + * Returns the value as an INTEGER. * - * The function starts out empty: configure it with the setter functions (e.g. `duckdb_v2_table_function_set_name()`, - * `duckdb_v2_table_function_set_exec_callback()`, etc.) and the signature obtained via - * `duckdb_v2_table_function_get_signature()`, then make it available with - * `duckdb_v2_connection_register_table_function()` or `duckdb_v2_extension_register_table_function()`. The caller owns - * the returned handle and must destroy it with `duckdb_v2_table_function_destroy()`, also after registration. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * - * The table function can only be registered on the database the factory belongs to. + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload as an int32_t. + * @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_int(duckdb_v2_value_handle value, int32_t *out, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the value as a BIGINT. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the table function through. - * @param function On success, receives the newly created table function. Owned by the caller. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload as an int64_t. + * @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_table_function_create(duckdb_v2_factory_handle factory, - duckdb_v2_table_function_handle *function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_bigint(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the table function. + * Returns the value as a HUGEINT. * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload as an int128_t. + * @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_table_function_set_name(duckdb_v2_table_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_hugeint(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the documentation of the function so it can be filled in. + * Returns the value as a VARCHAR. * - * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with - * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified - * in place, describes this overload only, and is registered with the function. Optional. + * The string is borrowed from the value and stays valid until the value is destroyed. That borrow is why this getter + * does not convert: a converted copy would not outlive the call. A value of any other type id, and a NULL value, return + * ERROR_INPUT_INVALID. * * history: * - unstable: v2.0.0 * - * @param function The function to get the documentation of. - * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload as a UTF-8 string. The returned string is borrowed and valid until the value handle + * is destroyed. + * @param out_length Receives the length of `*out` in bytes. `*out` is not guaranteed to be null-terminated. + * @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_table_function_get_docs(duckdb_v2_table_function_handle function, - duckdb_v2_function_docs_handle *docs, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_varchar(duckdb_v2_value_handle value, const char **out, + idx_t *out_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the function's signature so it can be configured. + * Returns the value as a byte string: a BLOB, or the storage bytes of a BIT, a BIGNUM, or a DECIMAL wider than 38 + * digits (the BIGNUM storage of its unscaled value, for bignum_decode). * - * Add parameters with `duckdb_v2_function_signature_add_parameter()`. The signature is modified in place. A table - * function declares the columns it returns from its bind callback instead of through a return type, so registration - * rejects a signature whose return type was set with `duckdb_v2_function_signature_set_return_type()`. + * The string is borrowed from the value and stays valid until the value is destroyed. That borrow is why this getter + * does not convert: a converted copy would not outlive the call. A value of any other type id, and a NULL value, return + * ERROR_INPUT_INVALID. * * history: * - unstable: v2.0.0 * - * @param function The function to get the signature of. - * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload as a byte string. The returned string is borrowed and valid until the value handle is + * destroyed. + * @param out_length Receives the length of `*out` in bytes. `*out` is not guaranteed to be null-terminated. + * @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_table_function_get_signature(duckdb_v2_table_function_handle function, - duckdb_v2_function_signature_handle *sig, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_blob(duckdb_v2_value_handle value, const char **out, idx_t *out_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the table function. + * Returns the value as a FLOAT. * - * Associates an opaque pointer with the function, retrievable from the callbacks via - * `duckdb_v2_function_bind_get_user_data()`, `duckdb_v2_table_function_init_global_get_user_data()`, - * `duckdb_v2_table_function_exec_get_user_data()` and their counterparts on the other phases. The opaque handle bundles - * the pointer with an optional destructor, invoked when the data is no longer needed. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload as a float. + * @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_table_function_set_user_data(duckdb_v2_table_function_handle function, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_float(duckdb_v2_value_handle value, float *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the bind callback of the table function. + * Returns the value as a DOUBLE. * - * The bind callback is invoked during query planning for each call site of the function. It must declare the columns - * the function returns via `duckdb_v2_table_function_bind_add_result_column()`. Through its - * `duckdb_v2_function_bind_info_handle` it can also inspect the constant argument values and set "bind data" that is - * shared with all later callbacks. A bind callback must be set before registration. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the bind callback of. - * @param callback The bind callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload as a double. + * @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_table_function_set_bind_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_bind_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_double(duckdb_v2_value_handle value, double *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional global init callback of the table function. + * Returns the value as a DATE. * - * The global init callback is invoked once per scan, at the start of execution. It can set "global state" shared by - * every thread scanning the function, and declare how many threads may scan it in parallel via - * `duckdb_v2_table_function_init_global_set_max_threads()`. + * The payload is days since 1970-01-01, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the global init callback of. - * @param callback The global init callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_set_init_global_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_init_global_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_date(duckdb_v2_value_handle value, int32_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional local init callback of the table function. + * Returns the value as a TIME. * - * The local init callback is invoked once per thread that will scan the function. It can set worker-local "local - * state", retrievable from the exec callback, typically derived from the shared global state. + * The payload is microseconds since midnight, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the local init callback of. - * @param callback The local init callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_set_init_local_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_init_local_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_time(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the exec callback of the table function. + * Returns the value as a TIME_NS. + * + * The payload is nanoseconds since midnight, the same unit a vector of this type exposes. * - * The exec callback implements the function's logic: it is invoked repeatedly during query execution and writes the - * next batch of rows to the output chunk, until it produces an empty batch to signal the end of the scan. An exec - * callback must be set before registration. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the exec callback of. - * @param callback The exec callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_set_exec_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_time_ns(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional progress callback of the table function. + * Returns the value as a TIME_TZ. * - * The progress callback is invoked on demand during execution to report how far the scan has advanced, which the engine - * surfaces as the query's progress. It is invoked concurrently with the exec callback, so it must read the global state - * in a thread-safe way. + * The payload packs the time of day and the UTC offset into one integer, in the committed layout: micros in the high 40 + * bits, a biased offset in the low 24. The same form a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the progress callback of. - * @param callback The progress callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_set_progress_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_progress_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_time_tz(duckdb_v2_value_handle value, uint64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets whether the table function supports projection pushdown. Defaults to false. + * Returns the value as a TIMESTAMP. * - * With projection pushdown, the engine asks the function for only the columns a query actually uses: the exec - * callback's output chunk holds one vector per requested column rather than one per column declared in bind, and the - * global init, local init and exec callbacks can look up which declared column each vector stands for via e.g. - * `duckdb_v2_table_function_exec_get_column_index()`. Without it the output chunk always holds every declared column, - * and the engine drops the unused ones itself. + * The payload is microseconds since 1970-01-01, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to configure. - * @param enable Whether the function supports projection pushdown. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_set_projection_pushdown(duckdb_v2_table_function_handle function, - bool enable, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Declares that the table function can produce the given virtual column. + * Returns the value as a TIMESTAMP_SEC. * - * A virtual column is not one of the columns declared in bind: the query asks for it by name, and the function only - * produces it when it is asked for. It then takes up a vector of the exec callback's output chunk, like any other - * column the scan produces. This requires projection pushdown (see - * `duckdb_v2_table_function_set_projection_pushdown()`), which is what lets the engine ask for it. The global init, - * local init and exec callbacks recognize the vector by its column index, which is 2^63 plus the value of the - * `DUCKDB_V2_TABLE_VIRTUAL_COLUMN` (see e.g. `duckdb_v2_table_function_exec_get_column_index()`). + * The payload is seconds since 1970-01-01, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to configure. - * @param column The virtual column the function can produce. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_add_virtual_column(duckdb_v2_table_function_handle function, - DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_sec(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional metrics callback of the table function. + * Returns the value as a TIMESTAMP_MS. * - * The metrics callback is invoked when the engine collects the metrics of the scan, e.g. when profiling is enabled, and - * can report what the scan did through its `duckdb_v2_table_function_metrics_info_handle`. + * The payload is milliseconds since 1970-01-01, the same unit a vector of this type exposes. * - * DuckDB does not synchronize the callback with the scan: each thread that scanned invokes it when it finishes, so it - * can run while other threads still scan and while other threads invoke it. The global state it reads is shared with - * those threads, so the function must synchronize what the callback reads from it, e.g. by keeping counters in atomics - * and reading them with an exchange, so that each amount is reported once. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the metrics callback of. - * @param callback The metrics callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_set_metrics_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_metrics_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_ms(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional filter pushdown callback of the table function. + * Returns the value as a TIMESTAMP_NS. * - * The filter pushdown callback is invoked while the query is optimized, after the bind callback and before any init - * callback, with the filter predicates the query applies to the function's rows. Each predicate is a bound expression - * the callback can inspect with the `expression` functions; the callback accepts the predicates it will apply itself - * via `duckdb_v2_table_function_filter_pushdown_accept()`, typically after recording what they select in the bind data. - * The engine then stops applying the accepted predicates and keeps applying the rest above the scan, so accepting a - * predicate is a promise to filter the rows exactly as it would have. The optimizer may invoke the callback more than - * once for the same query, each time with the predicates not yet accepted; it is not invoked when there are none. + * The payload is nanoseconds since 1970-01-01, the same unit a vector of this type exposes. * - * A function that also has projection pushdown (see `duckdb_v2_table_function_set_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, in the same form, with the column references resolved by - * `duckdb_v2_table_function_filter_pushdown_get_column_index()` as at optimization time. This is how the callback of a - * function wrapped in a multi-file function sees the predicates, which the optimizer only offers to the wrapper. 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 but does not have to understand them, and accepting one has no effect. The scan keeps the - * columns the predicates are applied to. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the filter pushdown callback of. - * @param callback The filter pushdown callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_set_filter_pushdown_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_filter_pushdown_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_ns(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional "partition data" callback of the table function. + * Returns the value as a TIMESTAMP_TZ. + * + * The payload is microseconds since 1970-01-01, in UTC, the same unit a vector of this type exposes. * - * The callback reports, for the batch the exec callback just produced, an ordering batch index, the values of a set of - * partitioning columns, or both, depending on what a downstream operator requires; it runs on the worker thread that - * produced the batch. Set `duckdb_v2_table_function_set_partitioning_callback()` too when the function can answer - * partitioning-column requests, since the engine only asks a scan for those when that callback reports - * `TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS`. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the partition data callback of. - * @param callback The partition data callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_set_partition_data_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_partition_data_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_tz(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional "partitioning" callback of the table function. + * Returns the value as a TIMESTAMP_TZ_NS. * - * The callback tells the query optimizer, for a candidate `GROUP BY` column set, whether every partition the scan - * produces carries exactly one distinct value for those columns; only `TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS` - * unlocks the partitioned aggregate optimization; any other result, or leaving this callback unset, keeps the regular - * hash aggregate. It runs on the planning thread, before execution starts, and must be deterministic for a given column - * set since it may be called on a plan the optimizer later discards. Registration fails unless - * `duckdb_v2_table_function_set_partition_data_callback()` is set too, since the engine asks that callback for the - * partitioning column values once this one claims single-value partitions. + * The payload is nanoseconds since 1970-01-01, in UTC, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the partitioning callback of. - * @param callback The partitioning callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_set_partitioning_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_partitioning_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_tz_ns(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional stats callback of the table function. + * Returns the value as an INTERVAL. * - * The stats callback is invoked during query optimization once for each declared column the query reads, when the - * engine wants to know about the column's values without reading them - e.g. to prune a scan whose filter no value can - * satisfy, to answer `min()` / `max()` from the statistics, or to estimate the selectivity of a filter. Through its - * `duckdb_v2_table_function_stats_info_handle` the callback narrows the statistics of that column (see - * `duckdb_v2_table_function_stats_get_result_stats()`): its minimum and maximum, whether it holds NULLs, the statistics - * of the children of a nested column, ... Leaving the statistics unchanged tells the engine nothing about the column. - * The statistics must hold for every row the call produces: a bound that excludes a value the scan then produces leads - * to wrong results. A function without a stats callback gives the engine no statistics for its columns. The callback is - * only asked about whole declared columns, never about virtual columns or about fields extracted from a column. + * The payload is the (months, days, micros) triple, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param function The function to set the stats callback of. - * @param callback The stats callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload. + * @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_table_function_set_stats_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_stats_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_interval(duckdb_v2_value_handle value, duckdb_v2_interval_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Declares one of the columns the function returns. + * Returns the value as a UUID, in its internal 128-bit form. * - * Call this once per column, in order: the columns declared here are the columns of the table the function produces, - * and the vectors of the output chunk the exec callback fills follow the same order. At least one column must be - * declared. The type must be a fully defined concrete type; ANY is rejected, as a result column carries data. The name - * and type are borrowed and copied. + * The dual of value_create_uuid: the storage form a vector element holds, with the high bit flipped so the integer + * sorts, rather than the canonical byte order. A value of any other type id, and a NULL value, return + * ERROR_INPUT_INVALID. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param name The name of the column. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param type The type of the column. Borrowed and copied. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the internal 128-bit storage form. + * @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_table_function_bind_add_result_column( - duckdb_v2_table_function_bind_info_handle info, const char *name, idx_t name_length, - duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uuid(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the estimated number of rows the scan will produce. + * Returns the value as a DECIMAL: its backing integer plus the width and scale of its type. * - * The estimate is a hint for the optimizer, not a limit: producing a different number of rows is not an error. Without - * it, the optimizer falls back on its own defaults. + * The integer is the value scaled by 10^scale — the dual of value_create_decimal — widened to 128 bits from whatever + * 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, 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 * - * @param info The bind info handle. - * @param cardinality The estimated number of rows. - * @param is_exact Whether the estimate is exact, which also makes it an upper bound on the row count. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the backing integer, scaled by 10^scale. + * @param out_width Receives the total digit count of the value's type. + * @param out_scale Receives the digits after the decimal point. + * @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_table_function_bind_set_cardinality( - duckdb_v2_table_function_bind_info_handle info, idx_t cardinality, bool is_exact, duckdb_v2_error_info_handle *err); +DUCKDB_C_API 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); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the order guarantee of the rows this call of the function produces. Defaults to - * `ORDER_PRESERVATION_INSERTION_ORDER`. + * Unwraps the logical type carried by a TYPE value. * - * With `ORDER_PRESERVATION_NO_ORDER`, a scan that reports more than one thread via - * `duckdb_v2_table_function_init_global_set_max_threads()` runs in parallel into query results, INSERT and COPY without - * a `duckdb_v2_table_function_set_partition_data_callback()`, and the rows arrive in no particular order. With - * insertion order kept, those consumers need the partition data callback to run in parallel. Fails with - * `ERROR_INPUT_INVALID` when order is not one of the enum's declared values. + * Returns ERROR_INPUT_INVALID unless the value is a non-NULL TYPE value. The returned logical type is caller-owned and + * must be destroyed via logical_type_destroy. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param order The order guarantee of the produced rows. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out_type Receives the owned logical type. + * @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_table_function_bind_set_order_preservation( - duckdb_v2_table_function_bind_info_handle info, DUCKDB_V2_ORDER_PRESERVATION order, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_type(duckdb_v2_value_handle value, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Creates a NULL value of the given logical type. + * + * The logical type is borrowed and copied into the value, so the caller can destroy it independently. * * history: * - unstable: v2.0.0 * - * @param info The global init info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param type The borrowed logical type to attach to the NULL value. + * @param out_value Receives the new NULL 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_table_function_init_global_get_user_data( - duckdb_v2_table_function_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_null(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle type, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Creates a BOOLEAN value from a bool. + * + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The global init info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The bool to wrap. + * @param out_value Receives the new BOOLEAN 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_table_function_init_global_get_bind_data( - duckdb_v2_table_function_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bool(duckdb_v2_factory_handle factory, bool in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the function's "global state" from the global init callback. + * Creates a UTINYINT value from a uint8_t. * - * The global state lives for the duration of the scan and is retrievable from the local init, exec and progress - * callbacks. Every thread scanning the function shares it, so the function must synchronize its own access to it. The - * opaque handle bundles the pointer with an optional destructor, invoked when the scan is done with the state. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The global init info handle. - * @param data Opaque handle bundling the global state pointer plus an optional destructor. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The uint8_t to wrap. + * @param out_value Receives the new UTINYINT 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_table_function_init_global_set_global_state( - duckdb_v2_table_function_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_utinyint(duckdb_v2_factory_handle factory, uint8_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets how many threads may scan the function in parallel. + * Creates a USMALLINT value from a uint16_t. * - * Defaults to 1, a single-threaded scan. The engine creates at most this many local states, and therefore runs at most - * this many exec callbacks concurrently. It is an upper bound, not a request: the engine may use fewer threads. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The global init info handle. - * @param max_threads The maximum number of threads. Must be at least 1. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The uint16_t to wrap. + * @param out_value Receives the new USMALLINT 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_table_function_init_global_set_max_threads( - duckdb_v2_table_function_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_usmallint(duckdb_v2_factory_handle factory, uint16_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns the scan produces. + * Creates a UINTEGER value from a uint32_t. * - * With projection pushdown (see `duckdb_v2_table_function_set_projection_pushdown()`) this is the number of columns the - * query uses, which is the number of vectors in the exec callback's output chunk; without it, it is the number of - * columns declared in bind. Valid indices for `duckdb_v2_table_function_init_global_get_column_index()` are `0` up to - * (but excluding) this count. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The global init info handle. - * @param count Receives the number of columns the scan produces. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The uint32_t to wrap. + * @param out_value Receives the new UINTEGER 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_table_function_init_global_get_column_count( - duckdb_v2_table_function_init_global_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_uint(duckdb_v2_factory_handle factory, uint32_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns which declared column the scan's column at the given index stands for. + * Creates a UBIGINT value from a uint64_t. * - * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration - * order: the exec callback fills the output chunk's vector at `index` with that column's data. Without projection - * pushdown the mapping is the identity. Fails if the index is out of bounds. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The global init info handle. - * @param index The index of the column in the scan's output. - * @param column_index Receives the index of the declared column. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The uint64_t to wrap. + * @param out_value Receives the new UBIGINT 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_table_function_init_global_get_column_index( - duckdb_v2_table_function_init_global_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_ubigint(duckdb_v2_factory_handle factory, uint64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Creates a UHUGEINT value from a uint128_t. + * + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The local init info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The uint128_t to wrap. + * @param out_value Receives the new UHUGEINT 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_table_function_init_local_get_user_data( - duckdb_v2_table_function_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_uhugeint(duckdb_v2_factory_handle factory, + const duckdb_v2_uhugeint_t *in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Creates a TINYINT value from an int8_t. + * + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The local init info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The int8_t to wrap. + * @param out_value Receives the new TINYINT 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_table_function_init_local_get_bind_data( - duckdb_v2_table_function_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_tinyint(duckdb_v2_factory_handle factory, int8_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the global state set by the function's global init callback. + * Creates a SMALLINT value from an int16_t. * - * Shared with every other thread scanning the function; access to it must be synchronized by the function. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The local init info handle. - * @param data Receives the global state pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The int16_t to wrap. + * @param out_value Receives the new SMALLINT 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_table_function_init_local_get_global_state( - duckdb_v2_table_function_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_smallint(duckdb_v2_factory_handle factory, int16_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the function's worker-local "local state" from the local init callback. + * Creates an INTEGER value from an int32_t. * - * The local state is associated with the executing thread for the duration of the scan and retrievable from the exec - * callback via `duckdb_v2_table_function_exec_get_local_state()`. No other thread observes it, so it needs no - * synchronization. The opaque handle bundles the pointer with an optional destructor, invoked when the local state is - * no longer needed. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The local init info handle. - * @param data Opaque handle bundling the local state pointer plus an optional destructor. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The int32_t to wrap. + * @param out_value Receives the new INTEGER 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_table_function_init_local_set_local_state( - duckdb_v2_table_function_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_int(duckdb_v2_factory_handle factory, int32_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns the scan produces. + * Creates a BIGINT value from an int64_t. * - * With projection pushdown (see `duckdb_v2_table_function_set_projection_pushdown()`) this is the number of columns the - * query uses, which is the number of vectors in the exec callback's output chunk; without it, it is the number of - * columns declared in bind. Valid indices for `duckdb_v2_table_function_init_local_get_column_index()` are `0` up to - * (but excluding) this count. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The local init info handle. - * @param count Receives the number of columns the scan produces. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The int64_t to wrap. + * @param out_value Receives the new BIGINT 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_table_function_init_local_get_column_count( - duckdb_v2_table_function_init_local_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bigint(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns which declared column the scan's column at the given index stands for. - * - * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration - * order: the exec callback fills the output chunk's vector at `index` with that column's data. Without projection - * pushdown the mapping is the identity. Fails if the index is out of bounds. + * Creates a HUGEINT value from an int128_t. + * + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The local init info handle. - * @param index The index of the column in the scan's output. - * @param column_index Receives the index of the declared column. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The int128_t to wrap. + * @param out_value Receives the new HUGEINT 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_table_function_init_local_get_column_index(duckdb_v2_table_function_init_local_info_handle info, idx_t index, - idx_t *column_index, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_hugeint(duckdb_v2_factory_handle factory, + const duckdb_v2_hugeint_t *in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Creates a VARCHAR value from a UTF-8 string. + * + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The UTF-8 string to wrap. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. + * @param out_value Receives the new VARCHAR 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_table_function_exec_get_user_data(duckdb_v2_table_function_exec_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_varchar(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Creates a BLOB value from a byte string. + * + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The byte string to wrap. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. + * @param out_value Receives the new BLOB 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_table_function_exec_get_bind_data(duckdb_v2_table_function_exec_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_blob(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the global state set by the function's global init callback. + * Creates a FLOAT value from a float. * - * Shared with every other thread scanning the function; access to it must be synchronized by the function. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the global state pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The float to wrap. + * @param out_value Receives the new FLOAT 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_table_function_exec_get_global_state( - duckdb_v2_table_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_float(duckdb_v2_factory_handle factory, float in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the worker-local local state set by the function's local init callback. + * Creates a DOUBLE value from a double. + * + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the local state pointer for the executing thread, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The double to wrap. + * @param out_value Receives the new DOUBLE 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_table_function_exec_get_local_state( - duckdb_v2_table_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_double(duckdb_v2_factory_handle factory, double in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the output chunk the exec callback must write the next batch of rows into. + * Creates a TYPE value from a logical type. * - * The chunk holds one vector per column declared with `duckdb_v2_table_function_bind_add_result_column()`, in the same - * order; reach them with `duckdb_v2_data_chunk_get_vector()`. The chunk starts out empty on every invocation: write the - * rows, then declare how many there are with `duckdb_v2_vector_set_size()` on the first vector, which the engine takes - * as the batch's row count and propagates to the other vectors. Producing an empty batch signals the end of the scan, - * after which the callback is not invoked again on that thread. Borrowed; valid only for the duration of the callback. + * The logical type is borrowed and copied into the value, so the caller can destroy it independently. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param chunk Receives the borrowed output chunk to write into. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_type The borrowed logical type to wrap. + * @param out_value Receives the new TYPE 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_table_function_exec_get_output_chunk(duckdb_v2_table_function_exec_info_handle info, - duckdb_v2_data_chunk_handle *chunk, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_type(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle in_type, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns the scan produces. + * Creates a DATE value. * - * With projection pushdown (see `duckdb_v2_table_function_set_projection_pushdown()`) this is the number of columns the - * query uses, which is the number of vectors in the exec callback's output chunk; without it, it is the number of - * columns declared in bind. Valid indices for `duckdb_v2_table_function_exec_get_column_index()` are `0` up to (but - * excluding) this count. + * The payload is days since 1970-01-01, the same unit value_get_date reports. It is not range-checked here; value_cast + * is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param count Receives the number of columns the scan produces. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new DATE 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_table_function_exec_get_column_count( - duckdb_v2_table_function_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_date(duckdb_v2_factory_handle factory, int32_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns which declared column the scan's column at the given index stands for. + * Creates a TIME value. * - * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration - * order: the exec callback fills the output chunk's vector at `index` with that column's data. Without projection - * pushdown the mapping is the identity. Fails if the index is out of bounds. + * The payload is microseconds since midnight, the same unit value_get_time reports. It is not range-checked here; + * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param index The index of the column in the scan's output. - * @param column_index Receives the index of the declared column. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIME 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_table_function_exec_get_column_index( - duckdb_v2_table_function_exec_info_handle info, idx_t index, idx_t *column_index, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_time(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Creates a TIME_NS value. + * + * The payload is nanoseconds since midnight, the same unit value_get_time_ns reports. It is not range-checked here; + * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The progress info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIME_NS 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_table_function_progress_get_user_data( - duckdb_v2_table_function_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_time_ns(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Creates a TIME_TZ value. + * + * The payload packs the time of day and the UTC offset into one integer, in the committed layout: micros in the high 40 + * bits, a biased offset in the low 24. The same form value_get_time_tz reports. It is not range-checked here; + * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The progress info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIME_TZ 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_table_function_progress_get_bind_data( - duckdb_v2_table_function_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_time_tz(duckdb_v2_factory_handle factory, uint64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the global state set by the function's global init callback. + * Creates a TIMESTAMP value. * - * The progress callback runs concurrently with the exec callbacks scanning the function, so it must read the global - * state in a thread-safe way. + * The payload is microseconds since 1970-01-01, the same unit value_get_timestamp reports. It is not range-checked + * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The progress info handle. - * @param data Receives the global state pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP 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_table_function_progress_get_global_state( - duckdb_v2_table_function_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports how far the scan has advanced. + * Creates a TIMESTAMP_SEC value. * - * A fraction between 0.0 (nothing scanned yet) and 1.0 (done); values outside that range are clamped. A progress - * callback that returns without calling this reports no progress. + * The payload is seconds since 1970-01-01, the same unit value_get_timestamp_sec reports. It is not range-checked here; + * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The progress info handle. - * @param progress The fraction of the scan that is complete, in [0.0, 1.0]. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP_SEC 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_table_function_progress_set_progress( - duckdb_v2_table_function_progress_info_handle info, double progress, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_sec(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`, or null if none was set. + * Creates a TIMESTAMP_MS value. + * + * The payload is milliseconds since 1970-01-01, the same unit value_get_timestamp_ms reports. It is not range-checked + * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param data Receives the user data pointer. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP_MS 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_table_function_filter_pushdown_get_user_data( - duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_ms(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set via `duckdb_v2_function_bind_set_bind_data()`, or null if none was set. + * Creates a TIMESTAMP_NS value. * - * This is the same object the init and exec callbacks later receive, so a predicate the callback accepts can be - * recorded in it for the scan to apply. + * The payload is nanoseconds since 1970-01-01, the same unit value_get_timestamp_ns reports. It is not range-checked + * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param data Receives the bind data pointer. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP_NS 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_table_function_filter_pushdown_get_bind_data( - duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_ns(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of filter predicates offered to the function. + * Creates a TIMESTAMP_TZ value. * - * The predicates are combined with `AND`: every row the scan produces must satisfy all of them. Valid indices for - * `duckdb_v2_table_function_filter_pushdown_get_filter()` and `duckdb_v2_table_function_filter_pushdown_accept()` are - * `0` up to (but excluding) this count. + * The payload is microseconds since 1970-01-01, in UTC, the same unit value_get_timestamp_tz reports. It is not + * range-checked here; value_cast is the validating path. The returned value is caller-owned; destroy it via + * value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param count Receives the number of predicates. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP_TZ 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_table_function_filter_pushdown_get_filter_count( - duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_tz(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the filter predicate at the given index. + * Creates a TIMESTAMP_TZ_NS value. * - * Fails if the index is out of bounds. The predicate is a bound expression evaluating to `BOOLEAN`; inspect it with - * `duckdb_v2_expression_get_type()` and the other `expression` functions, and resolve the column references it contains - * via `duckdb_v2_table_function_filter_pushdown_get_column_index()`. Borrowed; valid only for the duration of the - * callback. + * The payload is nanoseconds since 1970-01-01, in UTC, the same unit value_get_timestamp_tz_ns reports. It is not + * range-checked here; value_cast is the validating path. The returned value is caller-owned; destroy it via + * value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param index The index of the predicate to retrieve. - * @param filter Receives the borrowed predicate. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP_TZ_NS 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_table_function_filter_pushdown_get_filter( - duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, duckdb_v2_expression_handle *filter, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_tz_ns(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Accepts the filter predicate at the given index: the function will apply it itself. + * Creates a INTERVAL value. * - * The engine stops applying an accepted predicate, so the scan must produce only rows that satisfy it, or the query - * returns rows it should not. Predicates left unaccepted are applied by the engine as usual, so a callback that - * recognizes nothing can simply return. Fails if the index is out of bounds. + * The payload is the (months, days, micros) triple, the same unit value_get_interval reports. It is not range-checked + * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param index The index of the predicate to accept. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new INTERVAL 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_table_function_filter_pushdown_accept( - duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_interval(duckdb_v2_factory_handle factory, + const duckdb_v2_interval_t *in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns the predicates can refer to. + * Creates a DECIMAL value from its backing integer. * - * A column reference inside a predicate (`duckdb_v2_expression_column_ref_get_index()`) indexes the columns the query - * reads from the function, not the columns declared in bind. Valid indices for - * `duckdb_v2_table_function_filter_pushdown_get_column_index()` are `0` up to (but excluding) this count. + * 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 info The filter pushdown info handle. - * @param count Receives the number of referable columns. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The backing integer, scaled by 10^scale. + * @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_table_function_filter_pushdown_get_column_count( - duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_decimal(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); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Resolves a column reference found in a predicate to the declared column it refers to. + * Creates a UUID value from its internal 128-bit form. * - * Takes the index a `EXPRESSION_TYPE_BOUND_COLUMN_REF` node reports and returns the index of the column among the ones - * declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration order. Fails if the index is out of - * bounds. + * The payload is the storage form a vector element holds, not the canonical byte order: the high bit is flipped so the + * integer sorts. To build one from canonical text, cast a VARCHAR with value_cast instead, which is also how a UUID + * renders back. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param index The column index reported by a column reference node. - * @param column_index Receives the index of the declared column. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The internal 128-bit storage form. + * @param out_value Receives the new UUID 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_table_function_filter_pushdown_get_column_index( - duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_uuid(duckdb_v2_factory_handle factory, + const duckdb_v2_hugeint_t *in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Creates a BIT value from its wire bytes. + * + * The wire form is a mandatory padding-header byte — the count of leading bits in the first data byte that are not part + * of the bit string — followed by the data bytes, so the input must be at least 1 byte. These are the same bytes + * value_get_blob reports back. * * history: * - unstable: v2.0.0 * - * @param info The partition data info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The wire bytes, a padding header byte followed by data. Must be at least 1 byte. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. + * @param out_value Receives the new BIT 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_table_function_partition_data_get_user_data( - duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bit(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Creates a BIGNUM value from its storage bytes. + * + * The bytes are opaque storage, as produced by bignum_encode from a magnitude and a sign flag; a negative is stored + * bit-inverted behind a header, so these are not the magnitude bytes. The header plus at least one magnitude byte means + * the input must exceed 3 bytes. These are the same bytes value_get_blob reports back, for bignum_decode to translate. * * history: * - unstable: v2.0.0 * - * @param info The partition data info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The opaque storage bytes from bignum_encode. Must exceed 3 bytes. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. + * @param out_value Receives the new BIGNUM 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_table_function_partition_data_get_bind_data( - duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bignum(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the global state set by the function's global init callback. + * Creates a LIST value from its elements. * - * Shared with every other thread scanning the function; access to it must be synchronized by the function. + * The child type is the common type of the elements, resolved by the same rule a SQL list literal follows, and every + * element is cast to it; a set with no common type surfaces the cast error. Pass child_type to name the type instead, + * which is also how an empty list is built: with child_type NULL, an empty element array has no type to resolve and + * returns ERROR_INPUT_INVALID. + * + * The elements are borrowed and copied in, and a NULL element becomes a typed NULL. The type is rebuilt from its child, + * so an alias on the outer LIST type is not preserved; value_cast is the alias-preserving path. * * history: * - unstable: v2.0.0 * - * @param info The partition data info handle. - * @param data Receives the global state pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param child_type Optional. The element type. Pass NULL to resolve it from the elements. + * @param children An array of child_count elements. Borrowed (copied in). Pass NULL when child_count is 0. + * @param child_count The number of elements. + * @param out_value Receives the new composite 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_table_function_partition_data_get_global_state( - duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_list(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle child_type, + const duckdb_v2_value_handle *children, idx_t child_count, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the worker-local local state set by the function's local init callback, for the thread that produced the - * batch this call reports on. No other thread observes it, so it needs no synchronization. + * Creates an ARRAY value from its elements, sized by their count. + * + * The child type is resolved exactly as for value_create_list, and child_type names it explicitly the same way. The + * minimum array size is 1, so an empty element array returns ERROR_INPUT_INVALID whether or not child_type is given. + * + * The elements are borrowed and copied in, and a NULL element becomes a typed NULL. * * history: * - unstable: v2.0.0 * - * @param info The partition data info handle. - * @param data Receives the local state pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param child_type Optional. The element type. Pass NULL to resolve it from the elements. + * @param children An array of child_count elements. Borrowed (copied in). Pass NULL when child_count is 0. + * @param child_count The number of elements. + * @param out_value Receives the new composite 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_table_function_partition_data_get_local_state( - duckdb_v2_table_function_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_array(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle child_type, + const duckdb_v2_value_handle *children, idx_t child_count, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns whether a downstream operator needs this batch's ordering position. + * Creates a STRUCT value from named fields, in order. * - * `duckdb_v2_table_function_partition_data_set_batch_index()` must still be called even when this is false: the engine - * validates the reported value regardless of whether it is actually used for ordering, so `0` is always a safe answer - * when this reports false. + * Each field keeps its own child's type, so there is nothing to resolve across them; names and children are parallel + * arrays of field_count entries. An empty field list builds the empty struct, which is a real type. + * + * The names and children are borrowed and copied in, and a NULL child becomes a typed NULL. Duplicate field names are + * rejected. * * history: * - unstable: v2.0.0 * - * @param info The partition data info handle. - * @param required Receives whether a batch index is required. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param names An array of field_count field names. Pass NULL when field_count is 0. + * @param names_lengths Byte lengths of the entries in `names`; element i is the length of `names[i]`. May be NULL only + * when `names` is NULL. + * @param children An array of field_count field values. Borrowed (copied in). Pass NULL when field_count is 0. + * @param field_count The number of fields. + * @param out_value Receives the new composite 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_table_function_partition_data_requires_batch_index( - duckdb_v2_table_function_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, const char *const *names, + const idx_t *names_lengths, + const duckdb_v2_value_handle *children, idx_t field_count, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns whether a downstream operator needs this batch's values for a set of partitioning columns. + * Creates a TUPLE value from positional fields. + * + * TUPLE is the unnamed struct: the same positional children as value_create_struct, under a distinct type id and with + * no names. Each field keeps its own child's type. An empty field list builds the empty tuple, which is a real type. * - * When true, call `duckdb_v2_table_function_partition_data_set_partition_value()` once for every index in `[0, count)`, - * where `count` comes from `duckdb_v2_table_function_partition_data_get_partition_column_count()`. + * The children are borrowed and copied in, and a NULL child becomes a typed NULL. * * history: * - unstable: v2.0.0 * - * @param info The partition data info handle. - * @param required Receives whether partitioning column values are required. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param children An array of field_count field values. Borrowed (copied in). Pass NULL when field_count is 0. + * @param field_count The number of fields. + * @param out_value Receives the new composite 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_table_function_partition_data_requires_partition_columns( - duckdb_v2_table_function_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_tuple(duckdb_v2_factory_handle factory, + const duckdb_v2_value_handle *children, idx_t field_count, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of partitioning columns a downstream operator is requesting values for. + * Creates a MAP value from parallel key and value arrays. + * + * The key and value types are the common types of the keys and of the values, resolved as for value_create_list, and + * every entry is cast to them. Pass key_type and value_type to name them instead, which is also how an empty map is + * built: with both NULL, empty key and value arrays have no types to resolve and return ERROR_INPUT_INVALID. * - * `0` when `duckdb_v2_table_function_partition_data_requires_partition_columns()` is false. Valid indices for - * `duckdb_v2_table_function_partition_data_get_partition_column_index()` and - * `duckdb_v2_table_function_partition_data_set_partition_value()` are `0` up to (but excluding) this count. + * Keys and values are borrowed and copied in, and the two arrays must be the same length. Keys must be non-NULL and + * unique; both are enforced. * * history: * - unstable: v2.0.0 * - * @param info The partition data info handle. - * @param count Receives the number of requested partitioning columns. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param key_type Optional. The key type. Pass NULL to resolve it from the keys. + * @param value_type Optional. The value type. Pass NULL to resolve it from the values. + * @param keys An array of entry_count keys. Borrowed (copied in). Pass NULL when entry_count is 0. + * @param values An array of entry_count values, parallel to keys. Borrowed (copied in). Pass NULL when entry_count is + * 0. + * @param entry_count The number of entries. + * @param out_value Receives the new composite 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_table_function_partition_data_get_partition_column_count( - duckdb_v2_table_function_partition_data_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_map( + duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle key_type, duckdb_v2_logical_type_handle value_type, + const duckdb_v2_value_handle *keys, const duckdb_v2_value_handle *values, idx_t entry_count, + duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns which declared column the requested partitioning column at the given index stands for. + * Returns the number of child values of a value. * - * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration - * order. Fails if the index is out of bounds. + * Per type kind: the element count for LIST and ARRAY; the field count for STRUCT and TUPLE; twice the entry count for + * MAP, whose children alternate key, value; and 2 for UNION, the tag plus the active member. Everything else reports 0, + * NULL values of any nested type included. * * history: * - unstable: v2.0.0 * - * @param info The partition data info handle. - * @param index The index of the requested partitioning column. - * @param column_index Receives the index of the declared column. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out_count Receives the number of children. + * @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_table_function_partition_data_get_partition_column_index( - duckdb_v2_table_function_partition_data_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_child_count(duckdb_v2_value_handle value, idx_t *out_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports the ordering position of the batch the exec callback just produced. + * Returns one child of a composite value as an owned copy. * - * Required on every call, whether or not `duckdb_v2_table_function_partition_data_requires_batch_index()` is true: the - * engine validates the reported value regardless. Not calling this before the callback returns fails the query; `0` is - * always a safe answer when the batch index is not actually required. Must not decrease across successive calls on the - * same thread, must be unique across threads for the ordering to be meaningful, must be less than roughly `10^13`, and, - * when partitioning column values are also being reported, must change whenever those values change: the engine only - * re-reads them when the batch index changes, so reporting a new value under an unchanged batch index is treated as a - * caller error rather than applied. Fails with `ERROR_INPUT_INVALID` for an out-of-range value; a decreasing value or - * an unchanged value paired with changed partitioning columns fails the query once the callback returns. + * LIST and ARRAY children are the elements. STRUCT and TUPLE children are the fields in declared order, and a STRUCT's + * field names come from its type, via logical_type_get_param. MAP children alternate key, value, symmetric with + * value_create_map. UNION children are [0] the tag, as a UTINYINT value, and [1] the active member, because a union + * value holds only that one member. + * + * Note the divergence from vector_get_child, which descends structurally and so exposes [0] = tag and [1..N] = ALL + * members. Code written to descend generically over both must account for that difference. + * + * An out-of-range index returns ERROR_INPUT_INVALID, as does any index on a non-composite or NULL value. The returned + * value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The partition data info handle. - * @param batch_index The batch's ordering position. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param index The child index, in [0, child_count). + * @param out_child Receives the owned child 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_table_function_partition_data_set_batch_index( - duckdb_v2_table_function_partition_data_info_handle info, idx_t batch_index, duckdb_v2_error_info_handle *err); +DUCKDB_C_API 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); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports the single value of the partitioning column at the given index, for the batch the exec callback just - * produced. + * Returns the value that a VARIANT value holds, as a value of its own type. * - * Every partition reported this way carries exactly one distinct value for the column, so the value serves as both the - * minimum and maximum of the partition's range. The value is borrowed and copied, and must be of the declared type of - * the corresponding result column. Required once for every index in `[0, - * `duckdb_v2_table_function_partition_data_get_partition_column_count()`)` before the callback returns; calling it - * again for the same index overwrites the previous value. The reported value only takes effect together with a changed - * `duckdb_v2_table_function_partition_data_set_batch_index()`: reporting a different value under an unchanged batch - * index fails the query once the callback returns. Fails with `ERROR_INPUT_INVALID` when the index is out of bounds or - * the value's type does not match. + * 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 info The partition data info handle. - * @param index The index of the partitioning column being reported. - * @param value The single value of the partitioning column. Borrowed and copied. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @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_table_function_partition_data_set_partition_value( - duckdb_v2_table_function_partition_data_info_handle info, idx_t index, duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); +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 /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Casts a value to a target type, using a factory. + * + * The conversion is the SQL-faithful, non-strict one, registered custom casts included, and a cast failure surfaces + * from the call. Together with a VARCHAR built through value_create_varchar, this constructs any value from text, + * extension values included; casting a member value to a union type, or a VARCHAR to an enum type, is the sanctioned + * way to build UNION and ENUM values. + * + * A connection's or callback's factory casts with that client's cast functions and settings (e.g. TimeZone). An + * instance's factory supports only the built-in casts, with default settings. + * + * The input value and target type are borrowed. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The partitioning info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory supplying the cast functions. + * @param value The borrowed value to cast. + * @param target_type The borrowed target logical type. + * @param out_value Receives the owned cast result. + * @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_table_function_partitioning_get_user_data( - duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_cast(duckdb_v2_factory_handle factory, duckdb_v2_value_handle value, + duckdb_v2_logical_type_handle target_type, + duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Returns whether the value is NULL. * * history: * - unstable: v2.0.0 * - * @param info The partitioning info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out_is_null Receives true if the value is NULL, false otherwise. + * @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_table_function_partitioning_get_bind_data( - duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_is_null(duckdb_v2_value_handle value, bool *out_is_null, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns the optimizer is asking about: the candidate `GROUP BY` column set. + * Returns the logical type of the value. * - * Valid indices for `duckdb_v2_table_function_partitioning_get_partition_column_index()` are `0` up to (but excluding) - * this count. + * The returned logical type is caller-owned; destroy it via logical_type_destroy. * * history: * - unstable: v2.0.0 * - * @param info The partitioning info handle. - * @param count Receives the number of columns in the candidate set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out_type Receives the owned logical type. + * @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_table_function_partitioning_get_partition_column_count( - duckdb_v2_table_function_partitioning_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_logical_type(duckdb_v2_value_handle value, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns which declared column the candidate `GROUP BY` column at the given index stands for. + * Renders the value as a human-readable string. Diagnostic only. * - * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration - * order. Fails if the index is out of bounds. + * Writes into a caller-supplied buffer, so nothing is allocated on the caller's behalf and nothing has to be freed. + * + * Pass out_string = NULL to size the buffer without rendering into it: out_length then receives the length, and + * out_capacity is ignored. With out_string != NULL, out_capacity must be at least out_length + 1, or the call returns + * ERROR_INPUT_OBJECT_SIZE with out_length set to the required length and out_string left untouched. + * + * out_length never counts the terminator, but a successful write always appends one, so the buffer is usable as a C + * string. * * history: * - unstable: v2.0.0 * - * @param info The partitioning info handle. - * @param index The index of the candidate column. - * @param column_index Receives the index of the declared column. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out_string Caller-owned buffer receiving the text plus a null terminator, or NULL to only report the required + * length in out_length. + * @param out_capacity Bytes available in out_string, terminator included. Ignored when out_string is NULL. + * @param out_length Receives the text length excluding the null terminator — written on success and on + * ERROR_INPUT_OBJECT_SIZE. + * @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_table_function_partitioning_get_partition_column_index( - duckdb_v2_table_function_partitioning_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_to_string(duckdb_v2_value_handle value, char *out_string, + idx_t out_capacity, idx_t *out_length, + duckdb_v2_error_info_handle *err); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE +/* --- Struct definitions for value --- */ + +/* ============================================================================ + * MODULE: arrow + * ============================================================================ */ + +/* --- Enums for arrow --- */ + +/* --- Struct forward declarations for arrow --- */ + +/* --- Types for arrow --- */ + /*! - * Reports whether every partition the scan produces carries exactly one distinct value for the candidate `GROUP BY` - * column set. - * - * Only `TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS` unlocks the partitioned aggregate optimization; any other value - * keeps the regular hash aggregate. A callback that never calls this is treated as reporting - * `TABLE_PARTITION_INFO_NOT_PARTITIONED`. Fails with `ERROR_INPUT_INVALID` when partition_info is not one of the enum's - * declared values. - * - * history: - * - unstable: v2.0.0 + * Converts Arrow arrays into DuckDB data chunks, against one resolved ArrowSchema. Create it with + * `duckdb_v2_arrow_importer_create()`, which resolves every column's DuckDB type once, so the same importer serves any + * number of arrays of that shape. `duckdb_v2_arrow_importer_get_schema()` reports the resolved DuckDB schema. + * `duckdb_v2_arrow_importer_append()` takes an array, `duckdb_v2_arrow_importer_next_chunk()` produces chunks from it, + * and `duckdb_v2_arrow_importer_destroy()` frees the importer. * - * @param info The partitioning info handle. - * @param partition_info Whether, and how, the scan is partitioned by the candidate column set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR + * 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. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_set_partition_info( - duckdb_v2_table_function_partitioning_info_handle info, DUCKDB_V2_TABLE_PARTITION_INFO partition_info, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_arrow_importer { + void *internal_ptr; +} * duckdb_v2_arrow_importer_handle; -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Converts DuckDB data chunks into Arrow arrays, for one fixed list of columns. Create it with + * `duckdb_v2_arrow_exporter_create()`, which captures the session's Arrow settings and resolves the extension types + * once. `duckdb_v2_arrow_exporter_get_schema()` reports the Arrow schema. `duckdb_v2_arrow_exporter_append()` takes a + * chunk, `duckdb_v2_arrow_exporter_next_array()` produces arrays from it, and `duckdb_v2_arrow_exporter_destroy()` + * frees the exporter. * - * history: - * - unstable: v2.0.0 + * An exporter must not be used from two threads at once. + */ +typedef struct _duckdb_v2_arrow_exporter { + void *internal_ptr; +} * duckdb_v2_arrow_exporter_handle; + +/*! + * A query result that produces Arrow arrays. Works like a result, which produces data chunks. Create it with + * `duckdb_v2_statement_execute_arrow()` or `duckdb_v2_prepared_statement_execute_arrow()`. * - * @param info The stats info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR + * - Use it from one thread at a time. + * - `duckdb_v2_connection_interrupt()` cancels it: `duckdb_v2_arrow_result_step()` reports `CANCELLED`, and + * `duckdb_v2_arrow_result_fetch_array()` and a stream's `get_next` fail. + * - Arrays and schemas it hands out belong to the caller and stay valid after the result is destroyed. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_user_data( - duckdb_v2_table_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_arrow_result { + void *internal_ptr; +} * duckdb_v2_arrow_result_handle; + +/* --- Constants for arrow --- */ + +/* --- Function pointer typedefs for arrow --- */ + +/* --- Functions for arrow --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Resolves an Arrow schema into a reusable importer. + * + * Works out every column's DuckDB logical type and the Arrow type information the conversion needs, once, so any number + * of arrays of that shape can be imported without re-reading the schema. `schema` is read, not consumed: the caller + * keeps ownership and still releases it. + * + * `batch_size` caps the rows per produced chunk. A long array is split across several chunks. Rows left over that do + * not fill a batch are held back and joined with the next array, unless the append asked to flush. Pass 0 for no + * maximum: each array becomes one chunk, however long it is. + * + * Resolving reads the catalog for extension types, so `context` must have an active transaction. The importer keeps + * using that context for every conversion and must not outlive it. Within one connection the context is the same + * throughout, so an importer created in a bind callback is usable from the matching exec callback. `*out_importer` is + * set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param context The context used to resolve the Arrow types, extension types included. + * @param schema The schema to resolve. Read, not consumed; the caller keeps ownership. + * @param batch_size Maximum rows per produced chunk, or 0 for no maximum. + * @param out_importer On success, receives the new importer. Owned by the caller; destroy via + * `duckdb_v2_arrow_importer_destroy()`. * @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_table_function_stats_get_bind_data( - duckdb_v2_table_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_importer_create(duckdb_v2_context_handle context, + const struct ArrowSchema *schema, idx_t batch_size, + duckdb_v2_arrow_importer_handle *out_importer, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns which declared column the statistics describe. + * Returns the resolved DuckDB schema. * - * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration - * order. It is never the index of a virtual column or of a field extracted from a column; the callback is not asked - * about those. + * Writes an owned schema handle with the DuckDB name and logical type of every column the importer resolved. This is + * how a caller learns the DuckDB shape of an ArrowSchema, to declare a table function's result columns for instance, + * without reimplementing the mapping from Arrow format strings to logical types. + * + * The fields were resolved at creation, so this reads no catalog and needs no transaction. `*out_schema` is set to NULL + * on failure. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param column_index Receives the index of the declared column. + * @param importer The importer to read. + * @param out_schema On success, receives an owned schema. Destroy via `duckdb_v2_schema_destroy()`. * @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_table_function_stats_get_column_index( - duckdb_v2_table_function_stats_info_handle info, idx_t *column_index, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_importer_get_schema(duckdb_v2_arrow_importer_handle importer, + duckdb_v2_schema_handle *out_schema, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the statistics of the column, for the callback to narrow. + * Gives the importer one array to convert. * - * The statistics start out unknown, with every kind of value possible, and are of the column's type as the bind - * callback declared it. The callback narrows them with `duckdb_v2_stats_set_value()`, from a STRUCT value in the shape - * `duckdb_v2_stats_get_value()` returns - e.g. `{'min': 20, 'max': 30, 'has_null': false}` for an INTEGER column, or - * the statistics of the fields of a STRUCT column under `child_stats` - and with `duckdb_v2_stats_set_can_have_null()` - * / `duckdb_v2_stats_set_can_have_valid()`. Statistics built with `duckdb_v2_stats_create()`, e.g. combined from the - * files of a scan with `duckdb_v2_stats_merge()`, are copied in with `duckdb_v2_stats_assign()`. They describe every - * value the scan produces for the column. Borrowed; valid only for the duration of the callback. + * Take the chunks with `duckdb_v2_arrow_importer_next_chunk()` until that returns NULL. Appending while the previous + * array still has rows left is rejected with `ERROR_INPUT_INVALID`. An array whose shape does not match the resolved + * schema -- a different child count, a child whose length differs from the array's, a null or already-released child -- + * is rejected the same way, before anything is read. + * + * `flush` marks the end of the input: rows that do not fill a batch then come out as a final short chunk instead of + * being held back for the next array. Pass NULL for `array` with `flush` set to release the held rows without supplying + * more input. + * + * `consume` decides what happens to the caller's array. + * + * When true, the importer takes over the array and sets its `release` to NULL; the caller must not release it + * afterwards. The produced chunks reference the Arrow buffers directly, without copying, and keep them alive, so the + * chunks stay valid after the importer is destroyed. Prefer this path. + * + * When false, the caller keeps the array and must keep it valid until the drain finishes. The produced chunks are + * copies, so they do not depend on the array, at the cost of one copy per chunk. + * + * Either way, a chunk that joins rows held back from the previous array is a copy, since it cannot reference two + * arrays. + * + * Only the default, dictionary-encoded and run-end-encoded Arrow layouts are supported. Any other layout reports + * `ERROR_QUERY_NOT_IMPLEMENTED` when the column is converted. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param stats Receives the borrowed, writable statistics of the column. + * @param importer The importer to feed. + * @param array The array to convert. Its `release` is set to NULL when `consume` is true. + * @param consume True to hand the array over for a zero-copy import; false to keep it, in which case every produced + * chunk is a copy. + * @param flush True to mark the end of the input, releasing held rows as a final short chunk. Pass NULL for `array` + * with this set to flush without supplying more input. * @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_table_function_stats_get_result_stats( - duckdb_v2_table_function_stats_info_handle info, duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_importer_append(duckdb_v2_arrow_importer_handle importer, + struct ArrowArray *array, bool consume, bool flush, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Produces the next chunk of the appended array, or NULL once the array is drained. + * + * Call it in a loop until `*out_chunk` is NULL. An importer with no array appended also returns NULL. Each chunk holds + * at most the importer's `batch_size` rows, or the whole array when that is 0. A chunk may start with rows held back + * from the previous array, and rows that do not fill a batch are held back in turn unless the append asked to flush. So + * NULL means the array has been read, not that all of its rows have come out. + * + * The conversion runs under the context the importer was created with, which must still be alive. `*out_chunk` is set + * to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param info The metrics info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param importer The importer to drain. + * @param out_chunk On success, receives the next chunk, or NULL once the array is drained. Destroy via + * `duckdb_v2_data_chunk_destroy()`. * @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_table_function_metrics_get_user_data( - duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_importer_next_chunk(duckdb_v2_arrow_importer_handle importer, + duckdb_v2_data_chunk_handle *out_chunk, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Destroys an importer. + * + * Null-safe: passing NULL, or a slot already set to NULL, is a no-op. Chunks already produced stay valid, including the + * zero-copy ones, which keep the Arrow buffers alive themselves. An array appended with `consume` true and not fully + * drained is released here. Rows held back for a next array are dropped. On success the slot is set to NULL. * * history: * - unstable: v2.0.0 * - * @param info The metrics info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param importer The importer to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_get_bind_data( - duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_importer_destroy(duckdb_v2_arrow_importer_handle *importer); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the global state set by the function's global init callback. + * Creates an exporter for one fixed list of columns. * - * The metrics callback can run while the scan is still running, so it must read the global state in a thread-safe way. - * The global state is null if the scan has not been initialized. + * Resolves the extension types and captures the session's Arrow settings, so every array this exporter produces matches + * the schema `duckdb_v2_arrow_exporter_get_schema()` reports, even if a setting changes afterwards. + * + * `batch_size` caps the rows per produced array. A long chunk is split across several arrays. Rows left over that do + * not fill a batch are held back and joined with the next chunk, unless the append asked to flush. Pass 0 for no + * maximum: each chunk becomes one array, however long it is. + * + * `types` and `names` are parallel arrays of `count` entries, borrowed and copied; they may be NULL only when `count` + * is 0. Resolving reads the catalog, so `context` must have an active transaction. `*out_exporter` is set to NULL on + * failure. * * history: * - unstable: v2.0.0 * - * @param info The metrics info handle. - * @param data Receives the global state pointer, or null if none was set. + * @param context The context whose Arrow settings are captured and whose transaction resolves the types. + * @param types An array of `count` column types. May be NULL only when `count` is 0. + * @param names An array of `count` column names, parallel to `types`. Each name must be valid UTF-8. May be NULL only + * when `count` is 0. + * @param names_lengths Byte lengths of the entries in `names`; element i is the length of `names[i]`. May be NULL only + * when `names` is NULL. + * @param count The number of columns, being the length of both `types` and `names`. + * @param batch_size Maximum rows per produced array, or 0 for no maximum. + * @param out_exporter On success, receives the new exporter. Owned by the caller; destroy via + * `duckdb_v2_arrow_exporter_destroy()`. * @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_table_function_metrics_get_global_state( - duckdb_v2_table_function_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_create(duckdb_v2_context_handle context, + const duckdb_v2_logical_type_handle *types, + const char *const *names, const idx_t *names_lengths, + idx_t count, idx_t batch_size, + duckdb_v2_arrow_exporter_handle *out_exporter, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports an operator metric of the scan, by the name DuckDB's profiler uses for it (the names `tracked_metrics` - * accepts). - * - * The metrics a scan can report are counters: - * - `operator.rows_scanned`: the rows the scan read. - * - `operator.row_groups_scanned`: the row groups the scan read. A row group is the unit a format lets the scan skip, - * e.g. a Parquet row group or an ORC stripe. - * - `operator.total_row_groups_to_scan`: the row groups the scan read or skipped. - * - `operator.bytes_scanned`: the bytes the scan read. + * Returns the Arrow schema of the arrays this exporter produces. * - * The engine may collect the metrics of a scan more than once, and adds up what it is told: each value is the amount - * since the metrics were last collected, except `operator.total_row_groups_to_scan`, which is the number found so far - * in all. Fails for a name that is not one of the above. + * Fills the caller-allocated `out_schema`. The caller owns the result and releases it with + * `out_schema->release(out_schema)`. Callable at any point, and always returns the same schema, since it is built from + * the settings captured at creation. * * history: * - unstable: v2.0.0 * - * @param info The metrics info handle. - * @param name The name of the metric. Borrowed. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8 and need not be null-terminated. - * @param value The value of the metric. + * @param exporter The exporter to read. + * @param out_schema Caller-allocated schema the library fills. Release it with `out_schema->release(out_schema)`. * @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_table_function_metrics_set(duckdb_v2_table_function_metrics_info_handle info, - const char *name, idx_t name_length, uint64_t value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_get_schema(duckdb_v2_arrow_exporter_handle exporter, + struct ArrowSchema *out_schema, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the table function, making it available for use in SQL queries. + * Gives the exporter one chunk to convert. * - * The function is registered on the connection's database, visible to every connection, in the connection's - * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. Registration requires a name, a bind callback and an exec callback, and rejects a signature - * that declares a return type, since a table function declares the columns it returns from its bind callback. The table - * function must have been created through a factory of the same database. The caller still owns the handle after - * registration and must destroy it with `duckdb_v2_table_function_destroy()`, which does not affect the registered - * function. + * The chunk is converted in full before this returns. The conversion copies into freshly allocated Arrow buffers, so + * nothing of the caller's is retained. Every array completed by this chunk becomes available from + * `duckdb_v2_arrow_exporter_next_array()`; rows that do not complete a batch are held back and finished by the next + * chunk. Completed arrays queue up, so appending again before they are taken is allowed. + * + * `flush` marks the end of the input: the held rows are then finished as a final short array. Pass NULL for `chunk` + * with `flush` set to release the held rows without supplying more input. + * + * The chunk's types must match the ones the exporter was created with, or the call is rejected with + * `ERROR_INPUT_INVALID` before anything is read. + * + * `consume` decides only what happens to the caller's handle, since the data is copied either way. When true the chunk + * is destroyed and the slot set to NULL, saving a `duckdb_v2_data_chunk_destroy()` for a chunk the caller owns. When + * false the chunk is left untouched, which is what a chunk borrowed from a callback needs, such as the output chunk of + * a table function's exec callback, which the caller does not own and must not destroy. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param function The table function to register. + * @param exporter The exporter to feed. + * @param chunk The chunk to convert. Destroyed and set to NULL only when `consume` is true. + * @param consume True to hand the chunk over, destroying it; false to leave the caller's handle untouched. + * @param flush True to mark the end of the input, releasing the held rows as a final short array. Pass NULL for `chunk` + * with this set to flush without supplying more input. * @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_register_table_function(duckdb_v2_connection_handle conn, - duckdb_v2_table_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_append(duckdb_v2_arrow_exporter_handle exporter, + duckdb_v2_data_chunk_handle *chunk, bool consume, + bool flush, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the table function, making it available for use in SQL queries. + * Takes the next completed array, or reports that none is ready. * - * The function is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. Registration requires a name, a bind callback and an exec callback, and rejects a - * signature that declares a return type, since a table function declares the columns it returns from its bind callback. - * The table function must have been created through a factory of the same database. The caller still owns the handle - * after registration and must destroy it with `duckdb_v2_table_function_destroy()`, which does not affect the - * registered function. + * Call it in a loop after every `duckdb_v2_arrow_exporter_append()` until `out_array->release` is NULL, which is how + * the Arrow C Data Interface signals "no array" and what a stream's `get_next` does at end of input. Rows held back + * towards an unfinished batch are not an array yet; they come out after a further append or a flush. + * + * Each array is owned by the caller and released with `out_array->release(out_array)`, independently of the exporter + * and of every other array. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The table function to register. + * @param exporter The exporter to drain. + * @param out_array Caller-allocated array the library fills. Left released -- `release` NULL -- when none is ready. + * Release a filled one with `out_array->release(out_array)`. * @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_extension_register_table_function(duckdb_v2_extension_handle extension, - duckdb_v2_table_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_next_array(duckdb_v2_arrow_exporter_handle exporter, + struct ArrowArray *out_array, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the table function, releasing its resources. + * Destroys an exporter. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered function. + * Null-safe: passing NULL, or a slot already set to NULL, is a no-op. Arrays already taken stay valid. Arrays still + * queued inside are released here, and rows held back towards an unfinished batch are dropped. On success the slot is + * set to NULL. * * history: * - unstable: v2.0.0 * - * @param function The function to destroy. + * @param exporter The exporter to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_destroy(duckdb_v2_table_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_destroy(duckdb_v2_arrow_exporter_handle *exporter); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the optional claim batch callback of the table function. - * - * With a claim batch callback, a scanning thread works through the scan one batch at a time: the callback claims the - * next batch of work (e.g. the next block of a file) for the thread's local state, typically from the shared global - * state, and the exec callback then produces the rows of that batch only, leaving the output chunk empty once the batch - * is exhausted. A batch is claimed before the exec callback first runs on a thread, and again whenever the exec - * callback leaves the output chunk empty; the scan ends for a thread once the claim batch callback does not claim a - * batch. - * - * Telling the batches apart lets a caller that scans several batches in parallel put their rows back in the order of - * the batches, e.g. a multi-file function registered with `duckdb_v2_connection_register_multi_file_function()` or - * `duckdb_v2_extension_register_multi_file_function()` claims the batches of the function itself, so that the rows of a - * file keep their order also when several threads scan it. +/*! + * Executes a parsed statement. The result produces Arrow arrays. * - * The callback runs while the work of the scan is handed out to the threads, possibly while every other scanning thread - * waits for it. It should therefore only claim the work - e.g. reserve the number of the next block - and leave reading - * it to the exec callback. + * Works like `duckdb_v2_statement_execute()`. `*out_result` is set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param function The function to set the claim batch callback of. - * @param callback The claim batch callback to set. + * @param conn The connection to run the statement on. + * @param statement The statement to execute. Not consumed. + * @param parameter_names Optional. As in `duckdb_v2_statement_execute()`. + * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of + * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. + * @param parameter_values Optional. As in `duckdb_v2_statement_execute()`. + * @param parameter_count The number of parameters. 0 for none. + * @param batch_size Maximum rows per array. Arrays can be shorter. 0 means 131072. + * @param out_result Receives the new result. Destroy via `duckdb_v2_arrow_result_destroy()`. * @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_table_function_set_claim_batch_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_claim_batch_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow( + duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set on the table function via `duckdb_v2_table_function_set_user_data()`. + * Executes a prepared statement. The result produces Arrow arrays. + * + * Works like `duckdb_v2_prepared_statement_execute()`. `*out_result` is set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param info The claim batch info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param prepared The prepared statement to execute. Not consumed. + * @param parameter_names Optional. As in `duckdb_v2_prepared_statement_execute()`. + * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of + * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. + * @param parameter_values Optional. As in `duckdb_v2_prepared_statement_execute()`. + * @param parameter_count The number of parameters. 0 for none. + * @param batch_size Maximum rows per array. Arrays can be shorter. 0 means 131072. + * @param out_result Receives the new result. Destroy via `duckdb_v2_arrow_result_destroy()`. * @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_table_function_claim_batch_get_user_data( - duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute_arrow( + duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Destroys the result. Works like `duckdb_v2_result_destroy()`. * * history: * - unstable: v2.0.0 * - * @param info The claim batch info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param result The result to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_claim_batch_get_bind_data( - duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_destroy(duckdb_v2_arrow_result_handle *result); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the global state set by the function's global init callback. + * Runs a bounded amount of the query and returns without blocking. * - * Shared with every other thread scanning the function; access to it must be synchronized by the function. + * Works like `duckdb_v2_result_step()`. On status `CHUNK`, `out_array` holds the next array. Otherwise its `release` is + * NULL. * * history: * - unstable: v2.0.0 * - * @param info The claim batch info handle. - * @param data Receives the global state pointer, or null if none was set. + * @param result The result to step. + * @param out_array Caller-allocated array the library fills. Release it with `out_array->release(out_array)`. + * @param out_status Receives the step status. * @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_table_function_claim_batch_get_global_state( - duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_step(duckdb_v2_arrow_result_handle result, + struct ArrowArray *out_array, + DUCKDB_V2_RESULT_STEP_STATUS *out_status, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the local state set by the function's local init callback, for the thread claiming a batch. + * Blocks until the next array is ready. + * + * Works like `duckdb_v2_result_fetch_chunk()`. At the end of the result, `out_array->release` is NULL. * * history: * - unstable: v2.0.0 * - * @param info The claim batch info handle. - * @param data Receives the local state pointer for the claiming thread, or null if none was set. + * @param result The result to fetch from. + * @param out_array Caller-allocated array the library fills. Release it with `out_array->release(out_array)`. * @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_table_function_claim_batch_get_local_state( - duckdb_v2_table_function_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_fetch_array(duckdb_v2_arrow_result_handle result, + struct ArrowArray *out_array, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports whether the callback claimed a batch for the thread. - * - * A callback that returns without calling this claimed nothing, which ends the scan for the thread. + * Blocks until `duckdb_v2_arrow_result_step()` can make progress. Works like `duckdb_v2_result_wait()`. * * history: * - unstable: v2.0.0 * - * @param info The claim batch info handle. - * @param claimed Whether a batch was claimed. + * @param result The result to wait on. * @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_table_function_claim_batch_set_claimed( - duckdb_v2_table_function_claim_batch_info_handle info, bool claimed, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_wait(duckdb_v2_arrow_result_handle result, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional "get bind info" callback of the table function. - * - * The engine invokes the callback with the bind data of a bound call when it needs to know more about the call than its - * columns. E.g. a multi-file function registered with `duckdb_v2_connection_register_multi_file_function()` or - * `duckdb_v2_extension_register_multi_file_function()` asks the function it wraps for every file it binds: it maps the - * columns of the files onto the columns of its scan by the identifiers the callback reports, and exposes the options it - * reports as the metadata of the reader of the file. The callback may be invoked more than once for the same bind data, - * so it should only report what the bind already determined. + * Runs the query to the end and reports the changed-row count. Works like `duckdb_v2_result_drain()`. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The "get bind info" callback to set. + * @param result The result to drain. + * @param out_rows_changed Receives the changed-row count for an INSERT, UPDATE or DELETE, 0 otherwise. * @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_table_function_set_get_bind_info_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_get_bind_info_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_drain(duckdb_v2_arrow_result_handle result, idx_t *out_rows_changed, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Returns the shape of the result. Works like `duckdb_v2_result_get_result_type()`. * * history: * - unstable: v2.0.0 * - * @param info The get bind info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param result The result. + * @param out_type Receives the result shape. * @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_table_function_get_bind_info_get_user_data( - duckdb_v2_table_function_get_bind_info_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_get_result_type(duckdb_v2_arrow_result_handle result, + DUCKDB_V2_RESULT_TYPE *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data the function's bind callback set for the bound call being described. + * Returns the type of statement that produced the result. Works like `duckdb_v2_result_get_statement_type()`. * * history: * - unstable: v2.0.0 * - * @param info The get bind info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param result The result. + * @param out_type Receives the statement type. * @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_table_function_get_bind_info_get_bind_data( - duckdb_v2_table_function_get_bind_info_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_get_statement_type(duckdb_v2_arrow_result_handle result, + DUCKDB_V2_STATEMENT_TYPE *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Attaches an identifier to a result column of the bound call, or to a field nested inside one. - * - * A multi-file reader can then map the columns of every file onto the columns of its scan by identifier rather than by - * name - e.g. by the field ids of a file format that carries them, so that renamed columns and fields are still found. - * An identifier is an INTEGER field id or a VARCHAR name. + * Returns the Arrow schema of the result's arrays. * - * The nested field is addressed by a path of child indexes, starting at the result column at `column_index`: 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. An empty path addresses the result column itself. Setting an identifier again for the same - * column or field replaces it. Fails with `ERROR_INPUT_INVALID` when the column index is out of range, or the path does - * not address a nested field of the column's type. + * Available whenever `duckdb_v2_result_get_schema()` would be. * * history: * - unstable: v2.0.0 * - * @param info The get bind info handle. - * @param column_index The index of the result column, in the order the bind callback declared the columns. - * @param child_path The path of child indexes addressing the nested field, or null for the column itself. - * @param child_path_length The number of entries in the path, 0 for the column itself. - * @param identifier The identifier, an INTEGER or VARCHAR value. Borrowed and copied. + * @param result The result. + * @param out_schema Caller-allocated schema the library fills. Release it with `out_schema->release(out_schema)`. * @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_table_function_get_bind_info_set_column_identifier( - duckdb_v2_table_function_get_bind_info_info_handle info, idx_t column_index, const idx_t *child_path, - idx_t child_path_length, duckdb_v2_value_handle identifier, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_get_schema(duckdb_v2_arrow_result_handle result, + struct ArrowSchema *out_schema, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets an option describing the bound call: a key-value fact about what the call reads, e.g. a property of the file it - * reads. Setting a key again replaces its value. + * Turns the result into an ArrowArrayStream. * - * A multi-file function registered with `duckdb_v2_connection_register_multi_file_function()` or - * `duckdb_v2_extension_register_multi_file_function()` exposes the options of the function it wraps as the metadata of - * the reader of each file, e.g. to a custom multi-file reader of another extension. + * On success the stream takes over the result and `*result` is set to NULL. Each `get_next` returns the next array. + * Arrays already fetched are not repeated. Releasing the stream destroys the result. + * + * Converting runs no part of the query. The stream's `get_schema` can: for a statement that expands into several + * statements, such as PIVOT, it runs the ones before the statement that returns rows. A failing `get_next` or + * `get_schema` returns `EIO`; `get_last_error` has the message. * * history: * - unstable: v2.0.0 * - * @param info The get bind info handle. - * @param key The key of the option. Borrowed and copied. - * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is - * 0. - * @param value The value of the option. Borrowed and copied. + * @param result The result to take over. Set to NULL on success. + * @param out_stream Caller-allocated stream the library fills. Release it with `out_stream->release(out_stream)`. * @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_table_function_get_bind_info_set_option( - duckdb_v2_table_function_get_bind_info_info_handle info, const char *key, idx_t key_length, - duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_to_arrow_c_stream(duckdb_v2_arrow_result_handle *result, + struct ArrowArrayStream *out_stream, + duckdb_v2_error_info_handle *err); #endif +/* --- Struct definitions for arrow --- */ + +/* ============================================================================ + * MODULE: data_source + * ============================================================================ */ + +/* --- Enums for data_source --- */ + +/* --- Struct forward declarations for data_source --- */ + +/* --- Types for data_source --- */ + +/*! + * An owned opaque handle to a data source being built. A data source is what scans a source of rows: like a physical + * operator source it sets up the state of the scan, hands out the work to the scanning threads, and produces the + * batches of rows, without knowing how the call that scans it was bound. It is configured with the setter functions + * (e.g. `duckdb_v2_data_source_set_exec_callback()`), and made the scan of a table function with + * `duckdb_v2_table_function_set_data_source()`, which any number of table functions can do. The COPY FROM side of a + * copy function scans with a data source in the same way (`copy_from_set_data_source`). + * + * The callbacks of a data source run when a scan executes, and receive the handles of the scan (e.g. + * `duckdb_v2_data_source_exec_info_handle`). The "bind data" they can read is the bind data of the call or statement + * that scans the data source (the table function call, or the `COPY ... FROM` statement), and the user data they can + * read is the one set with `duckdb_v2_data_source_set_user_data()`. Created with `duckdb_v2_data_source_create()`, + * destroyed with `duckdb_v2_data_source_destroy()`. + */ +typedef struct _duckdb_v2_data_source { + void *internal_ptr; +} * duckdb_v2_data_source_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a data source during the global state initialization "init + * global" phase. The "init global" callback receives this handle and can use it to e.g. set up the state shared by + * every thread scanning the data source, and to declare how many threads may scan it. + */ +typedef struct _duckdb_v2_data_source_init_global_info { + void *internal_ptr; +} * duckdb_v2_data_source_init_global_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a data source during the local state initialization "init + * local" phase. The "init local" callback receives this handle and can use it to e.g. set up worker-local state, + * typically by claiming work from the shared global state. + */ +typedef struct _duckdb_v2_data_source_init_local_info { + void *internal_ptr; +} * duckdb_v2_data_source_init_local_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a data source during the execution "exec" phase. The "exec" + * callback receives this handle and can use it to e.g. access the global and local state and write the next batch of + * rows to the output chunk. + */ +typedef struct _duckdb_v2_data_source_exec_info { + void *internal_ptr; +} * duckdb_v2_data_source_exec_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a data source during the "progress" phase. The "progress" + * callback receives this handle and can use it to report how far the scan has advanced. + */ +typedef struct _duckdb_v2_data_source_progress_info { + void *internal_ptr; +} * duckdb_v2_data_source_progress_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a data source during the "partition data" phase. The engine + * invokes the callback on the worker thread that just produced a batch of rows, once per batch, only when a downstream + * operator needs to know the batch's ordering position, the values of a set of partitioning columns, or both; the + * handle reports which of those were actually requested and receives the answer. + */ +typedef struct _duckdb_v2_data_source_partition_data_info { + void *internal_ptr; +} * duckdb_v2_data_source_partition_data_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a data source when a scanning thread claims its next batch of + * work. The "claim batch" callback receives this handle and can use it to claim the next part of the scan from the + * shared global state for the thread's local state, and to report whether it claimed one. + */ +typedef struct _duckdb_v2_data_source_claim_batch_info { + void *internal_ptr; +} * duckdb_v2_data_source_claim_batch_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a data source when the engine collects the metrics of a scan. + * The "metrics" callback receives this handle and can use it to report the operator metrics of the scan, e.g. how many + * row groups it read. + */ +typedef struct _duckdb_v2_data_source_metrics_info { + void *internal_ptr; +} * duckdb_v2_data_source_metrics_info_handle; + +/* --- Constants for data_source --- */ + +/* --- Function pointer typedefs for data_source --- */ + +typedef void (*duckdb_v2_data_source_init_global_callback_fn)(duckdb_v2_data_source_init_global_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_data_source_init_local_callback_fn)(duckdb_v2_data_source_init_local_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_data_source_exec_callback_fn)(duckdb_v2_data_source_exec_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_data_source_progress_callback_fn)(duckdb_v2_data_source_progress_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_data_source_metrics_callback_fn)(duckdb_v2_data_source_metrics_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_data_source_partition_data_callback_fn)(duckdb_v2_data_source_partition_data_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_data_source_claim_batch_callback_fn)(duckdb_v2_data_source_claim_batch_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +/* --- Functions for data_source --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional "to string" callback of the table function. + * Creates a new data source through a factory. * - * The engine invokes the callback with the bind data of a bound call when it renders a query plan that scans the - * function, e.g. for `EXPLAIN`, `EXPLAIN ANALYZE` and the profiler, both for the logical and for the physical plan. The - * callback reports what the plan shows for the scan as key-value pairs with `duckdb_v2_table_function_to_string_set()`, - * e.g. the file or the remote table it reads. Without the callback the physical plan shows the name of the function - * under the key `Function`; with it, the plan shows what the callback reports instead, so a callback that wants the - * name shown reports it itself. The engine shows the projections, filters and estimated cardinality of the scan next to - * them either way. The callback may be invoked more than once for the same bind data, and is not invoked with the - * global state of a scan, so it should only report what the bind already determined. A function wrapped in a multi-file - * function is not asked: the plan describes the multi-file scan. + * The data source starts out empty: configure it with the setter functions (e.g. + * `duckdb_v2_data_source_set_exec_callback()`), then make it the scan of a table function with + * `duckdb_v2_table_function_set_data_source()`. The caller owns the returned handle and must destroy it with + * `duckdb_v2_data_source_destroy()`, also after it has been handed to a table function. * - * With profiling enabled (including `EXPLAIN ANALYZE`), the engine also invokes the callback while the query executes, - * once per worker thread that scans the function. Calls can therefore run concurrently with the same bind data and user - * data, so the callback must not modify them without synchronization, and an error it reports there fails the query. - * Builds with assertions enabled also invoke it while executing queries without profiling. + * The data source can only be used for table functions and copy functions of the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The "to string" callback to set. + * @param factory The factory to create the data source through. + * @param source On success, receives the newly created data source. Owned by the caller. * @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_table_function_set_to_string_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_to_string_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_create(duckdb_v2_factory_handle factory, + duckdb_v2_data_source_handle *source, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Sets arbitrary user data on the data source. + * + * Associates an opaque pointer with the data source, retrievable from its callbacks via + * `duckdb_v2_data_source_init_global_get_user_data()`, `duckdb_v2_data_source_exec_get_user_data()` and their + * counterparts on the other phases. The opaque handle bundles the pointer with an optional destructor, invoked when the + * data is no longer needed. A data source without user data, or whose user data pointer is null, hands its callbacks + * the user data of the table function or copy function that scans it, if that has any. * * history: * - unstable: v2.0.0 * - * @param info The to string info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param source The data source to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. * @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_table_function_to_string_get_user_data( - duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_set_user_data(duckdb_v2_data_source_handle source, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data the function's bind callback set for the bound call being described. + * Sets the optional global init callback of the data source. + * + * The global init callback is invoked once per scan, at the start of execution. It can set "global state" shared by + * every thread scanning the data source, and declare how many threads may scan it in parallel via + * `duckdb_v2_data_source_init_global_set_max_threads()`. * * history: * - unstable: v2.0.0 * - * @param info The to string info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param source The data source to set the global init callback of. + * @param callback The global init callback to set. * @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_table_function_to_string_get_bind_data( - duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_set_init_global_callback( + duckdb_v2_data_source_handle source, duckdb_v2_data_source_init_global_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports a key-value pair the query plan shows for the scan, e.g. `File` and the path of the file it reads. The plan - * shows the pairs in the order they were first reported; setting a key again replaces its value in place. Fails with - * `ERROR_INPUT_INVALID` when the key is empty. + * Sets the optional local init callback of the data source. + * + * The local init callback is invoked once per thread that will scan the data source. It can set worker-local "local + * state", retrievable from the exec callback, typically derived from the shared global state. * * history: * - unstable: v2.0.0 * - * @param info The to string info handle. - * @param key The key. Borrowed and copied. - * @param key_length The length of `key` in bytes. `key` need not be null-terminated. - * @param value The value. Borrowed and copied. May span several lines. - * @param value_length The length of `value` in bytes. `value` need not be null-terminated and may be NULL only when - * this is 0. + * @param source The data source to set the local init callback of. + * @param callback The local init callback to set. * @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_table_function_to_string_set(duckdb_v2_table_function_to_string_info_handle info, - const char *key, idx_t key_length, - const char *value, idx_t value_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_set_init_local_callback( + duckdb_v2_data_source_handle source, duckdb_v2_data_source_init_local_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new multi-file function through a factory. - * - * The function starts out empty: give it a name with `duckdb_v2_multi_file_function_set_name()` and the single-file - * function it wraps with `duckdb_v2_multi_file_function_set_single_file_function()`, then make it available with - * `duckdb_v2_connection_register_multi_file_function()` or `duckdb_v2_extension_register_multi_file_function()`. The - * caller owns the returned handle and must destroy it with `duckdb_v2_multi_file_function_destroy()`, also after - * registration. + * Sets the exec callback of the data source. * - * The multi-file function can only be registered on the database the factory belongs to. + * The exec callback implements the scan: it is invoked repeatedly during query execution and writes the next batch of + * rows to the output chunk, until it produces an empty batch to signal the end of the scan. An exec callback must be + * set before the data source is given to a table function. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the multi-file function through. - * @param function On success, receives the newly created multi-file function. Owned by the caller. + * @param source The data source to set the exec callback of. + * @param callback The exec callback to set. * @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_multi_file_function_create(duckdb_v2_factory_handle factory, - duckdb_v2_multi_file_function_handle *function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_set_exec_callback(duckdb_v2_data_source_handle source, + duckdb_v2_data_source_exec_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the multi-file function, as SQL will call it. + * Sets the optional progress callback of the data source. * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * The progress callback is invoked on demand during execution to report how far the scan has advanced, which the engine + * surfaces as the query's progress. It is invoked concurrently with the exec callback, so it must read the global state + * in a thread-safe way. * * history: * - unstable: v2.0.0 * - * @param function The function to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this - * is 0. + * @param source The data source to set the progress callback of. + * @param callback The progress callback to set. * @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_multi_file_function_set_name(duckdb_v2_multi_file_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_set_progress_callback( + duckdb_v2_data_source_handle source, duckdb_v2_data_source_progress_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the table function that reads a single file, which the multi-file function wraps. + * Sets the optional metrics callback of the data source. * - * The single-file function must be registered before the multi-file function is, and must take the file to read as its - * only positional parameter, of type ANY. It is bound once for every file that is read, and receives the file the way a - * multi-file function takes one: as the VARCHAR path of the file when there is nothing more to know about it, and - * otherwise as a STRUCT holding the path in its `filename` field and the options to open the file with in its other - * fields - e.g. the size of the file, as a file system reported it while globbing, or the options a caller passed along - * with the file (`read_x([{'filename': 'f.x', 'file_size': 42}])`). Opening the file with those options, set with - * `duckdb_v2_file_open_options_set_value()`, lets the file system skip work it would otherwise repeat, such as asking a - * remote store for the size of the file. A single-file function that takes a VARCHAR parameter instead is still - * accepted, and only receives the path. Every named parameter the single-file function declares is also a named - * parameter of the multi-file function, forwarded to it as given. Everything that involves several files - globbing, - * lists of files, hive partitioning, the `filename` column, `union_by_name` and the like - is provided by the - * multi-file function on top of it. The name is borrowed and copied. A single-file function must be set before - * registration. + * The metrics callback is invoked when the engine collects the metrics of the scan, e.g. when profiling is enabled, and + * reports them via `duckdb_v2_data_source_metrics_set()`. * * history: * - unstable: v2.0.0 * - * @param function The function to set the single-file function of. - * @param name The name of the registered single-file table function. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this - * is 0. + * @param source The data source to set the metrics callback of. + * @param callback The metrics callback to set. * @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_multi_file_function_set_single_file_function(duckdb_v2_multi_file_function_handle function, const char *name, - idx_t name_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_set_metrics_callback( + duckdb_v2_data_source_handle source, duckdb_v2_data_source_metrics_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets how the files the function reads are referred to in messages, e.g. "Avro" or "JSON". + * Sets the optional partition data callback of the data source. * - * Optional: without it, the files are referred to by the name of the multi-file function. The name is borrowed and - * copied. + * The partition data callback is invoked on the worker thread that just produced a batch of rows, once per batch, when + * a downstream operator needs to know the ordering position of the batch or the values of a set of partitioning + * columns. A table function with a partitioning callback (see `duckdb_v2_table_function_set_partitioning_callback()`) + * requires its data source to have one. * * history: * - unstable: v2.0.0 * - * @param function The function to set the reader type of. - * @param reader_type The reader type. Borrowed and copied. - * @param reader_type_length The length of `reader_type` in bytes. `reader_type` need not be null-terminated and may be - * NULL only when this is 0. + * @param source The data source to set the partition data callback of. + * @param callback The partition data callback to set. * @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_multi_file_function_set_reader_type(duckdb_v2_multi_file_function_handle function, const char *reader_type, - idx_t reader_type_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_set_partition_data_callback( + duckdb_v2_data_source_handle source, duckdb_v2_data_source_partition_data_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the file extension of the files the function reads, e.g. "avro". + * Sets the optional claim batch callback of the data source. * - * Optional. With a file extension, a path that names a directory rather than a file reads the files with that extension - * inside it. Without one, the paths passed to the function must match at least one file. The extension is given without - * a leading dot, and is borrowed and copied. + * With a claim batch callback, a scanning thread works through the scan one batch at a time: the callback claims the + * next batch of work (e.g. the next block of a file) for the thread's local state, typically from the shared global + * state, and the exec callback then produces the rows of that batch only, leaving the output chunk empty once the batch + * is exhausted. A batch is claimed before the exec callback first runs on a thread, and again whenever the exec + * callback leaves the output chunk empty; the scan ends for a thread once the claim batch callback does not claim a + * batch. * * history: * - unstable: v2.0.0 * - * @param function The function to set the file extension of. - * @param extension The file extension, without a leading dot. Borrowed and copied. - * @param extension_length The length of `extension` in bytes. `extension` need not be null-terminated and may be NULL - * only when this is 0. + * @param source The data source to set the claim batch callback of. + * @param callback The claim batch callback to set. * @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_multi_file_function_set_file_extension(duckdb_v2_multi_file_function_handle function, const char *extension, - idx_t extension_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_set_claim_batch_callback( + duckdb_v2_data_source_handle source, duckdb_v2_data_source_claim_batch_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the multi-file function, making it available for use in SQL queries. + * Makes the scan of the table function the given data source. * - * The function is registered on the connection's database, visible to every connection, in the connection's - * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. It can then be called with the path of a single file, a glob pattern, or a list of either, and - * accepts the options every multi-file function accepts (e.g. `filename`, `hive_partitioning`, `union_by_name`) next to - * the named parameters of the single-file function. Registration requires a name and a single-file function, and fails - * when no table function by that name is registered or it does not take the path of the file to read as its only - * positional parameter (see `duckdb_v2_multi_file_function_set_single_file_function()`). The multi-file function must - * have been created through a factory of the same database. The caller still owns the handle after registration and - * must destroy it with `duckdb_v2_multi_file_function_destroy()`, which does not affect the registered function. + * A table function takes care of everything that is decided when a call is planned - it binds the call and declares the + * columns it returns, and pushes projections and filters down - and scans with a data source: the callbacks that set up + * the scan at execution time and produce its rows. A table function has no scan callbacks of its own, so a data source + * must be set before the function is registered. The function keeps a copy of the data source as it is when this is + * called, so the same data source can be given to any number of functions, and changing it afterwards does not change + * them. + * + * The callbacks of the data source read the bind data the bind callback of the function sets, and the user data of the + * data source or, if it has none or its pointer is null, the user data of the function. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param function The multi-file function to register. + * @param function The function to set the data source of. + * @param data_source The data source to scan with. Borrowed; it can be destroyed after this call. * @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_register_multi_file_function( - duckdb_v2_connection_handle conn, duckdb_v2_multi_file_function_handle function, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_data_source(duckdb_v2_table_function_handle function, + duckdb_v2_data_source_handle data_source, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the multi-file function, making it available for use in SQL queries. + * Destroys the data source, releasing its resources. * - * The function is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. It can then be called with the path of a single file, a glob pattern, or a list of either, - * and accepts the options every multi-file function accepts (e.g. `filename`, `hive_partitioning`, `union_by_name`) - * next to the named parameters of the single-file function. Registration requires a name and a single-file function, - * and fails when no table function by that name is registered or it does not take the path of the file to read as its - * only positional parameter (see `duckdb_v2_multi_file_function_set_single_file_function()`). The multi-file function - * must have been created through a factory of the same database. The caller still owns the handle after registration - * and must destroy it with `duckdb_v2_multi_file_function_destroy()`, which does not affect the registered function. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after it was given to a table function does not affect that table function, + * which keeps a copy of the data source as it was. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The multi-file function to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param source The data source to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_multi_file_function( - duckdb_v2_extension_handle extension, duckdb_v2_multi_file_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_destroy(duckdb_v2_data_source_handle *source); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the multi-file function, releasing its resources. - * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered function. + * Retrieves the user data set via `duckdb_v2_data_source_set_user_data()`, or the user data of the table function or + * copy function that scans it when the data source has none or its pointer is null. * * history: * - unstable: v2.0.0 * - * @param function The function to destroy. + * @param info The global init info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_multi_file_function_destroy(duckdb_v2_multi_file_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_init_global_get_user_data( + duckdb_v2_data_source_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for table --- */ - -/* ============================================================================ - * MODULE: value - * ============================================================================ */ - -/* --- Enums for value --- */ - -/* --- Struct forward declarations for value --- */ - -/* --- Types for value --- */ - -/* --- Constants for value --- */ - -/* --- Function pointer typedefs for value --- */ - -/* --- Functions for value --- */ - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a value handle. - * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. On success the slot is set to nullptr. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param value The value to destroy. + * @param info The global init info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_destroy(duckdb_v2_value_handle *value); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_init_global_get_bind_data( + duckdb_v2_data_source_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a BOOLEAN. + * Sets the function's "global state" from the global init callback. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The global state lives for the duration of the scan and is retrievable from the local init, exec and progress + * callbacks. Every thread scanning the function shares it, so the function must synchronize its own access to it. The + * opaque handle bundles the pointer with an optional destructor, invoked when the scan is done with the state. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a bool. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The global init info handle. + * @param data Opaque handle bundling the global state pointer plus an optional destructor. + * @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_value_get_bool(duckdb_v2_value_handle value, bool *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_init_global_set_global_state( + duckdb_v2_data_source_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a UTINYINT. + * Sets how many threads may scan the function in parallel. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Defaults to 1, a single-threaded scan. The engine creates at most this many local states, and therefore runs at most + * this many exec callbacks concurrently. It is an upper bound, not a request: the engine may use fewer threads. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a uint8_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The global init info handle. + * @param max_threads The maximum number of threads. Must be at least 1. + * @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_value_get_utinyint(duckdb_v2_value_handle value, uint8_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_init_global_set_max_threads( + duckdb_v2_data_source_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a USMALLINT. + * Returns the number of columns the scan produces. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * With projection pushdown (see `duckdb_v2_table_function_set_projection_pushdown()`) this is the number of columns the + * query uses, which is the number of vectors in the exec callback's output chunk; without it, it is the number of + * columns declared in bind. Valid indices for `duckdb_v2_data_source_init_global_get_column_index()` are `0` up to (but + * excluding) this count. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a uint16_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The global init info handle. + * @param count Receives the number of columns the scan produces. + * @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_value_get_usmallint(duckdb_v2_value_handle value, uint16_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_init_global_get_column_count( + duckdb_v2_data_source_init_global_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a UINTEGER. + * Returns which declared column the scan's column at the given index stands for. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration + * order: the exec callback fills the output chunk's vector at `index` with that column's data. Without projection + * pushdown the mapping is the identity. Fails if the index is out of bounds. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a uint32_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The global init info handle. + * @param index The index of the column in the scan's output. + * @param column_index Receives the index of the declared column. + * @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_value_get_uint(duckdb_v2_value_handle value, uint32_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_data_source_init_global_get_column_index(duckdb_v2_data_source_init_global_info_handle info, idx_t index, + idx_t *column_index, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a UBIGINT. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Retrieves the user data set via `duckdb_v2_data_source_set_user_data()`, or the user data of the table function or + * copy function that scans it when the data source has none or its pointer is null. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a uint64_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The local init info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_get_ubigint(duckdb_v2_value_handle value, uint64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_init_local_get_user_data( + duckdb_v2_data_source_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a UHUGEINT. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a uint128_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The local init info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_get_uhugeint(duckdb_v2_value_handle value, duckdb_v2_uhugeint_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_init_local_get_bind_data( + duckdb_v2_data_source_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TINYINT. + * Retrieves the global state set by the function's global init callback. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Shared with every other thread scanning the function; access to it must be synchronized by the function. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as an int8_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The local init info handle. + * @param data Receives the global state pointer, or null if none was set. + * @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_value_get_tinyint(duckdb_v2_value_handle value, int8_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_init_local_get_global_state( + duckdb_v2_data_source_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a SMALLINT. + * Sets the function's worker-local "local state" from the local init callback. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The local state is associated with the executing thread for the duration of the scan and retrievable from the exec + * callback via `duckdb_v2_data_source_exec_get_local_state()`. No other thread observes it, so it needs no + * synchronization. The opaque handle bundles the pointer with an optional destructor, invoked when the local state is + * no longer needed. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as an int16_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The local init info handle. + * @param data Opaque handle bundling the local state pointer plus an optional destructor. + * @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_value_get_smallint(duckdb_v2_value_handle value, int16_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_init_local_set_local_state( + duckdb_v2_data_source_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as an INTEGER. + * Returns the number of columns the scan produces. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * With projection pushdown (see `duckdb_v2_table_function_set_projection_pushdown()`) this is the number of columns the + * query uses, which is the number of vectors in the exec callback's output chunk; without it, it is the number of + * columns declared in bind. Valid indices for `duckdb_v2_data_source_init_local_get_column_index()` are `0` up to (but + * excluding) this count. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as an int32_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The local init info handle. + * @param count Receives the number of columns the scan produces. + * @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_value_get_int(duckdb_v2_value_handle value, int32_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_init_local_get_column_count( + duckdb_v2_data_source_init_local_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a BIGINT. + * Returns which declared column the scan's column at the given index stands for. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration + * order: the exec callback fills the output chunk's vector at `index` with that column's data. Without projection + * pushdown the mapping is the identity. Fails if the index is out of bounds. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as an int64_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The local init info handle. + * @param index The index of the column in the scan's output. + * @param column_index Receives the index of the declared column. + * @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_value_get_bigint(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_data_source_init_local_get_column_index(duckdb_v2_data_source_init_local_info_handle info, idx_t index, + idx_t *column_index, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a HUGEINT. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Retrieves the user data set via `duckdb_v2_data_source_set_user_data()`, or the user data of the table function or + * copy function that scans it when the data source has none or its pointer is null. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as an int128_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_get_hugeint(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_user_data(duckdb_v2_data_source_exec_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a VARCHAR. - * - * The string is borrowed from the value and stays valid until the value is destroyed. That borrow is why this getter - * does not convert: a converted copy would not outlive the call. A value of any other type id, and a NULL value, return - * ERROR_INPUT_INVALID. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a UTF-8 string. The returned string is borrowed and valid until the value handle - * is destroyed. - * @param out_length Receives the length of `*out` in bytes. `*out` is not guaranteed to be null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_get_varchar(duckdb_v2_value_handle value, const char **out, - idx_t *out_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_bind_data(duckdb_v2_data_source_exec_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a byte string: a BLOB, or the storage bytes of a BIT, a BIGNUM, or a DECIMAL wider than 38 - * digits (the BIGNUM storage of its unscaled value, for bignum_decode). + * Retrieves the global state set by the function's global init callback. * - * The string is borrowed from the value and stays valid until the value is destroyed. That borrow is why this getter - * does not convert: a converted copy would not outlive the call. A value of any other type id, and a NULL value, return - * ERROR_INPUT_INVALID. + * Shared with every other thread scanning the function; access to it must be synchronized by the function. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a byte string. The returned string is borrowed and valid until the value handle is - * destroyed. - * @param out_length Receives the length of `*out` in bytes. `*out` is not guaranteed to be null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param data Receives the global state pointer, or null if none was set. + * @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_value_get_blob(duckdb_v2_value_handle value, const char **out, idx_t *out_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_global_state(duckdb_v2_data_source_exec_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a FLOAT. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Retrieves the worker-local local state set by the function's local init callback. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a float. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param data Receives the local state pointer for the executing thread, or null if none was set. + * @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_value_get_float(duckdb_v2_value_handle value, float *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_local_state(duckdb_v2_data_source_exec_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a DOUBLE. + * Retrieves the output chunk the exec callback must write the next batch of rows into. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The chunk holds one vector per column declared with `duckdb_v2_table_function_bind_add_result_column()`, in the same + * order; reach them with `duckdb_v2_data_chunk_get_vector()`. The chunk starts out empty on every invocation: write the + * rows, then declare how many there are with `duckdb_v2_vector_set_size()` on the first vector, which the engine takes + * as the batch's row count and propagates to the other vectors. Producing an empty batch signals the end of the scan, + * after which the callback is not invoked again on that thread. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a double. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param chunk Receives the borrowed output chunk to write into. + * @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_value_get_double(duckdb_v2_value_handle value, double *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_output_chunk(duckdb_v2_data_source_exec_info_handle info, + duckdb_v2_data_chunk_handle *chunk, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a DATE. - * - * The payload is days since 1970-01-01, the same unit a vector of this type exposes. + * Returns the number of columns the scan produces. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * With projection pushdown (see `duckdb_v2_table_function_set_projection_pushdown()`) this is the number of columns the + * query uses, which is the number of vectors in the exec callback's output chunk; without it, it is the number of + * columns declared in bind. Valid indices for `duckdb_v2_data_source_exec_get_column_index()` are `0` up to (but + * excluding) this count. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param count Receives the number of columns the scan produces. + * @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_value_get_date(duckdb_v2_value_handle value, int32_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_column_count(duckdb_v2_data_source_exec_info_handle info, + idx_t *count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIME. - * - * The payload is microseconds since midnight, the same unit a vector of this type exposes. + * Returns which declared column the scan's column at the given index stands for. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration + * order: the exec callback fills the output chunk's vector at `index` with that column's data. Without projection + * pushdown the mapping is the identity. Fails if the index is out of bounds. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param index The index of the column in the scan's output. + * @param column_index Receives the index of the declared column. + * @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_value_get_time(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_column_index(duckdb_v2_data_source_exec_info_handle info, + idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIME_NS. - * - * The payload is nanoseconds since midnight, the same unit a vector of this type exposes. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Retrieves the user data set via `duckdb_v2_data_source_set_user_data()`, or the user data of the table function or + * copy function that scans it when the data source has none or its pointer is null. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The progress info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_get_time_ns(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_progress_get_user_data( + duckdb_v2_data_source_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIME_TZ. - * - * The payload packs the time of day and the UTC offset into one integer, in the committed layout: micros in the high 40 - * bits, a biased offset in the low 24. The same form a vector of this type exposes. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The progress info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_get_time_tz(duckdb_v2_value_handle value, uint64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_progress_get_bind_data( + duckdb_v2_data_source_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP. - * - * The payload is microseconds since 1970-01-01, the same unit a vector of this type exposes. + * Retrieves the global state set by the function's global init callback. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The progress callback runs concurrently with the exec callbacks scanning the function, so it must read the global + * state in a thread-safe way. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The progress info handle. + * @param data Receives the global state pointer, or null if none was set. + * @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_value_get_timestamp(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_progress_get_global_state( + duckdb_v2_data_source_progress_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP_SEC. - * - * The payload is seconds since 1970-01-01, the same unit a vector of this type exposes. + * Reports how far the scan has advanced. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * A fraction between 0.0 (nothing scanned yet) and 1.0 (done); values outside that range are clamped. A progress + * callback that returns without calling this reports no progress. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The progress info handle. + * @param progress The fraction of the scan that is complete, in [0.0, 1.0]. + * @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_value_get_timestamp_sec(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_progress_set_progress( + duckdb_v2_data_source_progress_info_handle info, double progress, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP_MS. - * - * The payload is milliseconds since 1970-01-01, the same unit a vector of this type exposes. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Retrieves the user data set via `duckdb_v2_data_source_set_user_data()`, or the user data of the table function or + * copy function that scans it when the data source has none or its pointer is null. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partition data info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_get_timestamp_ms(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_partition_data_get_user_data( + duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP_NS. - * - * The payload is nanoseconds since 1970-01-01, the same unit a vector of this type exposes. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partition data info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_get_timestamp_ns(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_partition_data_get_bind_data( + duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP_TZ. - * - * The payload is microseconds since 1970-01-01, in UTC, the same unit a vector of this type exposes. + * Retrieves the global state set by the function's global init callback. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Shared with every other thread scanning the function; access to it must be synchronized by the function. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partition data info handle. + * @param data Receives the global state pointer, or null if none was set. + * @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_value_get_timestamp_tz(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_partition_data_get_global_state( + duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP_TZ_NS. - * - * The payload is nanoseconds since 1970-01-01, in UTC, the same unit a vector of this type exposes. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Retrieves the worker-local local state set by the function's local init callback, for the thread that produced the + * batch this call reports on. No other thread observes it, so it needs no synchronization. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partition data info handle. + * @param data Receives the local state pointer, or null if none was set. + * @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_value_get_timestamp_tz_ns(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_partition_data_get_local_state( + duckdb_v2_data_source_partition_data_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as an INTERVAL. - * - * The payload is the (months, days, micros) triple, the same unit a vector of this type exposes. + * Returns whether a downstream operator needs this batch's ordering position. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * `duckdb_v2_data_source_partition_data_set_batch_index()` must still be called even when this is false: the engine + * validates the reported value regardless of whether it is actually used for ordering, so `0` is always a safe answer + * when this reports false. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partition data info handle. + * @param required Receives whether a batch index is required. + * @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_value_get_interval(duckdb_v2_value_handle value, duckdb_v2_interval_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_partition_data_requires_batch_index( + duckdb_v2_data_source_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a UUID, in its internal 128-bit form. + * Returns whether a downstream operator needs this batch's values for a set of partitioning columns. * - * The dual of value_create_uuid: the storage form a vector element holds, with the high bit flipped so the integer - * sorts, rather than the canonical byte order. A value of any other type id, and a NULL value, return - * ERROR_INPUT_INVALID. + * When true, call `duckdb_v2_data_source_partition_data_set_partition_value()` once for every index in `[0, count)`, + * where `count` comes from `duckdb_v2_data_source_partition_data_get_partition_column_count()`. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the internal 128-bit storage form. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partition data info handle. + * @param required Receives whether partitioning column values are required. + * @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_value_get_uuid(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_partition_data_requires_partition_columns( + duckdb_v2_data_source_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a DECIMAL: its backing integer plus the width and scale of its type. + * Returns the number of partitioning columns a downstream operator is requesting values for. * - * The integer is the value scaled by 10^scale — the dual of value_create_decimal — widened to 128 bits from whatever - * 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, 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). + * `0` when `duckdb_v2_data_source_partition_data_requires_partition_columns()` is false. Valid indices for + * `duckdb_v2_data_source_partition_data_get_partition_column_index()` and + * `duckdb_v2_data_source_partition_data_set_partition_value()` are `0` up to (but excluding) this count. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the backing integer, scaled by 10^scale. - * @param out_width Receives the total digit count of the value's type. - * @param out_scale Receives the digits after the decimal point. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partition data info handle. + * @param count Receives the number of requested partitioning columns. + * @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_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_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_partition_data_get_partition_column_count( + duckdb_v2_data_source_partition_data_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Unwraps the logical type carried by a TYPE value. + * Returns which declared column the requested partitioning column at the given index stands for. * - * Returns ERROR_INPUT_INVALID unless the value is a non-NULL TYPE value. The returned logical type is caller-owned and - * must be destroyed via logical_type_destroy. + * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration + * order. Fails if the index is out of bounds. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out_type Receives the owned logical type. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partition data info handle. + * @param index The index of the requested partitioning column. + * @param column_index Receives the index of the declared column. + * @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_value_get_type(duckdb_v2_value_handle value, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_partition_data_get_partition_column_index( + duckdb_v2_data_source_partition_data_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a NULL value of the given logical type. + * Reports the ordering position of the batch the exec callback just produced. * - * The logical type is borrowed and copied into the value, so the caller can destroy it independently. + * Required on every call, whether or not `duckdb_v2_data_source_partition_data_requires_batch_index()` is true: the + * engine validates the reported value regardless. Not calling this before the callback returns fails the query; `0` is + * always a safe answer when the batch index is not actually required. Must not decrease across successive calls on the + * same thread, must be unique across threads for the ordering to be meaningful, must be less than roughly `10^13`, and, + * when partitioning column values are also being reported, must change whenever those values change: the engine only + * re-reads them when the batch index changes, so reporting a new value under an unchanged batch index is treated as a + * caller error rather than applied. Fails with `ERROR_INPUT_INVALID` for an out-of-range value; a decreasing value or + * an unchanged value paired with changed partitioning columns fails the query once the callback returns. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param type The borrowed logical type to attach to the NULL value. - * @param out_value Receives the new NULL value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partition data info handle. + * @param batch_index The batch's ordering position. + * @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_value_create_null(duckdb_v2_factory_handle factory, - duckdb_v2_logical_type_handle type, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_partition_data_set_batch_index( + duckdb_v2_data_source_partition_data_info_handle info, idx_t batch_index, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a BOOLEAN value from a bool. + * Reports the single value of the partitioning column at the given index, for the batch the exec callback just + * produced. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Every partition reported this way carries exactly one distinct value for the column, so the value serves as both the + * minimum and maximum of the partition's range. The value is borrowed and copied, and must be of the declared type of + * the corresponding result column. Required once for every index in `[0, + * `duckdb_v2_data_source_partition_data_get_partition_column_count()`)` before the callback returns; calling it again + * for the same index overwrites the previous value. The reported value only takes effect together with a changed + * `duckdb_v2_data_source_partition_data_set_batch_index()`: reporting a different value under an unchanged batch index + * fails the query once the callback returns. Fails with `ERROR_INPUT_INVALID` when the index is out of bounds or the + * value's type does not match. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The bool to wrap. - * @param out_value Receives the new BOOLEAN value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partition data info handle. + * @param index The index of the partitioning column being reported. + * @param value The single value of the partitioning column. Borrowed and copied. + * @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_value_create_bool(duckdb_v2_factory_handle factory, bool in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_partition_data_set_partition_value( + duckdb_v2_data_source_partition_data_info_handle info, idx_t index, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a UTINYINT value from a uint8_t. - * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the user data set via `duckdb_v2_data_source_set_user_data()`, or the user data of the table function or + * copy function that scans it when the data source has none or its pointer is null. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The uint8_t to wrap. - * @param out_value Receives the new UTINYINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The metrics info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_create_utinyint(duckdb_v2_factory_handle factory, uint8_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_metrics_get_user_data(duckdb_v2_data_source_metrics_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a USMALLINT value from a uint16_t. - * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The uint16_t to wrap. - * @param out_value Receives the new USMALLINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The metrics info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_create_usmallint(duckdb_v2_factory_handle factory, uint16_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_metrics_get_bind_data(duckdb_v2_data_source_metrics_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a UINTEGER value from a uint32_t. + * Retrieves the global state set by the function's global init callback. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * The metrics callback can run while the scan is still running, so it must read the global state in a thread-safe way. + * The global state is null if the scan has not been initialized. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The uint32_t to wrap. - * @param out_value Receives the new UINTEGER 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_uint(duckdb_v2_factory_handle factory, uint32_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); + * @param info The metrics info handle. + * @param data Receives the global state pointer, or null if none was set. + * @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_data_source_metrics_get_global_state( + duckdb_v2_data_source_metrics_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a UBIGINT value from a uint64_t. + * Reports an operator metric of the scan, by the name DuckDB's profiler uses for it (the names `tracked_metrics` + * accepts). * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * The metrics a scan can report are counters: + * - `operator.rows_scanned`: the rows the scan read. + * - `operator.row_groups_scanned`: the row groups the scan read. A row group is the unit a format lets the scan skip, + * e.g. a Parquet row group or an ORC stripe. + * - `operator.total_row_groups_to_scan`: the row groups the scan read or skipped. + * - `operator.bytes_scanned`: the bytes the scan read. + * + * The engine may collect the metrics of a scan more than once, and adds up what it is told: each value is the amount + * since the metrics were last collected, except `operator.total_row_groups_to_scan`, which is the number found so far + * in all. Fails for a name that is not one of the above. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The uint64_t to wrap. - * @param out_value Receives the new UBIGINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The metrics info handle. + * @param name The name of the metric. Borrowed. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8 and need not be null-terminated. + * @param value The value of the metric. + * @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_value_create_ubigint(duckdb_v2_factory_handle factory, uint64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_metrics_set(duckdb_v2_data_source_metrics_info_handle info, + const char *name, idx_t name_length, uint64_t value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a UHUGEINT value from a uint128_t. - * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the user data set via `duckdb_v2_data_source_set_user_data()`, or the user data of the table function or + * copy function that scans it when the data source has none or its pointer is null. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The uint128_t to wrap. - * @param out_value Receives the new UHUGEINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The claim batch info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_create_uhugeint(duckdb_v2_factory_handle factory, - const duckdb_v2_uhugeint_t *in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_claim_batch_get_user_data( + duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TINYINT value from an int8_t. - * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The int8_t to wrap. - * @param out_value Receives the new TINYINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The claim batch info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_create_tinyint(duckdb_v2_factory_handle factory, int8_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_claim_batch_get_bind_data( + duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a SMALLINT value from an int16_t. + * Retrieves the global state set by the function's global init callback. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Shared with every other thread scanning the function; access to it must be synchronized by the function. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The int16_t to wrap. - * @param out_value Receives the new SMALLINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The claim batch info handle. + * @param data Receives the global state pointer, or null if none was set. + * @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_value_create_smallint(duckdb_v2_factory_handle factory, int16_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_claim_batch_get_global_state( + duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates an INTEGER value from an int32_t. - * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the local state set by the function's local init callback, for the thread claiming a batch. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The int32_t to wrap. - * @param out_value Receives the new INTEGER value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The claim batch info handle. + * @param data Receives the local state pointer for the claiming thread, or null if none was set. + * @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_value_create_int(duckdb_v2_factory_handle factory, int32_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_claim_batch_get_local_state( + duckdb_v2_data_source_claim_batch_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a BIGINT value from an int64_t. + * Reports whether the callback claimed a batch for the thread. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * A callback that returns without calling this claimed nothing, which ends the scan for the thread. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The int64_t to wrap. - * @param out_value Receives the new BIGINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The claim batch info handle. + * @param claimed Whether a batch was claimed. + * @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_value_create_bigint(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_claim_batch_set_claimed( + duckdb_v2_data_source_claim_batch_info_handle info, bool claimed, duckdb_v2_error_info_handle *err); #endif +/* --- Struct definitions for data_source --- */ + +/* ============================================================================ + * MODULE: copy + * ============================================================================ */ + +/* --- Enums for copy --- */ + +/* --- Struct forward declarations for copy --- */ + +/* --- Types for copy --- */ + +/*! + * An owned opaque handle to a custom copy function being built: an output format for `COPY ... TO`, an input format for + * `COPY ... FROM`, or both. Created with `duckdb_v2_copy_function_create()`, configured with the setter functions (e.g. + * `duckdb_v2_copy_function_set_name()`, `duckdb_v2_copy_to_set_batch_callback()`, + * `duckdb_v2_copy_from_set_data_source()`, etc.), made available with `duckdb_v2_connection_register_copy_function()` + * or `duckdb_v2_extension_register_copy_function()`, and destroyed with `duckdb_v2_copy_function_destroy()`. + */ +typedef struct _duckdb_v2_copy_function { + void *internal_ptr; +} * duckdb_v2_copy_function_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a copy function during the query preparation "bind" phase of a + * `COPY ... TO` statement. The "bind" callback receives this handle and can use it to e.g. inspect the names and types + * of the columns being written, read the statement's options and initialize some constant state. + */ +typedef struct _duckdb_v2_copy_to_bind_info { + void *internal_ptr; +} * duckdb_v2_copy_to_bind_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a copy function during the "batch size" phase of a `COPY ... + * TO` statement. The "batch size" callback receives this handle and must use it to report how many rows a batch should + * carry. + */ +typedef struct _duckdb_v2_copy_to_batch_size_info { + void *internal_ptr; +} * duckdb_v2_copy_to_batch_size_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a copy function during the per-file "init" phase of a `COPY ... + * TO` statement. The "init" callback receives this handle and can use it to e.g. read the path of the file being + * written and set up the state shared by every batch written to that file. + */ +typedef struct _duckdb_v2_copy_to_init_info { + void *internal_ptr; +} * duckdb_v2_copy_to_init_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a copy function during the "batch" phase of a `COPY ... TO` + * statement. The "batch" callback receives this handle and can use it to take ownership of the rows of the batch and to + * set the prepared form of the batch handed to the "flush" callback. + */ +typedef struct _duckdb_v2_copy_to_batch_info { + void *internal_ptr; +} * duckdb_v2_copy_to_batch_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a copy function during the "flush" phase of a `COPY ... TO` + * statement. The "flush" callback receives this handle and can use it to access the prepared batch and write it to the + * output. + */ +typedef struct _duckdb_v2_copy_to_flush_info { + void *internal_ptr; +} * duckdb_v2_copy_to_flush_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a copy function during the per-file "finalize" phase of a `COPY + * ... TO` statement. The "finalize" callback receives this handle and can use it to e.g. close the file after every + * batch has been flushed to it. + */ +typedef struct _duckdb_v2_copy_to_finalize_info { + void *internal_ptr; +} * duckdb_v2_copy_to_finalize_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a copy function when a `COPY ... TO` statement reports + * statistics about the files it wrote (e.g. with `RETURN_STATS`). The "statistics" callback receives this handle and + * uses it to report the statistics of one written file. + */ +typedef struct _duckdb_v2_copy_to_statistics_info { + void *internal_ptr; +} * duckdb_v2_copy_to_statistics_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to a copy function during the query preparation "bind" phase of a + * `COPY ... FROM` statement. The "bind" callback receives this handle and can use it to e.g. read the path of the file + * to read, inspect the names and types of the columns the target table expects, read the statement's options, hint at + * the number of rows the read will produce and initialize some constant state. + */ +typedef struct _duckdb_v2_copy_from_bind_info { + void *internal_ptr; +} * duckdb_v2_copy_from_bind_info_handle; + +/* --- Constants for copy --- */ + +/* --- Function pointer typedefs for copy --- */ + +typedef void (*duckdb_v2_copy_to_bind_callback_fn)(duckdb_v2_copy_to_bind_info_handle info, + duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_copy_to_batch_size_callback_fn)(duckdb_v2_copy_to_batch_size_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_copy_to_init_callback_fn)(duckdb_v2_copy_to_init_info_handle info, + duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_copy_to_batch_callback_fn)(duckdb_v2_copy_to_batch_info_handle info, + duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_copy_to_flush_callback_fn)(duckdb_v2_copy_to_flush_info_handle info, + duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_copy_to_finalize_callback_fn)(duckdb_v2_copy_to_finalize_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_copy_to_statistics_callback_fn)(duckdb_v2_copy_to_statistics_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_copy_from_bind_callback_fn)(duckdb_v2_copy_from_bind_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +/* --- Functions for copy --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a HUGEINT value from an int128_t. + * Creates a new copy function through a factory. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * A copy function implements a file format for `COPY`: once registered, SQL reaches it with `COPY ... TO 'path' (FORMAT + * name)` and `COPY table FROM 'path' (FORMAT name)`. The function starts out empty: configure it with the setter + * functions (e.g. `duckdb_v2_copy_function_set_name()`, the `copy_to_set_*` callbacks for writing, the + * `copy_from_set_*` callbacks for reading, or both), then make it available with + * `duckdb_v2_connection_register_copy_function()` or `duckdb_v2_extension_register_copy_function()`. The caller owns + * the returned handle and must destroy it with `duckdb_v2_copy_function_destroy()`, also after registration. + * + * The copy function can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The int128_t to wrap. - * @param out_value Receives the new HUGEINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param factory The factory to create the copy function through. + * @param function On success, receives the newly created copy function. Owned by the caller. + * @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_value_create_hugeint(duckdb_v2_factory_handle factory, - const duckdb_v2_hugeint_t *in_value, - duckdb_v2_value_handle *out_value, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_copy_function_handle *function, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a VARCHAR value from a UTF-8 string. + * Sets the name of the copy function. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * The name is the format SQL selects the function with: `COPY ... TO 'path' (FORMAT name)` or `COPY table FROM 'path' + * (FORMAT name)`. It is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The UTF-8 string to wrap. - * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only - * when this is 0. - * @param out_value Receives the new VARCHAR value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @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_value_create_varchar(duckdb_v2_factory_handle factory, const char *in_value, - idx_t in_value_length, duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_set_name(duckdb_v2_copy_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a BLOB value from a byte string. + * Sets the file extension of the files the copy function writes, without the leading dot, e.g. `parquet`. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * DuckDB uses it when it names files itself, e.g. the files of `COPY ... TO 'dir' (PARTITION_BY ...)` or + * `(PER_THREAD_OUTPUT)`. A statement can override it with the `FILE_EXTENSION` option. An extension starting with a dot + * is rejected. The extension is borrowed and copied. Calling this again replaces the previous extension. Optional, but + * without it the names DuckDB gives files end in a bare dot, e.g. `data_0.`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The byte string to wrap. - * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only - * when this is 0. - * @param out_value Receives the new BLOB value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the file extension of. + * @param extension The extension to set, without the leading dot. Borrowed and copied. + * @param extension_length The length of `extension` in bytes. `extension` need not be null-terminated and may be NULL + * only when this is 0. + * @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_value_create_blob(duckdb_v2_factory_handle factory, const char *in_value, - idx_t in_value_length, duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_set_file_extension(duckdb_v2_copy_function_handle function, + const char *extension, idx_t extension_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a FLOAT value from a float. + * Sets arbitrary user data on the copy function. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Associates an opaque pointer with the function, retrievable from each callback of either side via its user data + * accessor (e.g. `duckdb_v2_copy_to_bind_get_user_data()`, `duckdb_v2_data_source_exec_get_user_data()`, etc.). The + * opaque handle bundles the pointer with an optional destructor, invoked when the data is no longer needed. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The float to wrap. - * @param out_value Receives the new FLOAT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @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_value_create_float(duckdb_v2_factory_handle factory, float in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_set_user_data(duckdb_v2_copy_function_handle function, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a DOUBLE value from a double. + * Sets the optional bind callback of the `COPY ... TO` side. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * The bind callback is invoked during query planning for each `COPY ... TO` statement that uses the function. It can + * inspect the names and types of the columns being written, read the statement's options and set "bind data" that is + * shared with the other `COPY ... TO` callbacks. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The double to wrap. - * @param out_value Receives the new DOUBLE value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the callback of. + * @param callback The callback to set. + * @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_value_create_double(duckdb_v2_factory_handle factory, double in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_set_bind_callback(duckdb_v2_copy_function_handle function, + duckdb_v2_copy_to_bind_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TYPE value from a logical type. + * Sets the optional batch size callback of the `COPY ... TO` side. * - * The logical type is borrowed and copied into the value, so the caller can destroy it independently. + * The batch size callback is invoked during query planning, after the bind callback, for each `COPY ... TO` statement + * that does not set `BATCH_SIZE` itself. It should report how many rows a batch should carry via + * `duckdb_v2_copy_to_batch_size_set_target()`; the engine then cuts the rows being written into batches of that size + * and hands each to the batch callback. Without a batch size from either the statement or the callback, a batch is cut + * for every chunk of rows sunk, i.e. a vector at a time. A batch may still be smaller than the reported size (the last + * one of a file, or when `BATCH_SIZE_BYTES` cuts it first). * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_type The borrowed logical type to wrap. - * @param out_value Receives the new TYPE value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the callback of. + * @param callback The callback to set. + * @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_value_create_type(duckdb_v2_factory_handle factory, - duckdb_v2_logical_type_handle in_type, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_set_batch_size_callback( + duckdb_v2_copy_function_handle function, duckdb_v2_copy_to_batch_size_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a DATE value. + * Sets the optional init callback of the `COPY ... TO` side. * - * The payload is days since 1970-01-01, the same unit value_get_date reports. It is not range-checked here; value_cast - * is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * The init callback is invoked once per output file, before any batch destined for that file is prepared. It can read + * the path of the file via `duckdb_v2_copy_to_init_get_file_path()` and set "init data" that is shared with the batch, + * flush and finalize callbacks of that file. A statement may write several files, e.g. when its output is partitioned; + * each gets its own init data. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new DATE value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the callback of. + * @param callback The callback to set. + * @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_value_create_date(duckdb_v2_factory_handle factory, int32_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_set_init_callback(duckdb_v2_copy_function_handle function, + duckdb_v2_copy_to_init_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIME value. + * Sets the batch callback of the `COPY ... TO` side. * - * The payload is microseconds since midnight, the same unit value_get_time reports. It is not range-checked here; - * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * The batch callback is invoked during query execution with a batch of the rows being written, taken via + * `duckdb_v2_copy_to_batch_take_input()`. It prepares the batch for writing, e.g. by encoding it into the output + * format, and sets "batch data" via `duckdb_v2_copy_to_batch_set_batch_data()` that is handed to the flush callback. + * Batches may be prepared by several threads at once, so the callback must synchronize its own access to the init data. + * A batch callback must be set for the `COPY ... TO` side to be registered. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIME value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the callback of. + * @param callback The callback to set. + * @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_value_create_time(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_set_batch_callback(duckdb_v2_copy_function_handle function, + duckdb_v2_copy_to_batch_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIME_NS value. + * Sets the flush callback of the `COPY ... TO` side. * - * The payload is nanoseconds since midnight, the same unit value_get_time_ns reports. It is not range-checked here; - * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * The flush callback is invoked once per prepared batch to write its batch data, available via + * `duckdb_v2_copy_to_flush_get_batch_data()`, to the output. Flushes of the same file never run concurrently. A flush + * callback must be set for the `COPY ... TO` side to be registered. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIME_NS value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the callback of. + * @param callback The callback to set. + * @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_value_create_time_ns(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_set_flush_callback(duckdb_v2_copy_function_handle function, + duckdb_v2_copy_to_flush_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIME_TZ value. + * Sets the optional finalize callback of the `COPY ... TO` side. * - * The payload packs the time of day and the UTC offset into one integer, in the committed layout: micros in the high 40 - * bits, a biased offset in the low 24. The same form value_get_time_tz reports. It is not range-checked here; - * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * The finalize callback is invoked once per output file after the last batch destined for that file has been flushed. + * It can e.g. write a footer and close the file. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIME_TZ value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the callback of. + * @param callback The callback to set. + * @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_value_create_time_tz(duckdb_v2_factory_handle factory, uint64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_set_finalize_callback(duckdb_v2_copy_function_handle function, + duckdb_v2_copy_to_finalize_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP value. - * - * The payload is microseconds since 1970-01-01, the same unit value_get_timestamp reports. It is not range-checked - * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_create_timestamp(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_user_data(duckdb_v2_copy_to_bind_info_handle info, void **data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP_SEC value. + * Sets the function's "bind data" from the bind callback. * - * The payload is seconds since 1970-01-01, the same unit value_get_timestamp_sec reports. It is not range-checked here; - * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * The bind data is stored with the bound statement and retrievable from the other callbacks of the same side. The + * opaque handle bundles the pointer with an optional destructor, invoked when the bind data is no longer needed, and an + * optional equality callback used when comparing two bound statements; without one, pointer equality is used. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP_SEC value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param data Opaque handle bundling the bind data pointer plus optional destructor and equality callbacks. + * @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_value_create_timestamp_sec(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_set_bind_data(duckdb_v2_copy_to_bind_info_handle info, + duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP_MS value. + * Retrieves the path the `COPY ... TO` statement writes to, as written in the statement. * - * The payload is milliseconds since 1970-01-01, the same unit value_get_timestamp_ms reports. It is not range-checked - * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * This is the target before the engine's own rewrites: the path of each file actually being written, e.g. a temporary + * name or a per-partition path, is only known to the init callback via `duckdb_v2_copy_to_init_get_file_path()`. The + * path is borrowed and valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP_MS value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param path Receives a borrowed pointer to the file path. Valid only for the duration of the callback. + * @param path_length Receives the length of `*path` in bytes. `*path` is not guaranteed to be null-terminated. + * @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_value_create_timestamp_ms(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_file_path(duckdb_v2_copy_to_bind_info_handle info, + const char **path, idx_t *path_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP_NS value. + * Returns the number of columns being written, i.e. the columns of the rows every batch carries. * - * The payload is nanoseconds since 1970-01-01, the same unit value_get_timestamp_ns reports. It is not range-checked - * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * Valid indices for `duckdb_v2_copy_to_bind_get_column_type()` and `duckdb_v2_copy_to_bind_get_column_name()` are [0, + * count). * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP_NS value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param count Receives the number of columns. + * @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_value_create_timestamp_ns(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_column_count(duckdb_v2_copy_to_bind_info_handle info, + idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP_TZ value. + * Retrieves the type of the column at the given index. * - * The payload is microseconds since 1970-01-01, in UTC, the same unit value_get_timestamp_tz reports. It is not - * range-checked here; value_cast is the validating path. The returned value is caller-owned; destroy it via - * value_destroy. + * Fails if the index is out of bounds. The returned type is owned by the caller and must be destroyed via + * `duckdb_v2_logical_type_destroy()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP_TZ value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param index The index of the column to get the type of. + * @param type Receives the column type. Owned by the caller; destroy via `duckdb_v2_logical_type_destroy()`. + * @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_value_create_timestamp_tz(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_column_type(duckdb_v2_copy_to_bind_info_handle info, + idx_t index, duckdb_v2_logical_type_handle *type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP_TZ_NS value. + * Retrieves the name of the column at the given index. * - * The payload is nanoseconds since 1970-01-01, in UTC, the same unit value_get_timestamp_tz_ns reports. It is not - * range-checked here; value_cast is the validating path. The returned value is caller-owned; destroy it via - * value_destroy. + * Fails if the index is out of bounds. The name is borrowed and valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP_TZ_NS value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param index The index of the column to get the name of. + * @param name Receives a borrowed pointer to the column name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. + * @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_value_create_timestamp_tz_ns(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_column_name(duckdb_v2_copy_to_bind_info_handle info, + idx_t index, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a INTERVAL value. + * Returns the number of options the `COPY` statement passed to the function. * - * The payload is the (months, days, micros) triple, the same unit value_get_interval reports. It is not range-checked - * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * The engine's own options (e.g. `USE_TMP_FILE` or `BATCH_SIZE`) are handled before the function sees the statement and + * are not included. Valid indices for `duckdb_v2_copy_to_bind_get_option_name()` and + * `duckdb_v2_copy_to_bind_get_option_value()` are [0, count). The options are ordered by name. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new INTERVAL value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param count Receives the number of options. + * @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_value_create_interval(duckdb_v2_factory_handle factory, - const duckdb_v2_interval_t *in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_option_count(duckdb_v2_copy_to_bind_info_handle info, + idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * 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 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. + * Retrieves the name of the option at the given index. * - * 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. + * Option names are SQL identifiers, matched case-insensitively. Fails if the index is out of bounds. The name is + * borrowed and valid only for the duration of the callback. * * 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, 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. + * @param info The bind info handle. + * @param index The index of the option to get the name of. + * @param name Receives a borrowed pointer to the option name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. + * @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_value_create_decimal(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_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_option_name(duckdb_v2_copy_to_bind_info_handle info, + idx_t index, const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a UUID value from its internal 128-bit form. + * Retrieves the value of the option at the given index. * - * The payload is the storage form a vector element holds, not the canonical byte order: the high bit is flipped so the - * integer sorts. To build one from canonical text, cast a VARCHAR with value_cast instead, which is also how a UUID - * renders back. + * An option written with a single value (e.g. `DELIM ','`) yields that value. An option written as a bare name (e.g. + * `HEADER`) yields the BOOLEAN `true`. An option written with a parenthesized list (e.g. `KEYS (a, b)`) yields a tuple: + * an unnamed STRUCT with one field per element, in order. Fails if the index is out of bounds. The returned value is + * owned by the caller and must be destroyed via `duckdb_v2_value_destroy()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The internal 128-bit storage form. - * @param out_value Receives the new UUID value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param index The index of the option. + * @param value Receives the option's value. Owned by the caller; destroy via `duckdb_v2_value_destroy()`. + * @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_value_create_uuid(duckdb_v2_factory_handle factory, - const duckdb_v2_hugeint_t *in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_bind_get_option_value(duckdb_v2_copy_to_bind_info_handle info, + idx_t index, duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a BIT value from its wire bytes. - * - * The wire form is a mandatory padding-header byte — the count of leading bits in the first data byte that are not part - * of the bit string — followed by the data bytes, so the input must be at least 1 byte. These are the same bytes - * value_get_blob reports back. + * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The wire bytes, a padding header byte followed by data. Must be at least 1 byte. - * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only - * when this is 0. - * @param out_value Receives the new BIT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The batch size info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_create_bit(duckdb_v2_factory_handle factory, const char *in_value, - idx_t in_value_length, duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_batch_size_get_user_data(duckdb_v2_copy_to_batch_size_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a BIGNUM value from its storage bytes. - * - * The bytes are opaque storage, as produced by bignum_encode from a magnitude and a sign flag; a negative is stored - * bit-inverted behind a header, so these are not the magnitude bytes. The header plus at least one magnitude byte means - * the input must exceed 3 bytes. These are the same bytes value_get_blob reports back, for bignum_decode to translate. + * Retrieves the bind data set by the function's `COPY ... TO` bind callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The opaque storage bytes from bignum_encode. Must exceed 3 bytes. - * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only - * when this is 0. - * @param out_value Receives the new BIGNUM value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The batch size info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_create_bignum(duckdb_v2_factory_handle factory, const char *in_value, - idx_t in_value_length, duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_batch_size_get_bind_data(duckdb_v2_copy_to_batch_size_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a LIST value from its elements. - * - * The child type is the common type of the elements, resolved by the same rule a SQL list literal follows, and every - * element is cast to it; a set with no common type surfaces the cast error. Pass child_type to name the type instead, - * which is also how an empty list is built: with child_type NULL, an empty element array has no type to resolve and - * returns ERROR_INPUT_INVALID. - * - * The elements are borrowed and copied in, and a NULL element becomes a typed NULL. The type is rebuilt from its child, - * so an alias on the outer LIST type is not preserved; value_cast is the alias-preserving path. + * Sets the number of rows a batch should carry, as the target the engine cuts batches at. The batch size callback must + * set this to a value greater than 0; the statement fails otherwise. DuckDB defines the `BATCH_SIZE` on omission of + * calling the function. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param child_type Optional. The element type. Pass NULL to resolve it from the elements. - * @param children An array of child_count elements. Borrowed (copied in). Pass NULL when child_count is 0. - * @param child_count The number of elements. - * @param out_value Receives the new composite value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The batch size info handle. + * @param rows The number of rows a batch should carry. Must be greater than 0. + * @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_value_create_list(duckdb_v2_factory_handle factory, - duckdb_v2_logical_type_handle child_type, - const duckdb_v2_value_handle *children, idx_t child_count, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_batch_size_set_target(duckdb_v2_copy_to_batch_size_info_handle info, + idx_t rows, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates an ARRAY value from its elements, sized by their count. - * - * The child type is resolved exactly as for value_create_list, and child_type names it explicitly the same way. The - * minimum array size is 1, so an empty element array returns ERROR_INPUT_INVALID whether or not child_type is given. - * - * The elements are borrowed and copied in, and a NULL element becomes a typed NULL. + * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param child_type Optional. The element type. Pass NULL to resolve it from the elements. - * @param children An array of child_count elements. Borrowed (copied in). Pass NULL when child_count is 0. - * @param child_count The number of elements. - * @param out_value Receives the new composite value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The init info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_create_array(duckdb_v2_factory_handle factory, - duckdb_v2_logical_type_handle child_type, - const duckdb_v2_value_handle *children, idx_t child_count, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_init_get_user_data(duckdb_v2_copy_to_init_info_handle info, void **data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a STRUCT value from named fields, in order. - * - * Each field keeps its own child's type, so there is nothing to resolve across them; names and children are parallel - * arrays of field_count entries. An empty field list builds the empty struct, which is a real type. - * - * The names and children are borrowed and copied in, and a NULL child becomes a typed NULL. Duplicate field names are - * rejected. + * Retrieves the bind data set by the function's `COPY ... TO` bind callback. * * history: * - unstable: v2.0.0 - * - * @param factory The factory to create with. - * @param names An array of field_count field names. Pass NULL when field_count is 0. - * @param names_lengths Byte lengths of the entries in `names`; element i is the length of `names[i]`. May be NULL only - * when `names` is NULL. - * @param children An array of field_count field values. Borrowed (copied in). Pass NULL when field_count is 0. - * @param field_count The number of fields. - * @param out_value Receives the new composite value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * + * @param info The init info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_create_struct(duckdb_v2_factory_handle factory, const char *const *names, - const idx_t *names_lengths, - const duckdb_v2_value_handle *children, idx_t field_count, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_init_get_bind_data(duckdb_v2_copy_to_init_info_handle info, void **data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TUPLE value from positional fields. - * - * TUPLE is the unnamed struct: the same positional children as value_create_struct, under a distinct type id and with - * no names. Each field keeps its own child's type. An empty field list builds the empty tuple, which is a real type. + * Retrieves the path of the file the init callback is preparing. * - * The children are borrowed and copied in, and a NULL child becomes a typed NULL. + * This is the path the batches of this file are to be written to, after the engine has applied its own rewrites (e.g. a + * temporary name while the file is being written, or a per-partition path). The path is borrowed and valid only for the + * duration of the callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param children An array of field_count field values. Borrowed (copied in). Pass NULL when field_count is 0. - * @param field_count The number of fields. - * @param out_value Receives the new composite value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The init info handle. + * @param path Receives a borrowed pointer to the file path. Valid only for the duration of the callback. + * @param path_length Receives the length of `*path` in bytes. `*path` is not guaranteed to be null-terminated. + * @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_value_create_tuple(duckdb_v2_factory_handle factory, - const duckdb_v2_value_handle *children, idx_t field_count, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_init_get_file_path(duckdb_v2_copy_to_init_info_handle info, + const char **path, idx_t *path_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a MAP value from parallel key and value arrays. - * - * The key and value types are the common types of the keys and of the values, resolved as for value_create_list, and - * every entry is cast to them. Pass key_type and value_type to name them instead, which is also how an empty map is - * built: with both NULL, empty key and value arrays have no types to resolve and return ERROR_INPUT_INVALID. + * Sets the function's "init data" from the init callback. * - * Keys and values are borrowed and copied in, and the two arrays must be the same length. Keys must be non-NULL and - * unique; both are enforced. + * The init data lives for the duration of the file being written and is retrievable from the batch, flush and finalize + * callbacks of that file. Batches may be prepared by several threads at once, so the function must synchronize its own + * access to it from the batch callback. The opaque handle bundles the pointer with an optional destructor, invoked when + * the file is done with the data. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param key_type Optional. The key type. Pass NULL to resolve it from the keys. - * @param value_type Optional. The value type. Pass NULL to resolve it from the values. - * @param keys An array of entry_count keys. Borrowed (copied in). Pass NULL when entry_count is 0. - * @param values An array of entry_count values, parallel to keys. Borrowed (copied in). Pass NULL when entry_count is - * 0. - * @param entry_count The number of entries. - * @param out_value Receives the new composite value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The init info handle. + * @param data Opaque handle bundling the init data pointer plus an optional destructor. + * @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_value_create_map( - duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle key_type, duckdb_v2_logical_type_handle value_type, - const duckdb_v2_value_handle *keys, const duckdb_v2_value_handle *values, idx_t entry_count, - duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_init_set_init_data(duckdb_v2_copy_to_init_info_handle info, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of child values of a value. - * - * Per type kind: the element count for LIST and ARRAY; the field count for STRUCT and TUPLE; twice the entry count for - * MAP, whose children alternate key, value; and 2 for UNION, the tag plus the active member. Everything else reports 0, - * NULL values of any nested type included. + * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out_count Receives the number of children. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The batch info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_get_child_count(duckdb_v2_value_handle value, idx_t *out_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_batch_get_user_data(duckdb_v2_copy_to_batch_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns one child of a composite value as an owned copy. - * - * LIST and ARRAY children are the elements. STRUCT and TUPLE children are the fields in declared order, and a STRUCT's - * field names come from its type, via logical_type_get_param. MAP children alternate key, value, symmetric with - * value_create_map. UNION children are [0] the tag, as a UTINYINT value, and [1] the active member, because a union - * value holds only that one member. - * - * Note the divergence from vector_get_child, which descends structurally and so exposes [0] = tag and [1..N] = ALL - * members. Code written to descend generically over both must account for that difference. - * - * An out-of-range index returns ERROR_INPUT_INVALID, as does any index on a non-composite or NULL value. The returned - * value is caller-owned; destroy it via value_destroy. + * Retrieves the bind data set by the function's `COPY ... TO` bind callback. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param index The child index, in [0, child_count). - * @param out_child Receives the owned child value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The batch info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_get_child(duckdb_v2_value_handle value, idx_t index, - duckdb_v2_value_handle *out_child, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_batch_get_bind_data(duckdb_v2_copy_to_batch_info_handle info, + void **data, 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. + * Retrieves the init data set by the function's `COPY ... TO` init callback for the file this batch belongs to. * * 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. + * @param info The batch info handle. + * @param data Receives the init data pointer, or null if none was set. + * @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_value_variant_to_value(duckdb_v2_value_handle value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_batch_get_init_data(duckdb_v2_copy_to_batch_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Casts a value to a target type, using a factory. - * - * The conversion is the SQL-faithful, non-strict one, registered custom casts included, and a cast failure surfaces - * from the call. Together with a VARCHAR built through value_create_varchar, this constructs any value from text, - * extension values included; casting a member value to a union type, or a VARCHAR to an enum type, is the sanctioned - * way to build UNION and ENUM values. - * - * A connection's or callback's factory casts with that client's cast functions and settings (e.g. TimeZone). An - * instance's factory supports only the built-in casts, with default settings. + * Takes ownership of the rows of the batch to prepare. * - * The input value and target type are borrowed. The returned value is caller-owned; destroy it via value_destroy. + * The collection holds one column per column reported by `duckdb_v2_copy_to_bind_get_column_count()`, in the same + * order, and can be scanned with `duckdb_v2_column_data_collection_scan()`. The batch can only be taken once: a second + * call fails. Once taken, the caller owns the collection and must destroy it via + * `duckdb_v2_column_data_collection_destroy()`, e.g. by keeping it as the batch data with that destructor. A batch that + * is never taken is destroyed when the callback returns. * * history: * - unstable: v2.0.0 * - * @param factory The factory supplying the cast functions. - * @param value The borrowed value to cast. - * @param target_type The borrowed target logical type. - * @param out_value Receives the owned cast result. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The batch info handle. + * @param collection Receives the collection holding the rows of the batch. Owned by the caller; destroy via + * `duckdb_v2_column_data_collection_destroy()`. + * @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_value_cast(duckdb_v2_factory_handle factory, duckdb_v2_value_handle value, - duckdb_v2_logical_type_handle target_type, - duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_batch_take_input(duckdb_v2_copy_to_batch_info_handle info, + duckdb_v2_column_data_collection_handle *collection, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns whether the value is NULL. + * Sets the prepared "batch data" from the batch callback. + * + * The batch data is the prepared form of the batch and is handed to the flush callback via + * `duckdb_v2_copy_to_flush_get_batch_data()`. The opaque handle bundles the pointer with an optional destructor, + * invoked once the batch has been flushed. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out_is_null Receives true if the value is NULL, false otherwise. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The batch info handle. + * @param data Opaque handle bundling the batch data pointer plus an optional destructor. + * @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_value_is_null(duckdb_v2_value_handle value, bool *out_is_null, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_batch_set_batch_data(duckdb_v2_copy_to_batch_info_handle info, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the logical type of the value. - * - * The returned logical type is caller-owned; destroy it via logical_type_destroy. + * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out_type Receives the owned logical type. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The flush info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_value_get_logical_type(duckdb_v2_value_handle value, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_flush_get_user_data(duckdb_v2_copy_to_flush_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Renders the value as a human-readable string. Diagnostic only. - * - * Writes into a caller-supplied buffer, so nothing is allocated on the caller's behalf and nothing has to be freed. - * - * Pass out_string = NULL to size the buffer without rendering into it: out_length then receives the length, and - * out_capacity is ignored. With out_string != NULL, out_capacity must be at least out_length + 1, or the call returns - * ERROR_INPUT_OBJECT_SIZE with out_length set to the required length and out_string left untouched. - * - * out_length never counts the terminator, but a successful write always appends one, so the buffer is usable as a C - * string. + * Retrieves the bind data set by the function's `COPY ... TO` bind callback. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out_string Caller-owned buffer receiving the text plus a null terminator, or NULL to only report the required - * length in out_length. - * @param out_capacity Bytes available in out_string, terminator included. Ignored when out_string is NULL. - * @param out_length Receives the text length excluding the null terminator — written on success and on - * ERROR_INPUT_OBJECT_SIZE. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The flush info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_value_to_string(duckdb_v2_value_handle value, char *out_string, - idx_t out_capacity, idx_t *out_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_flush_get_bind_data(duckdb_v2_copy_to_flush_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for value --- */ - -/* ============================================================================ - * MODULE: arrow - * ============================================================================ */ - -/* --- Enums for arrow --- */ - -/* --- Struct forward declarations for arrow --- */ - -/* --- Types for arrow --- */ - +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Converts Arrow arrays into DuckDB data chunks, against one resolved ArrowSchema. Create it with - * `duckdb_v2_arrow_importer_create()`, which resolves every column's DuckDB type once, so the same importer serves any - * number of arrays of that shape. `duckdb_v2_arrow_importer_get_schema()` reports the resolved DuckDB schema. - * `duckdb_v2_arrow_importer_append()` takes an array, `duckdb_v2_arrow_importer_next_chunk()` produces chunks from it, - * and `duckdb_v2_arrow_importer_destroy()` frees the importer. + * Retrieves the init data set by the function's `COPY ... TO` init callback for the file this batch belongs to. * - * 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. + * history: + * - unstable: v2.0.0 + * + * @param info The flush info handle. + * @param data Receives the init data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_arrow_importer { - void *internal_ptr; -} * duckdb_v2_arrow_importer_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_flush_get_init_data(duckdb_v2_copy_to_flush_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Converts DuckDB data chunks into Arrow arrays, for one fixed list of columns. Create it with - * `duckdb_v2_arrow_exporter_create()`, which captures the session's Arrow settings and resolves the extension types - * once. `duckdb_v2_arrow_exporter_get_schema()` reports the Arrow schema. `duckdb_v2_arrow_exporter_append()` takes a - * chunk, `duckdb_v2_arrow_exporter_next_array()` produces arrays from it, and `duckdb_v2_arrow_exporter_destroy()` - * frees the exporter. + * Retrieves the batch data set by the function's batch callback for the batch being flushed. * - * An exporter must not be used from two threads at once. + * history: + * - unstable: v2.0.0 + * + * @param info The flush info handle. + * @param data Receives the batch data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_arrow_exporter { - void *internal_ptr; -} * duckdb_v2_arrow_exporter_handle; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_flush_get_batch_data(duckdb_v2_copy_to_flush_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * A query result that produces Arrow arrays. Works like a result, which produces data chunks. Create it with - * `duckdb_v2_statement_execute_arrow()` or `duckdb_v2_prepared_statement_execute_arrow()`. + * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. * - * - Use it from one thread at a time. - * - `duckdb_v2_connection_interrupt()` cancels it: `duckdb_v2_arrow_result_step()` reports `CANCELLED`, and - * `duckdb_v2_arrow_result_fetch_array()` and a stream's `get_next` fail. - * - Arrays and schemas it hands out belong to the caller and stay valid after the result is destroyed. + * history: + * - unstable: v2.0.0 + * + * @param info The finalize info handle. + * @param data Receives the user data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_arrow_result { - void *internal_ptr; -} * duckdb_v2_arrow_result_handle; - -/* --- Constants for arrow --- */ - -/* --- Function pointer typedefs for arrow --- */ - -/* --- Functions for arrow --- */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_finalize_get_user_data(duckdb_v2_copy_to_finalize_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Resolves an Arrow schema into a reusable importer. - * - * Works out every column's DuckDB logical type and the Arrow type information the conversion needs, once, so any number - * of arrays of that shape can be imported without re-reading the schema. `schema` is read, not consumed: the caller - * keeps ownership and still releases it. + * Retrieves the bind data set by the function's `COPY ... TO` bind callback. * - * `batch_size` caps the rows per produced chunk. A long array is split across several chunks. Rows left over that do - * not fill a batch are held back and joined with the next array, unless the append asked to flush. Pass 0 for no - * maximum: each array becomes one chunk, however long it is. + * history: + * - unstable: v2.0.0 * - * Resolving reads the catalog for extension types, so `context` must have an active transaction. The importer keeps - * using that context for every conversion and must not outlive it. Within one connection the context is the same - * throughout, so an importer created in a bind callback is usable from the matching exec callback. `*out_importer` is - * set to NULL on failure. + * @param info The finalize info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_copy_to_finalize_get_bind_data(duckdb_v2_copy_to_finalize_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the init data set by the function's `COPY ... TO` init callback for the file being finalized. * * history: * - unstable: v2.0.0 * - * @param context The context used to resolve the Arrow types, extension types included. - * @param schema The schema to resolve. Read, not consumed; the caller keeps ownership. - * @param batch_size Maximum rows per produced chunk, or 0 for no maximum. - * @param out_importer On success, receives the new importer. Owned by the caller; destroy via - * `duckdb_v2_arrow_importer_destroy()`. + * @param info The finalize info handle. + * @param data Receives the init data pointer, or null if none was set. * @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_arrow_importer_create(duckdb_v2_context_handle context, - const struct ArrowSchema *schema, idx_t batch_size, - duckdb_v2_arrow_importer_handle *out_importer, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_finalize_get_init_data(duckdb_v2_copy_to_finalize_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the resolved DuckDB schema. - * - * Writes an owned schema handle with the DuckDB name and logical type of every column the importer resolved. This is - * how a caller learns the DuckDB shape of an ArrowSchema, to declare a table function's result columns for instance, - * without reimplementing the mapping from Arrow format strings to logical types. + * Makes the scan of the COPY FROM side of the copy function the given data source. * - * The fields were resolved at creation, so this reads no catalog and needs no transaction. `*out_schema` is set to NULL - * on failure. + * A copy function takes care of everything that is decided when a `COPY ... FROM` statement is bound - the bind + * callback receives the file path, the options and the columns to copy into - and scans with a data source: the + * callbacks that set up the scan at execution time and produce its rows. The data source produces the columns the bind + * callback receives: those of the statement's column list, so `COPY target(b) FROM ...` produces one column, or every + * column of the target table when the statement has none. The callbacks of the data source read the bind data the bind + * callback sets, and the user data of the data source or, if it has none or its pointer is null, the user data of the + * copy function. A data source with an exec callback must be set before the function is registered. The function keeps + * a copy of the data source as it is when this is called, so the same data source can be given to any number of + * functions, and changing it afterwards does not change them. * * history: * - unstable: v2.0.0 * - * @param importer The importer to read. - * @param out_schema On success, receives an owned schema. Destroy via `duckdb_v2_schema_destroy()`. + * @param function The copy function to set the data source of. + * @param data_source The data source to scan with. Borrowed; it can be destroyed after this call. * @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_arrow_importer_get_schema(duckdb_v2_arrow_importer_handle importer, - duckdb_v2_schema_handle *out_schema, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_set_data_source(duckdb_v2_copy_function_handle function, + duckdb_v2_data_source_handle data_source, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Gives the importer one array to convert. - * - * Take the chunks with `duckdb_v2_arrow_importer_next_chunk()` until that returns NULL. Appending while the previous - * array still has rows left is rejected with `ERROR_INPUT_INVALID`. An array whose shape does not match the resolved - * schema -- a different child count, a child whose length differs from the array's, a null or already-released child -- - * is rejected the same way, before anything is read. - * - * `flush` marks the end of the input: rows that do not fill a batch then come out as a final short chunk instead of - * being held back for the next array. Pass NULL for `array` with `flush` set to release the held rows without supplying - * more input. - * - * `consume` decides what happens to the caller's array. - * - * When true, the importer takes over the array and sets its `release` to NULL; the caller must not release it - * afterwards. The produced chunks reference the Arrow buffers directly, without copying, and keep them alive, so the - * chunks stay valid after the importer is destroyed. Prefer this path. + * Sets the bind callback of the `COPY ... FROM` side. * - * When false, the caller keeps the array and must keep it valid until the drain finishes. The produced chunks are - * copies, so they do not depend on the array, at the cost of one copy per chunk. + * The bind callback is invoked during query planning for each `COPY ... FROM` statement that uses the function. It can + * read the path of the file to read and the statement's options, inspect the names and types of the columns the target + * table expects, hint at the number of rows the read will produce, and set "bind data" that is shared with the other + * `COPY ... FROM` callbacks. The columns are fixed by the target table: the function must produce them as they are. A + * bind callback must be set for the `COPY ... FROM` side to be registered. * - * Either way, a chunk that joins rows held back from the previous array is a copy, since it cannot reference two - * arrays. + * history: + * - unstable: v2.0.0 * - * Only the default, dictionary-encoded and run-end-encoded Arrow layouts are supported. Any other layout reports - * `ERROR_QUERY_NOT_IMPLEMENTED` when the column is converted. + * @param function The function to set the callback of. + * @param callback The callback to set. + * @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_copy_from_set_bind_callback(duckdb_v2_copy_function_handle function, + duckdb_v2_copy_from_bind_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the user data set via `duckdb_v2_copy_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param importer The importer to feed. - * @param array The array to convert. Its `release` is set to NULL when `consume` is true. - * @param consume True to hand the array over for a zero-copy import; false to keep it, in which case every produced - * chunk is a copy. - * @param flush True to mark the end of the input, releasing held rows as a final short chunk. Pass NULL for `array` - * with this set to flush without supplying more input. + * @param info The bind info handle. + * @param data Receives the user data pointer, or null if none was set. * @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_arrow_importer_append(duckdb_v2_arrow_importer_handle importer, - struct ArrowArray *array, bool consume, bool flush, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_user_data(duckdb_v2_copy_from_bind_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Produces the next chunk of the appended array, or NULL once the array is drained. - * - * Call it in a loop until `*out_chunk` is NULL. An importer with no array appended also returns NULL. Each chunk holds - * at most the importer's `batch_size` rows, or the whole array when that is 0. A chunk may start with rows held back - * from the previous array, and rows that do not fill a batch are held back in turn unless the append asked to flush. So - * NULL means the array has been read, not that all of its rows have come out. + * Sets the function's "bind data" from the bind callback. * - * The conversion runs under the context the importer was created with, which must still be alive. `*out_chunk` is set - * to NULL on failure. + * The bind data is stored with the bound statement and retrievable from the other callbacks of the same side. The + * opaque handle bundles the pointer with an optional destructor, invoked when the bind data is no longer needed, and an + * optional equality callback used when comparing two bound statements; without one, pointer equality is used. * * history: * - unstable: v2.0.0 * - * @param importer The importer to drain. - * @param out_chunk On success, receives the next chunk, or NULL once the array is drained. Destroy via - * `duckdb_v2_data_chunk_destroy()`. + * @param info The bind info handle. + * @param data Opaque handle bundling the bind data pointer plus optional destructor and equality callbacks. * @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_arrow_importer_next_chunk(duckdb_v2_arrow_importer_handle importer, - duckdb_v2_data_chunk_handle *out_chunk, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_set_bind_data(duckdb_v2_copy_from_bind_info_handle info, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys an importer. + * Retrieves the path the `COPY ... FROM` statement reads from, as written in the statement. * - * Null-safe: passing NULL, or a slot already set to NULL, is a no-op. Chunks already produced stay valid, including the - * zero-copy ones, which keep the Arrow buffers alive themselves. An array appended with `consume` true and not fully - * drained is released here. Rows held back for a next array are dropped. On success the slot is set to NULL. + * The engine does not expand globs or check that the file exists; both are left to the function. The path is borrowed + * and valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param importer The importer to destroy. + * @param info The bind info handle. + * @param path Receives a borrowed pointer to the file path. Valid only for the duration of the callback. + * @param path_length Receives the length of `*path` in bytes. `*path` is not guaranteed to be null-terminated. + * @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_arrow_importer_destroy(duckdb_v2_arrow_importer_handle *importer); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_file_path(duckdb_v2_copy_from_bind_info_handle info, + const char **path, idx_t *path_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates an exporter for one fixed list of columns. - * - * Resolves the extension types and captures the session's Arrow settings, so every array this exporter produces matches - * the schema `duckdb_v2_arrow_exporter_get_schema()` reports, even if a setting changes afterwards. - * - * `batch_size` caps the rows per produced array. A long chunk is split across several arrays. Rows left over that do - * not fill a batch are held back and joined with the next chunk, unless the append asked to flush. Pass 0 for no - * maximum: each chunk becomes one array, however long it is. + * Returns the number of columns the target table expects, i.e. the columns every batch the exec callback produces must + * carry, in this order. * - * `types` and `names` are parallel arrays of `count` entries, borrowed and copied; they may be NULL only when `count` - * is 0. Resolving reads the catalog, so `context` must have an active transaction. `*out_exporter` is set to NULL on - * failure. + * Valid indices for `duckdb_v2_copy_from_bind_get_column_type()` and `duckdb_v2_copy_from_bind_get_column_name()` are + * [0, count). * * history: * - unstable: v2.0.0 * - * @param context The context whose Arrow settings are captured and whose transaction resolves the types. - * @param types An array of `count` column types. May be NULL only when `count` is 0. - * @param names An array of `count` column names, parallel to `types`. Each name must be valid UTF-8. May be NULL only - * when `count` is 0. - * @param names_lengths Byte lengths of the entries in `names`; element i is the length of `names[i]`. May be NULL only - * when `names` is NULL. - * @param count The number of columns, being the length of both `types` and `names`. - * @param batch_size Maximum rows per produced array, or 0 for no maximum. - * @param out_exporter On success, receives the new exporter. Owned by the caller; destroy via - * `duckdb_v2_arrow_exporter_destroy()`. + * @param info The bind info handle. + * @param count Receives the number of columns. * @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_arrow_exporter_create(duckdb_v2_context_handle context, - const duckdb_v2_logical_type_handle *types, - const char *const *names, const idx_t *names_lengths, - idx_t count, idx_t batch_size, - duckdb_v2_arrow_exporter_handle *out_exporter, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_column_count(duckdb_v2_copy_from_bind_info_handle info, + idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the Arrow schema of the arrays this exporter produces. + * Retrieves the type of the column at the given index. * - * Fills the caller-allocated `out_schema`. The caller owns the result and releases it with - * `out_schema->release(out_schema)`. Callable at any point, and always returns the same schema, since it is built from - * the settings captured at creation. + * Fails if the index is out of bounds. The returned type is owned by the caller and must be destroyed via + * `duckdb_v2_logical_type_destroy()`. * * history: * - unstable: v2.0.0 * - * @param exporter The exporter to read. - * @param out_schema Caller-allocated schema the library fills. Release it with `out_schema->release(out_schema)`. + * @param info The bind info handle. + * @param index The index of the column to get the type of. + * @param type Receives the column type. Owned by the caller; destroy via `duckdb_v2_logical_type_destroy()`. * @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_arrow_exporter_get_schema(duckdb_v2_arrow_exporter_handle exporter, - struct ArrowSchema *out_schema, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_column_type(duckdb_v2_copy_from_bind_info_handle info, + idx_t index, duckdb_v2_logical_type_handle *type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Gives the exporter one chunk to convert. - * - * The chunk is converted in full before this returns. The conversion copies into freshly allocated Arrow buffers, so - * nothing of the caller's is retained. Every array completed by this chunk becomes available from - * `duckdb_v2_arrow_exporter_next_array()`; rows that do not complete a batch are held back and finished by the next - * chunk. Completed arrays queue up, so appending again before they are taken is allowed. - * - * `flush` marks the end of the input: the held rows are then finished as a final short array. Pass NULL for `chunk` - * with `flush` set to release the held rows without supplying more input. - * - * The chunk's types must match the ones the exporter was created with, or the call is rejected with - * `ERROR_INPUT_INVALID` before anything is read. + * Retrieves the name of the column at the given index. * - * `consume` decides only what happens to the caller's handle, since the data is copied either way. When true the chunk - * is destroyed and the slot set to NULL, saving a `duckdb_v2_data_chunk_destroy()` for a chunk the caller owns. When - * false the chunk is left untouched, which is what a chunk borrowed from a callback needs, such as the output chunk of - * a table function's exec callback, which the caller does not own and must not destroy. + * Fails if the index is out of bounds. The name is borrowed and valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param exporter The exporter to feed. - * @param chunk The chunk to convert. Destroyed and set to NULL only when `consume` is true. - * @param consume True to hand the chunk over, destroying it; false to leave the caller's handle untouched. - * @param flush True to mark the end of the input, releasing the held rows as a final short array. Pass NULL for `chunk` - * with this set to flush without supplying more input. + * @param info The bind info handle. + * @param index The index of the column to get the name of. + * @param name Receives a borrowed pointer to the column name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @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_arrow_exporter_append(duckdb_v2_arrow_exporter_handle exporter, - duckdb_v2_data_chunk_handle *chunk, bool consume, - bool flush, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_column_name(duckdb_v2_copy_from_bind_info_handle info, + idx_t index, const char **name, + idx_t *name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Takes the next completed array, or reports that none is ready. - * - * Call it in a loop after every `duckdb_v2_arrow_exporter_append()` until `out_array->release` is NULL, which is how - * the Arrow C Data Interface signals "no array" and what a stream's `get_next` does at end of input. Rows held back - * towards an unfinished batch are not an array yet; they come out after a further append or a flush. + * Returns the number of options the `COPY` statement passed to the function. * - * Each array is owned by the caller and released with `out_array->release(out_array)`, independently of the exporter - * and of every other array. + * Every option other than `FORMAT` is included. Valid indices for `duckdb_v2_copy_from_bind_get_option_name()` and + * `duckdb_v2_copy_from_bind_get_option_value()` are [0, count). The options are ordered by name. * * history: * - unstable: v2.0.0 * - * @param exporter The exporter to drain. - * @param out_array Caller-allocated array the library fills. Left released -- `release` NULL -- when none is ready. - * Release a filled one with `out_array->release(out_array)`. + * @param info The bind info handle. + * @param count Receives the number of options. * @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_arrow_exporter_next_array(duckdb_v2_arrow_exporter_handle exporter, - struct ArrowArray *out_array, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_option_count(duckdb_v2_copy_from_bind_info_handle info, + idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys an exporter. + * Retrieves the name of the option at the given index. * - * Null-safe: passing NULL, or a slot already set to NULL, is a no-op. Arrays already taken stay valid. Arrays still - * queued inside are released here, and rows held back towards an unfinished batch are dropped. On success the slot is - * set to NULL. + * Option names are SQL identifiers, matched case-insensitively. Fails if the index is out of bounds. The name is + * borrowed and valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param exporter The exporter to destroy. + * @param info The bind info handle. + * @param index The index of the option to get the name of. + * @param name Receives a borrowed pointer to the option name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. + * @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_arrow_exporter_destroy(duckdb_v2_arrow_exporter_handle *exporter); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_option_name(duckdb_v2_copy_from_bind_info_handle info, + idx_t index, const char **name, + idx_t *name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Executes a parsed statement. The result produces Arrow arrays. + * Retrieves the value of the option at the given index. * - * Works like `duckdb_v2_statement_execute()`. `*out_result` is set to NULL on failure. + * An option written with a single value (e.g. `DELIM ','`) yields that value. An option written as a bare name (e.g. + * `HEADER`) yields the BOOLEAN `true`. An option written with a parenthesized list (e.g. `KEYS (a, b)`) yields a tuple: + * an unnamed STRUCT with one field per element, in order. Fails if the index is out of bounds. The returned value is + * owned by the caller and must be destroyed via `duckdb_v2_value_destroy()`. * * history: * - unstable: v2.0.0 * - * @param conn The connection to run the statement on. - * @param statement The statement to execute. Not consumed. - * @param parameter_names Optional. As in `duckdb_v2_statement_execute()`. - * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of - * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. - * @param parameter_values Optional. As in `duckdb_v2_statement_execute()`. - * @param parameter_count The number of parameters. 0 for none. - * @param batch_size Maximum rows per array. Arrays can be shorter. 0 means 131072. - * @param out_result Receives the new result. Destroy via `duckdb_v2_arrow_result_destroy()`. + * @param info The bind info handle. + * @param index The index of the option. + * @param value Receives the option's value. Owned by the caller; destroy via `duckdb_v2_value_destroy()`. * @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_statement_execute_arrow( - duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, - const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, - idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_get_option_value(duckdb_v2_copy_from_bind_info_handle info, + idx_t index, duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Executes a prepared statement. The result produces Arrow arrays. + * Reports the estimated number of rows the read will produce. * - * Works like `duckdb_v2_prepared_statement_execute()`. `*out_result` is set to NULL on failure. + * The estimate is a hint for the optimizer, not a limit: producing a different number of rows is not an error. Without + * it, the optimizer falls back on its own defaults. * * history: * - unstable: v2.0.0 * - * @param prepared The prepared statement to execute. Not consumed. - * @param parameter_names Optional. As in `duckdb_v2_prepared_statement_execute()`. - * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of - * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. - * @param parameter_values Optional. As in `duckdb_v2_prepared_statement_execute()`. - * @param parameter_count The number of parameters. 0 for none. - * @param batch_size Maximum rows per array. Arrays can be shorter. 0 means 131072. - * @param out_result Receives the new result. Destroy via `duckdb_v2_arrow_result_destroy()`. + * @param info The bind info handle. + * @param cardinality The estimated number of rows. + * @param is_exact Whether the estimate is exact, which also makes it an upper bound on the row count. * @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_prepared_statement_execute_arrow( - duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, - const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, - idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_set_cardinality(duckdb_v2_copy_from_bind_info_handle info, + idx_t cardinality, bool is_exact, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the result. Works like `duckdb_v2_result_destroy()`. + * Registers the copy function, making it available as a `COPY` format. + * + * The function is registered on the connection's database, visible to every connection, in the connection's + * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and + * a rollback undoes it. Registration requires a name and at least one configured side: a `COPY ... TO` side needs its + * batch and flush callbacks, a `COPY ... FROM` side needs its bind callback and a data source with an exec callback, + * set via `duckdb_v2_copy_from_set_data_source()`. A statement in a direction the function does not implement fails + * with an error. The copy function must have been created through a factory of the same database. The caller still owns + * the handle after registration and must destroy it with `duckdb_v2_copy_function_destroy()`, which does not affect the + * registered function. * * history: * - unstable: v2.0.0 * - * @param result The result to destroy. + * @param conn The connection to register on. + * @param function The copy function to register. + * @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_arrow_result_destroy(duckdb_v2_arrow_result_handle *result); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_copy_function(duckdb_v2_connection_handle conn, + duckdb_v2_copy_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Runs a bounded amount of the query and returns without blocking. + * Registers the copy function, making it available as a `COPY` format. * - * Works like `duckdb_v2_result_step()`. On status `CHUNK`, `out_array` holds the next array. Otherwise its `release` is - * NULL. + * The function is registered on the loading extension's database and attributed to the extension. Use this from the + * extension's load callback. Registration requires a name and at least one configured side: a `COPY ... TO` side needs + * its batch and flush callbacks, a `COPY ... FROM` side needs its bind callback and a data source with an exec + * callback, set via `duckdb_v2_copy_from_set_data_source()`. A statement in a direction the function does not implement + * fails with an error. The copy function must have been created through a factory of the same database. The caller + * still owns the handle after registration and must destroy it with `duckdb_v2_copy_function_destroy()`, which does not + * affect the registered function. * * history: * - unstable: v2.0.0 * - * @param result The result to step. - * @param out_array Caller-allocated array the library fills. Release it with `out_array->release(out_array)`. - * @param out_status Receives the step status. + * @param extension The loading extension. + * @param function The copy function to register. * @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_arrow_result_step(duckdb_v2_arrow_result_handle result, - struct ArrowArray *out_array, - DUCKDB_V2_RESULT_STEP_STATUS *out_status, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_copy_function(duckdb_v2_extension_handle extension, + duckdb_v2_copy_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Blocks until the next array is ready. + * Destroys the copy function, releasing its resources. * - * Works like `duckdb_v2_result_fetch_chunk()`. At the end of the result, `out_array->release` is NULL. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param result The result to fetch from. - * @param out_array Caller-allocated array the library fills. Release it with `out_array->release(out_array)`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param function The function to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_fetch_array(duckdb_v2_arrow_result_handle result, - struct ArrowArray *out_array, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_function_destroy(duckdb_v2_copy_function_handle *function); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Blocks until `duckdb_v2_arrow_result_step()` can make progress. Works like `duckdb_v2_result_wait()`. + * Sets the optional statistics callback of the `COPY ... TO` side. + * + * The statistics callback reports statistics about a written file, such as the number of rows and bytes it holds, which + * `COPY ... TO` returns when the statement asks for them with `RETURN_STATS`. It is invoked once per output file, after + * the finalize callback of that file, and only when the statement asks for the statistics. Without a statistics + * callback, `RETURN_STATS` is rejected for the function. * * history: * - unstable: v2.0.0 * - * @param result The result to wait on. + * @param function The function to set the callback of. + * @param callback The callback to set. * @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_arrow_result_wait(duckdb_v2_arrow_result_handle result, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_set_statistics_callback( + duckdb_v2_copy_function_handle function, duckdb_v2_copy_to_statistics_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Runs the query to the end and reports the changed-row count. Works like `duckdb_v2_result_drain()`. + * Retrieves the user data set on the copy function via `duckdb_v2_copy_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param result The result to drain. - * @param out_rows_changed Receives the changed-row count for an INSERT, UPDATE or DELETE, 0 otherwise. + * @param info The statistics info handle. + * @param data Receives the user data pointer, or null if none was set. * @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_arrow_result_drain(duckdb_v2_arrow_result_handle result, idx_t *out_rows_changed, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_statistics_get_user_data(duckdb_v2_copy_to_statistics_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the shape of the result. Works like `duckdb_v2_result_get_result_type()`. + * Retrieves the bind data set by the function's `COPY ... TO` bind callback. * * history: * - unstable: v2.0.0 * - * @param result The result. - * @param out_type Receives the result shape. + * @param info The statistics info handle. + * @param data Receives the bind data pointer, or null if none was set. * @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_arrow_result_get_result_type(duckdb_v2_arrow_result_handle result, - DUCKDB_V2_RESULT_TYPE *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_statistics_get_bind_data(duckdb_v2_copy_to_statistics_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the type of statement that produced the result. Works like `duckdb_v2_result_get_statement_type()`. + * Retrieves the init data set by the function's `COPY ... TO` init callback for the file being reported. * * history: * - unstable: v2.0.0 * - * @param result The result. - * @param out_type Receives the statement type. + * @param info The statistics info handle. + * @param data Receives the init data pointer, or null if none was set. * @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_arrow_result_get_statement_type(duckdb_v2_arrow_result_handle result, - DUCKDB_V2_STATEMENT_TYPE *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_statistics_get_init_data(duckdb_v2_copy_to_statistics_info_handle info, + void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the Arrow schema of the result's arrays. - * - * Available whenever `duckdb_v2_result_get_schema()` would be. + * Reports how many rows were written to the file. Reported as 0 when the callback does not set it. * * history: * - unstable: v2.0.0 * - * @param result The result. - * @param out_schema Caller-allocated schema the library fills. Release it with `out_schema->release(out_schema)`. + * @param info The statistics info handle. + * @param row_count The number of rows written to the file. * @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_arrow_result_get_schema(duckdb_v2_arrow_result_handle result, - struct ArrowSchema *out_schema, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_statistics_set_row_count(duckdb_v2_copy_to_statistics_info_handle info, + idx_t row_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Turns the result into an ArrowArrayStream. - * - * On success the stream takes over the result and `*result` is set to NULL. Each `get_next` returns the next array. - * Arrays already fetched are not repeated. Releasing the stream destroys the result. - * - * Converting runs no part of the query. The stream's `get_schema` can: for a statement that expands into several - * statements, such as PIVOT, it runs the ones before the statement that returns rows. A failing `get_next` or - * `get_schema` returns `EIO`; `get_last_error` has the message. + * Reports the size of the written file in bytes. Reported as 0 when the callback does not set it. * * history: * - unstable: v2.0.0 * - * @param result The result to take over. Set to NULL on success. - * @param out_stream Caller-allocated stream the library fills. Release it with `out_stream->release(out_stream)`. + * @param info The statistics info handle. + * @param file_size_bytes The size of the file in bytes. * @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_arrow_result_to_arrow_c_stream(duckdb_v2_arrow_result_handle *result, - struct ArrowArrayStream *out_stream, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_copy_to_statistics_set_file_size(duckdb_v2_copy_to_statistics_info_handle info, + idx_t file_size_bytes, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for arrow --- */ +/* --- Struct definitions for copy --- */ #ifdef __cplusplus } diff --git a/src/duckdb/src/main/attached_database.cpp b/src/duckdb/src/main/attached_database.cpp index b8abd9e8e..d35f78fe7 100644 --- a/src/duckdb/src/main/attached_database.cpp +++ b/src/duckdb/src/main/attached_database.cpp @@ -207,9 +207,11 @@ AttachedDatabase::AttachedDatabase(DatabaseInstance &db, Catalog &catalog_p, Sto } AttachedDatabase::~AttachedDatabase() { - if (!is_closed && is_detached) { - // a reference held outside of a transaction outlived the detach - auto action = Exception::UncaughtException() ? DatabaseCloseAction::SKIP_CHECKPOINT : detach_close_action; + if (!is_closed && (is_detached || IsTemporary())) { + // a reference held outside of a transaction outlived the detach, or a shared transaction outlived its + // connection + auto action = Exception::UncaughtException() || IsTemporary() ? DatabaseCloseAction::SKIP_CHECKPOINT + : detach_close_action; try { Close(action); } catch (std::exception &ex) { 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..dae34a0ba 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_connection.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_connection.cpp @@ -14,6 +14,19 @@ DUCKDB_V2_ERROR duckdb_v2_connection_create(duckdb_v2_instance_handle instance, }); } +DUCKDB_V2_ERROR duckdb_v2_connection_create_in_transaction(duckdb_v2_context_handle ctx, + duckdb_v2_connection_handle *out_conn, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(ctx); + DUCKDB_CHECK_ARG(out_conn); + *out_conn = nullptr; + return WithErrorHandler(err, [&]() { + auto &context = Convert(ctx)->context; + auto connection = duckdb::make_uniq(duckdb::Connection::CreateInTransaction(context)); + *out_conn = Convert(connection.release()); + }); +} + DUCKDB_V2_ERROR duckdb_v2_connection_destroy(duckdb_v2_connection_handle *conn) { return WithErrorHandler(nullptr, [&]() { if (!conn) { diff --git a/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp b/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp new file mode 100644 index 000000000..2aff41431 --- /dev/null +++ b/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp @@ -0,0 +1,1295 @@ +#include "duckdb/main/capi_v2/capi_v2_data_source_internal.hpp" +#include "duckdb/common/multi_file/base_file_reader.hpp" +#include "duckdb/common/multi_file/multi_file_data.hpp" +#include "duckdb/common/multi_file/multi_file_reader.hpp" +#include "duckdb/common/multi_file/table_function_multi_file.hpp" +#include "duckdb/execution/expression_executor.hpp" +#include "duckdb/execution/partition_info.hpp" +#include "duckdb/function/partition_stats.hpp" +#include "duckdb/main/profiler/metrics.hpp" +#include "duckdb/parallel/pipeline.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/filter/table_filter_functions.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/table_filter_set.hpp" +#include "duckdb/planner/table_filter_state.hpp" +#include "duckdb/storage/table/column_segment.hpp" + +namespace duckdb::capiv2 { + +class CV2DataSourceGlobalState final : public GlobalTableFunctionState { +public: + auto MaxThreads() const -> idx_t override { + return max_threads; + } + + CV2UserData handle; + idx_t max_threads = 1; + + // The declared column each vector of the output chunk stands for, kept here so the exec callback can ask. + vector scan_columns; +}; + +class CV2DataSourceLocalState final : public LocalTableFunctionState { +public: + CV2UserData handle; + //! Whether the caller claims the batches of this thread (see TableFunction::claim_batch) + bool claimed_externally = false; + //! Whether this thread has claimed a batch it has not exhausted yet + bool batch_claimed = false; + //! Written into by the exec callback when the scan requests no columns, as the function produces its rows through + //! its first column + unique_ptr row_chunk; + //! The filters of the query the engine applies to what the function produces, as the position of the scan column + //! each applies to and its state. Only for a function that reads the filters. + vector>> filters; + //! A column the multi-file scan wants converted before its filters apply: the position of the scan column it + //! produces and the expression doing the conversion, on the columns that follow it in what the function produced + struct ConvertedColumn { + idx_t position; + unique_ptr expression; + unique_ptr executor; + unique_ptr input; + }; + vector converted_columns; + //! For each scan column, whether it is one of the converted columns + vector converted_position; + //! What the function produces, in the types of its file, when some columns are converted afterwards + unique_ptr file_chunk; + + // Requested partition columns as declared columns, fixed for the lifetime of the local state's pipeline. + const vector &PartitionColumns(const OperatorPartitionInfo &partition_info, + const vector &scan_columns) { + if (!partition_columns_resolved) { + for (auto scan_position : partition_info.partition_columns) { + D_ASSERT(scan_position < scan_columns.size()); + partition_columns.push_back(scan_columns[scan_position]); + } + partition_columns_resolved = true; + } + D_ASSERT(partition_columns.size() == partition_info.partition_columns.size()); + return partition_columns; + } + + void CheckPartitionData(const Identifier &function_name, const OperatorPartitionData &data) { + if (last_batch_index.IsValid()) { + auto last_index = last_batch_index.GetIndex(); + // The engine would otherwise raise an InternalException, which invalidates the database. + if (data.batch_index < last_index) { + throw InvalidInputException( + "The partition data callback of table function %s reported batch index %llu after " + "previously reporting %llu on the same thread; the batch index must not decrease.", + function_name, data.batch_index, last_index); + } + // The engine only reads the values when the batch index changes; a changed value would silently be ignored. + if (data.batch_index == last_index) { + D_ASSERT(data.partition_data.size() == last_partition_values.size()); + for (idx_t i = 0; i < last_partition_values.size(); i++) { + if (Value::NotDistinctFrom(data.partition_data[i].min_val, last_partition_values[i])) { + continue; + } + throw InvalidInputException( + "The partition data callback of table function %s reported a different partitioning " + "column value at index %llu without changing the batch index.", + function_name, i); + } + return; + } + } + last_batch_index = data.batch_index; + last_partition_values.clear(); + for (auto &entry : data.partition_data) { + last_partition_values.push_back(entry.min_val); + } + } + +private: + bool partition_columns_resolved = false; + vector partition_columns; + optional_idx last_batch_index; + vector last_partition_values; +}; + +class CV2TableInitGlobalInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + const vector *in_scan_columns = nullptr; + + duckdb_v2_opaque out_global_state = {}; + idx_t out_max_threads = 1; +}; + +static auto Convert(duckdb_v2_data_source_init_global_info_handle info) -> CV2TableInitGlobalInfo * { + return reinterpret_cast(info); +} +static auto Convert(CV2TableInitGlobalInfo *info) -> duckdb_v2_data_source_init_global_info_handle { + return reinterpret_cast(info); +} + +class CV2TableInitLocalInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + void *in_global_state = nullptr; + const vector *in_scan_columns = nullptr; + + duckdb_v2_opaque out_local_state = {}; +}; + +static auto Convert(duckdb_v2_data_source_init_local_info_handle info) -> CV2TableInitLocalInfo * { + return reinterpret_cast(info); +} +static auto Convert(CV2TableInitLocalInfo *info) -> duckdb_v2_data_source_init_local_info_handle { + return reinterpret_cast(info); +} + +class CV2TableExecInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + void *in_global_state = nullptr; + void *in_local_state = nullptr; + const vector *in_scan_columns = nullptr; + + DataChunk *output = nullptr; +}; + +static auto Convert(duckdb_v2_data_source_exec_info_handle info) -> CV2TableExecInfo * { + return reinterpret_cast(info); +} +static auto Convert(CV2TableExecInfo *info) -> duckdb_v2_data_source_exec_info_handle { + return reinterpret_cast(info); +} + +class CV2TableProgressInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + void *in_global_state = nullptr; + + double out_progress = 0.0; +}; + +static auto Convert(duckdb_v2_data_source_progress_info_handle info) -> CV2TableProgressInfo * { + return reinterpret_cast(info); +} +static auto Convert(CV2TableProgressInfo *info) -> duckdb_v2_data_source_progress_info_handle { + return reinterpret_cast(info); +} + +class CV2TableMetricsInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + void *in_global_state = nullptr; + + //! The metrics the callback reported, by name, applied to the scan's metrics afterwards + vector> out_metrics; +}; + +//! The operator metrics a table function scan can report, by the name the profiler uses for them +static auto CV2TableApplyMetric(OperatorMetrics &metrics, const string &name, uint64_t value) -> bool { + if (name == MetricOperatorRowsScanned::Name) { + metrics.rows_scanned = value; + } else if (name == MetricOperatorRowGroupsScanned::Name) { + metrics.row_groups_scanned = value; + } else if (name == MetricOperatorTotalRowGroupsToScan::Name) { + metrics.total_row_groups_to_scan = value; + } else if (name == MetricOperatorBytesScanned::Name) { + metrics.bytes_scanned = value; + metrics.bytes_scanned_reported = true; + } else { + return false; + } + return true; +} + +static void CV2TableAddMetric(CV2TableMetricsInfo &info, const char *name, idx_t name_length, uint64_t value) { + string metric_name(name, name_length); + OperatorMetrics probe; + if (!CV2TableApplyMetric(probe, metric_name, value)) { + throw InvalidInputException("\"%s\" is not a metric a table function can report, expected one of " + "\"%s\", \"%s\", \"%s\" or \"%s\"", + metric_name, MetricOperatorRowsScanned::Name, MetricOperatorRowGroupsScanned::Name, + MetricOperatorTotalRowGroupsToScan::Name, MetricOperatorBytesScanned::Name); + } + info.out_metrics.emplace_back(std::move(metric_name), value); +} + +static auto Convert(duckdb_v2_data_source_metrics_info_handle info) -> CV2TableMetricsInfo * { + return reinterpret_cast(info); +} +static auto Convert(CV2TableMetricsInfo *info) -> duckdb_v2_data_source_metrics_info_handle { + return reinterpret_cast(info); +} + +class CV2TableClaimBatchInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + void *in_global_state = nullptr; + void *in_local_state = nullptr; + + bool out_claimed = false; +}; + +static auto Convert(duckdb_v2_data_source_claim_batch_info_handle info) -> CV2TableClaimBatchInfo * { + return reinterpret_cast(info); +} +static auto Convert(CV2TableClaimBatchInfo *info) -> duckdb_v2_data_source_claim_batch_info_handle { + return reinterpret_cast(info); +} + +class CV2TablePartitionDataInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + void *in_global_state = nullptr; + void *in_local_state = nullptr; + const OperatorPartitionInfo *in_partition_info = nullptr; + const vector *in_partition_columns = nullptr; + const vector *in_column_types = nullptr; + + optional_idx out_batch_index; + vector out_partition_value_set; + vector out_partition_values; +}; + +static auto Convert(duckdb_v2_data_source_partition_data_info_handle info) -> CV2TablePartitionDataInfo * { + return reinterpret_cast(info); +} +static auto Convert(CV2TablePartitionDataInfo *info) -> duckdb_v2_data_source_partition_data_info_handle { + return reinterpret_cast(info); +} + +//! Virtual columns are told apart from declared ones in the column lists of the scan by this plus their value in the +//! public enum +static constexpr column_t CV2_VIRTUAL_COLUMN_START = UINT64_C(9223372036854775808); + +//! The index the scan's column lists hold for a virtual column of the engine, which is invalid if there is no such +//! virtual column +static auto CV2VirtualColumnIndex(column_t engine_id) -> column_t { + if (engine_id == MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER) { + return CV2_VIRTUAL_COLUMN_START + DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER; + } + throw InternalException("Unsupported virtual column %llu in a table function scan", engine_id); +} + +//! The index the function sees for a column of the scan. A virtual column of a function wrapped in a multi-file +//! function has an index of its own past the declared columns, and the wrapper tells which virtual column that is. +auto CV2ScanColumnIndex(column_t column, optional_ptr> virtual_columns) + -> column_t { + if (virtual_columns) { + auto entry = virtual_columns->find(column); + if (entry != virtual_columns->end()) { + return CV2VirtualColumnIndex(entry->second); + } + } + return IsVirtualColumn(column) ? CV2VirtualColumnIndex(column) : column; +} + +//! The declared column behind each vector of the output chunk. With projection pushdown the engine sizes the chunk +//! to the columns it asked for; without it the chunk always holds every declared column, whatever the engine asked. +static auto CV2TableScanColumns(const CV2DataSourceBindData &bind_data, const TableFunctionInitInput &input) + -> vector { + if (bind_data.scan->projection_pushdown) { + if (input.column_ids.empty()) { + // the scan only produces rows (e.g. for count(*)) - the function produces them through its first column + return {0}; + } + const auto &virtual_columns = TableFunctionFileInitInput::Get(input).virtual_columns; + vector columns; + columns.reserve(input.column_ids.size()); + for (auto column : input.column_ids) { + columns.push_back(CV2ScanColumnIndex(column, virtual_columns)); + } + return columns; + } + vector columns; + for (idx_t i = 0; i < bind_data.column_types.size(); i++) { + columns.push_back(i); + } + return columns; +} + +//! The filters of the query that apply to a single column of the scan, as the position of the column among the scan's +//! columns and the predicate on it. A filter the engine applies speculatively is handed out as the predicate it +//! applies. +static auto CV2TableFilters(const TableFunctionInitInput &input) -> vector> { + //! The predicate behind a filter that is applied speculatively, which wraps it + auto unwrap = [](Expression &expression) -> Expression & { + reference current(expression); + while (current.get().GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { + auto &function = current.get().Cast(); + if (!function.BindInfo()) { + break; + } + auto &name = function.Function().GetName(); + if (name == OptionalFilterScalarFun::NAME) { + current = *function.BindInfo()->Cast().child_filter_expr; + } else if (name == SelectivityOptionalFilterScalarFun::NAME) { + current = *function.BindInfo()->Cast().child_filter_expr; + } else { + break; + } + } + return current.get(); + }; + vector> result; + if (!input.filters) { + return result; + } + for (auto &entry : *input.filters) { + auto &filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "CV2TableFilters"); + result.emplace_back(entry.GetIndex().GetIndex(), &unwrap(*filter.expr)); + } + return result; +} + +//! Offers the filters the scan applies to the filter pushdown callback once more, for the scan that is about to start. +//! The callback only sees the predicates at optimization time, which a function wrapped in a multi-file function does +//! not: the optimizer asks the wrapper. The engine applies the filters to what the function produces, so accepting a +//! predicate has no effect here. +static auto CV2TableOfferFilters(ClientContext &context, const CV2DataSourceBindData &bind_data, + const TableFunctionInitInput &input) -> void { + const auto &scan = *bind_data.scan; + const auto &file_input = TableFunctionFileInitInput::Get(input); + auto filters = CV2TableFilters(input); + if (file_input.expression_map) { + // the predicate on a converted column is written against the converted values, not those of the file + vector> on_file_columns; + for (auto &entry : filters) { + if (file_input.expression_map->find(ProjectionIndex(entry.first)) == file_input.expression_map->end()) { + on_file_columns.push_back(entry); + } + } + filters = std::move(on_file_columns); + } + if (filters.empty()) { + return; + } + // A table filter refers to the one column it applies to by a physical reference; the callback is offered column + // references, like at optimization time, which it resolves through the column list + vector> predicates; + for (auto &entry : filters) { + auto predicate = entry.second->Copy(); + ExpressionIterator::EnumerateExpression(predicate, [&](unique_ptr &child) { + if (child->GetExpressionClass() == ExpressionClass::BOUND_REF) { + child = make_uniq(child->GetAlias(), child->GetReturnType(), + ColumnBinding(TableIndex(0), ProjectionIndex(entry.first))); + } + }); + predicates.push_back(std::move(predicate)); + } + + CV2TableFilterPushdownInfo args = {}; + args.in_user_data = scan.user_data ? scan.user_data->GetData() : nullptr; + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + args.in_filters = &predicates; + for (auto column : input.column_ids) { + args.in_column_ids.push_back(CV2ScanColumnIndex(column, file_input.virtual_columns)); + } + args.out_handled.resize(predicates.size(), false); + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context); + scan.filter_pushdown_cb(Convert(&args), Convert(&callback_context), &err_ptr); + if (err.HasError()) { + err.ThrowAsException(); + } +} + +auto CV2DataSourceInitGlobal(ClientContext &context, TableFunctionInitInput &input) + -> unique_ptr { + const auto &bind_data = input.bind_data->Cast(); + const auto &info = *bind_data.source; + + // Always produced, even without a callback: it carries the thread count and column list the scan runs with. + auto result = make_uniq(); + result->scan_columns = CV2TableScanColumns(bind_data, input); + if (bind_data.scan->ReadsFilters()) { + CV2TableOfferFilters(context, bind_data, input); + } + if (!info.init_global_cb) { + return std::move(result); + } + + CV2TableInitGlobalInfo args = {}; + args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + args.in_scan_columns = &result->scan_columns; + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context); + info.init_global_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (args.out_global_state.ptr) { + result->handle = + CV2UserData(args.out_global_state.ptr, args.out_global_state.destroy, args.out_global_state.equals); + } + result->max_threads = args.out_max_threads; + + // Throw after taking ownership of the state, so that it is destroyed even if we error. + if (err.HasError()) { + err.ThrowAsException(); + } + + return std::move(result); +} + +//! Prepares the conversions the multi-file scan asks for (see TableFunctionFileInitInput::expression_map). The function +//! produces the values of its file, and the conversion turns them into the values the filters are written against. +static auto CV2TableInitConvertedColumns(ClientContext &context, const CV2DataSourceBindData &bind_data, + const TableFunctionInitInput &input, const vector &scan_columns, + CV2DataSourceLocalState &local_state) -> void { + const auto &expression_map = TableFunctionFileInitInput::Get(input).expression_map; + if (!expression_map || expression_map->empty()) { + return; + } + vector file_types; + for (auto column : scan_columns) { + file_types.push_back(IsVirtualColumn(column) ? LogicalType::BIGINT : bind_data.column_types[column]); + } + for (auto &entry : *expression_map) { + const auto position = entry.first.GetIndex(); + const auto input_count = entry.second.column_indexes.size(); + if (position + input_count > file_types.size()) { + throw InternalException("Converted column %llu of a table function scan is out of range", position); + } + CV2DataSourceLocalState::ConvertedColumn converted; + converted.position = position; + converted.expression = entry.second.expression->Copy(); + converted.executor = make_uniq(context, *converted.expression); + vector input_types(file_types.begin() + NumericCast(position), + file_types.begin() + NumericCast(position + input_count)); + converted.input = make_uniq(); + converted.input->InitializeEmpty(input_types); + local_state.converted_columns.push_back(std::move(converted)); + } + local_state.converted_position.assign(file_types.size(), false); + for (auto &converted : local_state.converted_columns) { + local_state.converted_position[converted.position] = true; + } + local_state.file_chunk = make_uniq(); + local_state.file_chunk->Initialize(context, file_types); +} + +//! Produces the converted columns from what the function produced in the types of its file +static auto CV2TableConvertColumns(CV2DataSourceLocalState &local_state, DataChunk &output) -> void { + auto &file_chunk = *local_state.file_chunk; + D_ASSERT(local_state.converted_position.size() == output.ColumnCount()); + for (idx_t i = 0; i < output.ColumnCount(); i++) { + if (!local_state.converted_position[i]) { + output.data[i].Reference(file_chunk.data[i]); + } + } + for (auto &converted : local_state.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(file_chunk.size()); + converted.executor->ExecuteExpression(converted_input, output.data[converted.position]); + } + output.SetChildCardinality(file_chunk.size()); +} + +auto CV2DataSourceInitLocal(ExecutionContext &context, TableFunctionInitInput &input, + GlobalTableFunctionState *global_state) -> unique_ptr { + const auto &bind_data = input.bind_data->Cast(); + const auto &info = *bind_data.source; + + // Always produced, even without a callback: get_partition_data keeps its per-thread guard state here. + auto result = make_uniq(); + if (bind_data.scan->ReadsFilters() && input.filters) { + // The function only reads the filters, so it is left to the engine to apply them to what it produces + for (auto &entry : *input.filters) { + result->filters.emplace_back(entry.GetIndex().GetIndex(), + TableFilterState::Initialize(context.client, entry.Filter())); + } + } + auto scan_columns = CV2TableScanColumns(bind_data, input); + if (bind_data.scan->ReadsFilters()) { + CV2TableInitConvertedColumns(context.client, bind_data, input, scan_columns, *result); + } + if (!info.init_local_cb) { + return std::move(result); + } + + CV2TableInitLocalInfo args = {}; + args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + args.in_scan_columns = &scan_columns; + if (global_state) { + args.in_global_state = global_state->Cast().handle.GetData(); + } + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context.client); + info.init_local_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (args.out_local_state.ptr) { + result->handle = + CV2UserData(args.out_local_state.ptr, args.out_local_state.destroy, args.out_local_state.equals); + } + + // Throw after taking ownership of the state, so that it is destroyed even if we error. + if (err.HasError()) { + err.ThrowAsException(); + } + + return std::move(result); +} + +//! Calls the claim batch callback for the local state of the given input - returns whether a batch was claimed +static auto CV2TableClaimNextBatch(ClientContext &context, TableFunctionInput &input) -> bool { + const auto &bind_data = input.bind_data->Cast(); + const auto &info = *bind_data.source; + auto &local_state = input.local_state->Cast(); + + CV2TableClaimBatchInfo args = {}; + args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + if (input.global_state) { + args.in_global_state = input.global_state->Cast().handle.GetData(); + } + args.in_local_state = local_state.handle.GetData(); + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context); + info.claim_batch_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (err.HasError()) { + err.ThrowAsException(); + } + local_state.batch_claimed = args.out_claimed; + return args.out_claimed; +} + +//! The caller claims the batches of this local state itself - every exec then scans the claimed batch only +auto CV2DataSourceClaimBatch(ClientContext &context, TableFunctionInput &input) -> bool { + input.local_state->Cast().claimed_externally = true; + return CV2TableClaimNextBatch(context, input); +} + +static auto CV2TableExecBatch(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void; + +auto CV2DataSourceExec(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { + const auto &info = *input.bind_data->Cast().source; + if (!info.claim_batch_cb) { + CV2TableExecBatch(context, input, output); + return; + } + auto &local_state = input.local_state->Cast(); + if (local_state.claimed_externally) { + // an empty chunk ends the batch, after which the caller claims the next one + CV2TableExecBatch(context, input, output); + return; + } + // nobody claims the batches for us - move on to the next batch whenever the current one is exhausted + while (true) { + if (!local_state.batch_claimed && !CV2TableClaimNextBatch(context, input)) { + return; + } + CV2TableExecBatch(context, input, output); + if (output.size() > 0) { + return; + } + local_state.batch_claimed = false; + } +} + +static auto CV2TableExecBatchOnce(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void; + +//! Runs the exec callback and, for a function that reads the filters of the query, applies them to what it produced: +//! the function is free to produce rows that do not pass them +static auto CV2TableExecBatch(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { + auto &local_state = input.local_state->Cast(); + while (true) { + if (local_state.file_chunk) { + local_state.file_chunk->Reset(); + CV2TableExecBatchOnce(context, input, *local_state.file_chunk); + CV2TableConvertColumns(local_state, output); + } else { + CV2TableExecBatchOnce(context, input, output); + } + if (local_state.filters.empty() || output.size() == 0) { + return; + } + const auto count = output.size(); + idx_t remaining = count; + SelectionVector selection; + selection.Initialize(nullptr); + for (auto &filter : local_state.filters) { + if (remaining == 0) { + break; + } + ColumnSegment::FilterSelection(selection, output.data[filter.first], *filter.second, count, remaining); + } + if (remaining == count) { + return; + } + if (remaining > 0) { + output.Slice(selection, remaining); + return; + } + // Nothing of this batch passed, but an empty chunk means that the batch is exhausted + output.Reset(); + context.FastInterruptCheck(); + } +} + +static auto CV2TableExecBatchOnce(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { + const auto &bind_data = input.bind_data->Cast(); + const auto &info = *bind_data.source; + + CV2TableExecInfo args = {}; + args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + if (input.global_state) { + auto &global_state = input.global_state->Cast(); + args.in_global_state = global_state.handle.GetData(); + args.in_scan_columns = &global_state.scan_columns; + } + auto &local_state = input.local_state->Cast(); + args.in_local_state = local_state.handle.GetData(); + reference target(output); + if (output.ColumnCount() == 0) { + // the scan requests no columns (e.g. for count(*)), only rows - the function writes them into its first column + if (!local_state.row_chunk) { + local_state.row_chunk = make_uniq(); + local_state.row_chunk->Initialize(context, {bind_data.column_types[0]}); + } + local_state.row_chunk->Reset(); + target = *local_state.row_chunk; + } + args.output = &target.get(); + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context); + info.exec_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (err.HasError()) { + err.ThrowAsException(); + } + + // The vector write API sizes per vector, while the engine reads the chunk's cardinality. Callers typically size + // only the first vector and write the rest through direct buffer writes, so take the first vector's size as the + // batch's row count and propagate it to the others. A table function always has at least one result column. + auto row_count = target.get().data[0].size(); + if (output.ColumnCount() == 0) { + output.SetCardinalityUnsafe(row_count); + return; + } + output.SetChildCardinality(row_count); +} + +static auto CV2DataSourceProgress(ClientContext &context, const FunctionData *bind_data, + const GlobalTableFunctionState *global_state) -> double { + const auto &data = bind_data->Cast(); + const auto &info = *data.source; + + CV2TableProgressInfo args = {}; + args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = data.handle ? data.handle->GetData() : nullptr; + if (global_state) { + // The callback runs concurrently with the scan, so the state it reads is the shared one, unsynchronized. + args.in_global_state = global_state->Cast().handle.GetData(); + } + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context); + info.progress_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (err.HasError()) { + err.ThrowAsException(); + } + + // The API contract is a 0.0-1.0 fraction, the engine reads a 0-100 percentage. + return MinValue(MaxValue(args.out_progress, 0.0), 1.0) * 100.0; +} + +static auto CV2DataSourceGetMetrics(TableFunctionGetMetricsInput &input) -> void { + if (!input.bind_data) { + return; + } + const auto &data = input.bind_data->Cast(); + const auto &info = *data.source; + + CV2TableMetricsInfo args = {}; + args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = data.handle ? data.handle->GetData() : nullptr; + if (input.global_state) { + // The callback can run while the scan does, so the state it reads is the shared one, unsynchronized. + args.in_global_state = input.global_state->Cast().handle.GetData(); + } + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(input.context); + info.metrics_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (err.HasError()) { + err.ThrowAsException(); + } + + for (auto &metric : args.out_metrics) { + CV2TableApplyMetric(input.operator_metrics, metric.first, metric.second); + } +} + +//! Batch index is required on every call, even when unrequested: the pipeline range-checks it regardless. +static auto CV2TakePartitionData(CV2TablePartitionDataInfo &args, const Identifier &function_name) + -> OperatorPartitionData { + if (!args.out_batch_index.IsValid()) { + throw InvalidInputException("The partition data callback of table function %s did not set a batch index.", + function_name); + } + OperatorPartitionData result(args.out_batch_index.GetIndex()); + result.partition_data.reserve(args.out_partition_values.size()); + for (idx_t i = 0; i < args.out_partition_values.size(); i++) { + if (!args.out_partition_value_set[i]) { + throw InvalidInputException("The partition data callback of table function %s did not set the " + "partitioning column value at index %llu.", + function_name, i); + } + result.partition_data.emplace_back(std::move(args.out_partition_values[i])); + } + return result; +} + +static auto CV2DataSourceGetPartitionData(ClientContext &context, TableFunctionGetPartitionInput &input) + -> OperatorPartitionData { + const auto &bind_data = input.bind_data->Cast(); + const auto &info = *bind_data.source; + + auto &global_state = input.global_state->Cast(); + auto &local_state = input.local_state->Cast(); + + CV2TablePartitionDataInfo args = {}; + args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + args.in_global_state = global_state.handle.GetData(); + args.in_local_state = local_state.handle.GetData(); + args.in_partition_info = &input.partition_info; + // The planner resolves these to scan positions, unlike get_partition_info's, which it resolves to declared + // columns; the callback is promised declared columns in both. + args.in_partition_columns = &local_state.PartitionColumns(input.partition_info, global_state.scan_columns); + args.in_column_types = &bind_data.column_types; + args.out_partition_value_set.resize(args.in_partition_columns->size(), false); + args.out_partition_values.resize(args.in_partition_columns->size()); + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context); + info.partition_data_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (err.HasError()) { + err.ThrowAsException(); + } + + auto result = CV2TakePartitionData(args, info.name); + local_state.CheckPartitionData(info.name, result); + return result; +} + +void CV2DataSourceInfo::Verify() const { + if (!exec_cb) { + throw InvalidInputException("Exec callback must be set for the data source."); + } +} + +void CV2DataSourceInfo::ConfigureScan(TableFunction &function) const { + function.function = CV2DataSourceExec; + function.init_global = CV2DataSourceInitGlobal; + function.init_local = CV2DataSourceInitLocal; + if (progress_cb) { + function.table_scan_progress = CV2DataSourceProgress; + } + if (partition_data_cb) { + function.get_partition_data = CV2DataSourceGetPartitionData; + } + if (metrics_cb) { + function.get_metrics = CV2DataSourceGetMetrics; + } +} + +} // namespace duckdb::capiv2 + +//---------------------------------------------------------------------------------------------------------------------- +// Public Functions +//---------------------------------------------------------------------------------------------------------------------- + +using namespace duckdb::capiv2; + +DUCKDB_V2_ERROR +duckdb_v2_data_source_init_global_get_user_data(duckdb_v2_data_source_init_global_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_init_global_get_bind_data(duckdb_v2_data_source_init_global_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_init_global_set_global_state(duckdb_v2_data_source_init_global_info_handle info, + duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { Convert(info)->out_global_state = *data; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_init_global_set_max_threads(duckdb_v2_data_source_init_global_info_handle info, idx_t max_threads, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + return WithErrorHandler(err, [&]() { + if (max_threads == 0) { + throw duckdb::InvalidInputException("The maximum number of threads must be at least 1"); + } + Convert(info)->out_max_threads = max_threads; + }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_init_global_get_column_count(duckdb_v2_data_source_init_global_info_handle info, idx_t *count, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(count); + return WithErrorHandler(err, [&]() { *count = Convert(info)->in_scan_columns->size(); }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_init_global_get_column_index(duckdb_v2_data_source_init_global_info_handle info, idx_t index, + idx_t *column_index, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(column_index); + return WithErrorHandler(err, [&]() { + const auto &columns = *Convert(info)->in_scan_columns; + if (index >= columns.size()) { + throw duckdb::InvalidInputException( + "Index out of bounds in duckdb_v2_data_source_init_global_get_column_index"); + } + *column_index = columns[index]; + }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_init_local_get_user_data(duckdb_v2_data_source_init_local_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_init_local_get_bind_data(duckdb_v2_data_source_init_local_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_init_local_get_global_state(duckdb_v2_data_source_init_local_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_init_local_set_local_state(duckdb_v2_data_source_init_local_info_handle info, + duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { Convert(info)->out_local_state = *data; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_init_local_get_column_count(duckdb_v2_data_source_init_local_info_handle info, idx_t *count, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(count); + return WithErrorHandler(err, [&]() { *count = Convert(info)->in_scan_columns->size(); }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_init_local_get_column_index(duckdb_v2_data_source_init_local_info_handle info, idx_t index, + idx_t *column_index, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(column_index); + return WithErrorHandler(err, [&]() { + const auto &columns = *Convert(info)->in_scan_columns; + if (index >= columns.size()) { + throw duckdb::InvalidInputException( + "Index out of bounds in duckdb_v2_data_source_init_local_get_column_index"); + } + *column_index = columns[index]; + }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_user_data(duckdb_v2_data_source_exec_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_bind_data(duckdb_v2_data_source_exec_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_global_state(duckdb_v2_data_source_exec_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_local_state(duckdb_v2_data_source_exec_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_local_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_output_chunk(duckdb_v2_data_source_exec_info_handle info, + duckdb_v2_data_chunk_handle *chunk, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(chunk); + return WithErrorHandler(err, [&]() { *chunk = Convert(Convert(info)->output); }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_column_count(duckdb_v2_data_source_exec_info_handle info, idx_t *count, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(count); + return WithErrorHandler(err, [&]() { *count = Convert(info)->in_scan_columns->size(); }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_column_index(duckdb_v2_data_source_exec_info_handle info, idx_t index, + idx_t *column_index, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(column_index); + return WithErrorHandler(err, [&]() { + const auto &columns = *Convert(info)->in_scan_columns; + if (index >= columns.size()) { + throw duckdb::InvalidInputException("Index out of bounds in duckdb_v2_data_source_exec_get_column_index"); + } + *column_index = columns[index]; + }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_progress_get_user_data(duckdb_v2_data_source_progress_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_progress_get_bind_data(duckdb_v2_data_source_progress_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_progress_get_global_state(duckdb_v2_data_source_progress_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_progress_set_progress(duckdb_v2_data_source_progress_info_handle info, + double progress, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + return WithErrorHandler(err, [&]() { Convert(info)->out_progress = progress; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_metrics_get_user_data(duckdb_v2_data_source_metrics_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_metrics_get_bind_data(duckdb_v2_data_source_metrics_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_metrics_get_global_state(duckdb_v2_data_source_metrics_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_metrics_set(duckdb_v2_data_source_metrics_info_handle info, const char *name, + idx_t name_length, uint64_t value, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(name); + return WithErrorHandler(err, [&]() { CV2TableAddMetric(*Convert(info), name, name_length, value); }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_partition_data_get_user_data(duckdb_v2_data_source_partition_data_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_partition_data_get_bind_data(duckdb_v2_data_source_partition_data_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_partition_data_get_global_state(duckdb_v2_data_source_partition_data_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_partition_data_get_local_state(duckdb_v2_data_source_partition_data_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_local_state; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_partition_data_requires_batch_index(duckdb_v2_data_source_partition_data_info_handle info, + bool *required, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(required); + return WithErrorHandler(err, [&]() { *required = Convert(info)->in_partition_info->RequiresBatchIndex(); }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_partition_data_requires_partition_columns(duckdb_v2_data_source_partition_data_info_handle info, + bool *required, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(required); + return WithErrorHandler(err, [&]() { *required = Convert(info)->in_partition_info->RequiresPartitionColumns(); }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_partition_data_get_partition_column_count(duckdb_v2_data_source_partition_data_info_handle info, + idx_t *count, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(count); + return WithErrorHandler(err, [&]() { *count = Convert(info)->in_partition_columns->size(); }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_partition_data_get_partition_column_index(duckdb_v2_data_source_partition_data_info_handle info, + idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(column_index); + return WithErrorHandler(err, [&]() { + const auto &columns = *Convert(info)->in_partition_columns; + if (index >= columns.size()) { + throw duckdb::InvalidInputException( + "Index out of bounds in duckdb_v2_data_source_partition_data_get_partition_column_index"); + } + *column_index = columns[index]; + }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_partition_data_set_batch_index(duckdb_v2_data_source_partition_data_info_handle info, + idx_t batch_index, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + return WithErrorHandler(err, [&]() { + // ToPipelinePartitionData adds base + 1 and throws an InternalException from BATCH_INCREMENT - 1 on. + if (batch_index >= duckdb::PipelineBuildState::BATCH_INCREMENT - 2) { + throw duckdb::InvalidInputException( + "duckdb_v2_data_source_partition_data_set_batch_index: batch_index %llu must be less than " + "%llu", + batch_index, duckdb::PipelineBuildState::BATCH_INCREMENT - 2); + } + Convert(info)->out_batch_index = batch_index; + }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_partition_data_set_partition_value(duckdb_v2_data_source_partition_data_info_handle info, + idx_t index, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(value); + return WithErrorHandler(err, [&]() { + auto &args = *Convert(info); + if (index >= args.out_partition_values.size()) { + throw duckdb::InvalidInputException( + "Index out of bounds in duckdb_v2_data_source_partition_data_set_partition_value"); + } + const auto &expected_type = (*args.in_column_types)[(*args.in_partition_columns)[index]]; + const auto &actual = *Convert(value); + if (actual.type() != expected_type) { + throw duckdb::InvalidInputException( + "duckdb_v2_data_source_partition_data_set_partition_value: expected type %s for the " + "partitioning column at index %llu, got %s", + expected_type.ToString(), index, actual.type().ToString()); + } + args.out_partition_values[index] = actual; + args.out_partition_value_set[index] = true; + }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_claim_batch_get_user_data(duckdb_v2_data_source_claim_batch_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_claim_batch_get_bind_data(duckdb_v2_data_source_claim_batch_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_claim_batch_get_global_state(duckdb_v2_data_source_claim_batch_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_claim_batch_get_local_state(duckdb_v2_data_source_claim_batch_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_local_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_claim_batch_set_claimed(duckdb_v2_data_source_claim_batch_info_handle info, + bool claimed, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + return WithErrorHandler(err, [&]() { Convert(info)->out_claimed = claimed; }); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Data sources +//---------------------------------------------------------------------------------------------------------------------- + +DUCKDB_V2_ERROR duckdb_v2_data_source_create(duckdb_v2_factory_handle factory, duckdb_v2_data_source_handle *source, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(factory); + DUCKDB_CHECK_ARG(source); + *source = nullptr; + return WithErrorHandler(err, [&]() { + auto result = duckdb::make_uniq(Convert(factory)->GetDatabase()); + *source = Convert(result.release()); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_set_user_data(duckdb_v2_data_source_handle source, duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(source); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { + Convert(source)->info.user_data = duckdb::make_shared_ptr(data->ptr, data->destroy, data->equals); + }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_set_init_global_callback(duckdb_v2_data_source_handle source, + duckdb_v2_data_source_init_global_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(source); + return WithErrorHandler(err, [&]() { Convert(source)->info.init_global_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_set_init_local_callback(duckdb_v2_data_source_handle source, + duckdb_v2_data_source_init_local_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(source); + return WithErrorHandler(err, [&]() { Convert(source)->info.init_local_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_set_exec_callback(duckdb_v2_data_source_handle source, + duckdb_v2_data_source_exec_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(source); + return WithErrorHandler(err, [&]() { Convert(source)->info.exec_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_set_progress_callback(duckdb_v2_data_source_handle source, + duckdb_v2_data_source_progress_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(source); + return WithErrorHandler(err, [&]() { Convert(source)->info.progress_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_set_metrics_callback(duckdb_v2_data_source_handle source, + duckdb_v2_data_source_metrics_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(source); + return WithErrorHandler(err, [&]() { Convert(source)->info.metrics_cb = callback; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_set_partition_data_callback(duckdb_v2_data_source_handle source, + duckdb_v2_data_source_partition_data_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(source); + return WithErrorHandler(err, [&]() { Convert(source)->info.partition_data_cb = callback; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_data_source_set_claim_batch_callback(duckdb_v2_data_source_handle source, + duckdb_v2_data_source_claim_batch_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(source); + return WithErrorHandler(err, [&]() { Convert(source)->info.claim_batch_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_destroy(duckdb_v2_data_source_handle *source) { + return WithErrorHandler(nullptr, [&]() { + if (!source) { + return; + } + if (*source) { + delete Convert(*source); + *source = nullptr; + } + }); +} diff --git a/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp b/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp index 8c83df6b6..1290bd775 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp @@ -193,9 +193,8 @@ DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_handle file_sys duckdb::OpenFileInfo info(duckdb::string(Convert(file_path, file_path_length))); info.extended_info = opts.extended_info; - // No opener is passed: FileSystem::GetFileSystem hands back the context's own OpenerFileSystem, which - // pushes the opener itself -- which is how a remote file system reaches settings and secrets. Supplying one - // here is rejected outright ("the opener is pushed automatically"). + // FileSystem::GetFileSystem hands back the context's own bound FileSystem, which pushes the opener itself -- + // which is how a remote file system reaches settings and secrets. auto handle = slot.fs.OpenFile(info, opts.flags); if (!handle) { throw duckdb::IOException("Failed to open file: %s", info.path); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp index 5722794d4..b478b16b0 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp @@ -1,5 +1,6 @@ #include "duckdb/common/optional_idx.hpp" #include "duckdb/main/capi_v2/capi_v2_internal.hpp" +#include "duckdb/main/capi_v2/capi_v2_data_source_internal.hpp" #include "duckdb/catalog/catalog.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/execution/execution_context.hpp" @@ -23,10 +24,12 @@ class CV2CopyFunctionInfo final : public CopyFunctionInfo { duckdb_v2_copy_to_statistics_callback_fn to_statistics_cb = nullptr; // COPY ... FROM duckdb_v2_copy_from_bind_callback_fn from_bind_cb = nullptr; - duckdb_v2_copy_from_init_global_callback_fn from_init_global_cb = nullptr; - duckdb_v2_copy_from_init_local_callback_fn from_init_local_cb = nullptr; - duckdb_v2_copy_from_exec_callback_fn from_exec_cb = nullptr; - duckdb_v2_copy_from_progress_callback_fn from_progress_cb = nullptr; + //! The data source the COPY FROM side scans with. The bind data of a statement refers to it, which the function + //! outlives. + CV2DataSourceInfo from_source; + bool from_source_set = false; + //! COPY FROM pushes nothing down: the scan produces every column the bind callback receives + CV2ScanOptions from_scan; shared_ptr user_data = nullptr; @@ -35,7 +38,7 @@ class CV2CopyFunctionInfo final : public CopyFunctionInfo { to_statistics_cb; } bool HasCopyFrom() const { - return from_bind_cb || from_init_global_cb || from_init_local_cb || from_exec_cb || from_progress_cb; + return from_bind_cb || from_source_set; } }; @@ -48,7 +51,7 @@ class CV2CopyFromTableInfo final : public TableFunctionInfo { shared_ptr info; }; -//! The bind data of a bound COPY statement, in either direction. Besides the user's own bind data it shares +//! The bind data of a bound COPY TO statement. Besides the user's own bind data it shares //! ownership of the function info: the later hooks only receive the bind data, so it is their only route to the //! callbacks. class CV2CopyFunctionData final : public FunctionData { @@ -56,18 +59,10 @@ class CV2CopyFunctionData final : public FunctionData { shared_ptr handle; shared_ptr info; - // The static estimate a COPY FROM bind callback may set via copy_from_bind_set_cardinality. - idx_t cardinality = 0; - bool cardinality_is_exact = false; - bool cardinality_set = false; - auto Copy() const -> unique_ptr override { auto copy = make_uniq(); copy->handle = handle; copy->info = info; - copy->cardinality = cardinality; - copy->cardinality_is_exact = cardinality_is_exact; - copy->cardinality_set = cardinality_set; return std::move(copy); } @@ -77,6 +72,28 @@ class CV2CopyFunctionData final : public FunctionData { } }; +//! The bind data of a bound COPY FROM statement: what the data source it scans with needs, and the estimate its bind +//! callback may set via copy_from_bind_set_cardinality. It shares ownership of the function info, which the later hooks +//! only reach through the bind data. +class CV2CopyFromData final : public CV2DataSourceBindData { +public: + shared_ptr info; + + idx_t cardinality = 0; + bool cardinality_is_exact = false; + bool cardinality_set = false; + + auto Copy() const -> unique_ptr override { + auto copy = make_uniq(); + CopyTo(*copy); + copy->info = info; + copy->cardinality = cardinality; + copy->cardinality_is_exact = cardinality_is_exact; + copy->cardinality_set = cardinality_set; + return std::move(copy); + } +}; + class CV2CopyToGlobalState final : public GlobalFunctionData { public: CV2UserData handle; @@ -94,21 +111,6 @@ class CV2CopyToBatchData final : public PreparedBatchData { CV2UserData handle; }; -class CV2CopyFromGlobalState final : public GlobalTableFunctionState { -public: - auto MaxThreads() const -> idx_t override { - return max_threads; - } - - CV2UserData handle; - idx_t max_threads = 1; -}; - -class CV2CopyFromLocalState final : public LocalTableFunctionState { -public: - CV2UserData handle; -}; - //! The statement's options, snapshotted for the duration of a bind callback and ordered by name so that indices //! are predictable. using CV2CopyOptionList = vector *>>; @@ -268,71 +270,6 @@ static auto Convert(CV2CopyFromBindInfo *info) -> duckdb_v2_copy_from_bind_info_ return reinterpret_cast(info); } -class CV2CopyFromInitGlobalInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - - duckdb_v2_opaque out_global_state = {}; - idx_t out_max_threads = 1; -}; - -static auto Convert(duckdb_v2_copy_from_init_global_info_handle info) -> CV2CopyFromInitGlobalInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2CopyFromInitGlobalInfo *info) -> duckdb_v2_copy_from_init_global_info_handle { - return reinterpret_cast(info); -} - -class CV2CopyFromInitLocalInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - void *in_global_state = nullptr; - - duckdb_v2_opaque out_local_state = {}; -}; - -static auto Convert(duckdb_v2_copy_from_init_local_info_handle info) -> CV2CopyFromInitLocalInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2CopyFromInitLocalInfo *info) -> duckdb_v2_copy_from_init_local_info_handle { - return reinterpret_cast(info); -} - -class CV2CopyFromExecInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - void *in_global_state = nullptr; - void *in_local_state = nullptr; - - DataChunk *output = nullptr; -}; - -static auto Convert(duckdb_v2_copy_from_exec_info_handle info) -> CV2CopyFromExecInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2CopyFromExecInfo *info) -> duckdb_v2_copy_from_exec_info_handle { - return reinterpret_cast(info); -} - -class CV2CopyFromProgressInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - void *in_global_state = nullptr; - - double out_progress = 0.0; -}; - -static auto Convert(duckdb_v2_copy_from_progress_info_handle info) -> CV2CopyFromProgressInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2CopyFromProgressInfo *info) -> duckdb_v2_copy_from_progress_info_handle { - return reinterpret_cast(info); -} - //---------------------------------------------------------------------------------------------------------------------- // Shared helpers //---------------------------------------------------------------------------------------------------------------------- @@ -594,7 +531,12 @@ static auto CV2CopyFromBind(ClientContext &context, CopyFromFunctionBindInput &i CV2CallbackContext callback_context(context); info.from_bind_cb(Convert(&args), Convert(&callback_context), &err_ptr); - auto result = MakeBindData(function_info, std::move(args.out_bind_data)); + auto result = make_uniq(); + result->info = function_info; + result->handle = std::move(args.out_bind_data); + result->source = &info.from_source; + result->scan = &info.from_scan; + result->column_types = expected_types; result->cardinality = args.out_cardinality; result->cardinality_is_exact = args.out_cardinality_is_exact; result->cardinality_set = args.out_cardinality_set; @@ -604,110 +546,9 @@ static auto CV2CopyFromBind(ClientContext &context, CopyFromFunctionBindInput &i return std::move(result); } -static auto CV2CopyFromInitGlobal(ClientContext &context, TableFunctionInitInput &input) - -> unique_ptr { - const auto &bind_data = *input.bind_data; - const auto &info = GetFunctionInfo(bind_data); - - // Always produced, even without a callback: it carries the thread count the read runs with. - auto result = make_uniq(); - if (!info.from_init_global_cb) { - return std::move(result); - } - - CV2CopyFromInitGlobalInfo args = {}; - args.in_user_data = GetUserData(info); - args.in_bind_data = GetUserBindData(bind_data); - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context); - info.from_init_global_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (args.out_global_state.ptr) { - result->handle = - CV2UserData(args.out_global_state.ptr, args.out_global_state.destroy, args.out_global_state.equals); - } - result->max_threads = args.out_max_threads; - - // Throw after taking ownership of the state, so that it is destroyed even if we error. - if (err.HasError()) { - err.ThrowAsException(); - } - - return std::move(result); -} - -static auto CV2CopyFromInitLocal(ExecutionContext &context, TableFunctionInitInput &input, - GlobalTableFunctionState *global_state) -> unique_ptr { - const auto &bind_data = *input.bind_data; - const auto &info = GetFunctionInfo(bind_data); - - if (!info.from_init_local_cb) { - return nullptr; - } - - CV2CopyFromInitLocalInfo args = {}; - args.in_user_data = GetUserData(info); - args.in_bind_data = GetUserBindData(bind_data); - if (global_state) { - args.in_global_state = global_state->Cast().handle.GetData(); - } - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context.client); - info.from_init_local_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - unique_ptr result = nullptr; - if (args.out_local_state.ptr) { - auto set_result = make_uniq(); - set_result->handle = - CV2UserData(args.out_local_state.ptr, args.out_local_state.destroy, args.out_local_state.equals); - result = std::move(set_result); - } - - // Throw after taking ownership of the state, so that it is destroyed even if we error. - if (err.HasError()) { - err.ThrowAsException(); - } - - return result; -} - -static auto CV2CopyFromExec(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { - const auto &bind_data = *input.bind_data; - const auto &info = GetFunctionInfo(bind_data); - - CV2CopyFromExecInfo args = {}; - args.in_user_data = GetUserData(info); - args.in_bind_data = GetUserBindData(bind_data); - if (input.global_state) { - args.in_global_state = input.global_state->Cast().handle.GetData(); - } - if (input.local_state) { - args.in_local_state = input.local_state->Cast().handle.GetData(); - } - args.output = &output; - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context); - info.from_exec_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (err.HasError()) { - err.ThrowAsException(); - } - - // The vector write API sizes per vector, while the engine reads the chunk's cardinality. Callers typically size - // only the first vector and write the rest through direct buffer writes, so take the first vector's size as the - // batch's row count and propagate it to the others. The target table always has at least one column. - output.SetChildCardinality(output.data[0].size()); -} - static auto CV2CopyFromCardinality(ClientContext &context, const FunctionData *bind_data) -> unique_ptr { - const auto &data = bind_data->Cast(); + const auto &data = bind_data->Cast(); if (!data.cardinality_set) { // No estimate at all: the optimizer falls back on its own defaults. return nullptr; @@ -719,31 +560,6 @@ static auto CV2CopyFromCardinality(ClientContext &context, const FunctionData *b return make_uniq(data.cardinality); } -static auto CV2CopyFromProgress(ClientContext &context, const FunctionData *bind_data, - const GlobalTableFunctionState *global_state) -> double { - const auto &info = GetFunctionInfo(*bind_data); - - CV2CopyFromProgressInfo args = {}; - args.in_user_data = GetUserData(info); - args.in_bind_data = GetUserBindData(*bind_data); - if (global_state) { - // The callback runs concurrently with the read, so the state it reads is the shared one, unsynchronized. - args.in_global_state = global_state->Cast().handle.GetData(); - } - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context); - info.from_progress_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (err.HasError()) { - err.ThrowAsException(); - } - - // The API contract is a 0.0-1.0 fraction, the engine reads a 0-100 percentage. - return MinValue(MaxValue(args.out_progress, 0.0), 1.0) * 100.0; -} - //---------------------------------------------------------------------------------------------------------------------- // Function handle //---------------------------------------------------------------------------------------------------------------------- @@ -777,9 +593,16 @@ class CV2CopyFunction { if (!info.from_bind_cb) { throw InvalidInputException("Bind callback must be set for the COPY FROM side of the function."); } - if (!info.from_exec_cb) { - throw InvalidInputException("Exec callback must be set for the COPY FROM side of the function."); + if (!info.from_source_set) { + throw InvalidInputException("A data source must be set for the COPY FROM side of the function."); } + info.from_source.Verify(); + // Only once nothing can refuse the registration: a refused one leaves the configuration as it was. + // The data source gets the name for its error messages, and the user data of the function unless it has + // some. + info.from_source.name = name; + info.from_source.InheritUserData(info.user_data); + info.from_scan.user_data = info.user_data; } auto function_info = make_shared_ptr(std::move(info)); @@ -803,12 +626,10 @@ class CV2CopyFunction { } if (has_copy_from) { // The engine reads through a table function whose own bind is skipped in favour of copy_from_bind. - TableFunction reader(name, {}, CV2CopyFromExec, nullptr, CV2CopyFromInitGlobal, CV2CopyFromInitLocal); + TableFunction reader(name, {}, CV2DataSourceExec, nullptr, CV2DataSourceInitGlobal, CV2DataSourceInitLocal); + function_info->from_source.ConfigureScan(reader); // Always wired: it serves the static estimate a bind callback may set, which is not known at registration. reader.cardinality = CV2CopyFromCardinality; - if (function_info->from_progress_cb) { - reader.table_scan_progress = CV2CopyFromProgress; - } reader.function_info = make_shared_ptr(function_info); function.copy_from_bind = CV2CopyFromBind; function.copy_from_function = std::move(reader); @@ -1236,32 +1057,19 @@ DUCKDB_V2_ERROR duckdb_v2_copy_from_set_bind_callback(duckdb_v2_copy_function_ha return WithErrorHandler(err, [&]() { Convert(function)->info.from_bind_cb = callback; }); } -DUCKDB_V2_ERROR duckdb_v2_copy_from_set_init_global_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_from_init_global_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.from_init_global_cb = callback; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_set_init_local_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_from_init_local_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.from_init_local_cb = callback; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_set_exec_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_from_exec_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.from_exec_cb = callback; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_set_progress_callback(duckdb_v2_copy_function_handle function, - duckdb_v2_copy_from_progress_callback_fn callback, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_copy_from_set_data_source(duckdb_v2_copy_function_handle function, + duckdb_v2_data_source_handle data_source, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.from_progress_cb = callback; }); + DUCKDB_CHECK_ARG(data_source); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(function); + auto &source = *Convert(data_source); + CheckRegistrationTarget(source.db, self.db, "data source"); + // The function keeps a copy: changing the data source afterwards does not change the function + self.info.from_source = source.info; + self.info.from_source_set = true; + }); } //---------------------------------------------------------------------------------------------------------------------- @@ -1362,147 +1170,6 @@ DUCKDB_V2_ERROR duckdb_v2_copy_from_bind_set_cardinality(duckdb_v2_copy_from_bin }); } -//---------------------------------------------------------------------------------------------------------------------- -// COPY FROM init global -//---------------------------------------------------------------------------------------------------------------------- - -DUCKDB_V2_ERROR duckdb_v2_copy_from_init_global_get_user_data(duckdb_v2_copy_from_init_global_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_init_global_get_bind_data(duckdb_v2_copy_from_init_global_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_init_global_set_global_state(duckdb_v2_copy_from_init_global_info_handle info, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { Convert(info)->out_global_state = *data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_init_global_set_max_threads(duckdb_v2_copy_from_init_global_info_handle info, - idx_t max_threads, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - return WithErrorHandler(err, [&]() { - if (max_threads == 0) { - throw duckdb::InvalidInputException("The maximum number of threads must be at least 1"); - } - Convert(info)->out_max_threads = max_threads; - }); -} - -//---------------------------------------------------------------------------------------------------------------------- -// COPY FROM init local -//---------------------------------------------------------------------------------------------------------------------- - -DUCKDB_V2_ERROR duckdb_v2_copy_from_init_local_get_user_data(duckdb_v2_copy_from_init_local_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_init_local_get_bind_data(duckdb_v2_copy_from_init_local_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_init_local_get_global_state(duckdb_v2_copy_from_init_local_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_init_local_set_local_state(duckdb_v2_copy_from_init_local_info_handle info, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { Convert(info)->out_local_state = *data; }); -} - -//---------------------------------------------------------------------------------------------------------------------- -// COPY FROM exec -//---------------------------------------------------------------------------------------------------------------------- - -DUCKDB_V2_ERROR duckdb_v2_copy_from_exec_get_user_data(duckdb_v2_copy_from_exec_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_exec_get_bind_data(duckdb_v2_copy_from_exec_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_exec_get_global_state(duckdb_v2_copy_from_exec_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_exec_get_local_state(duckdb_v2_copy_from_exec_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_local_state; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_exec_get_output_chunk(duckdb_v2_copy_from_exec_info_handle info, - duckdb_v2_data_chunk_handle *chunk, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(chunk); - return WithErrorHandler(err, [&]() { *chunk = Convert(Convert(info)->output); }); -} - -//---------------------------------------------------------------------------------------------------------------------- -// COPY FROM progress -//---------------------------------------------------------------------------------------------------------------------- - -DUCKDB_V2_ERROR duckdb_v2_copy_from_progress_get_user_data(duckdb_v2_copy_from_progress_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_progress_get_bind_data(duckdb_v2_copy_from_progress_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_progress_get_global_state(duckdb_v2_copy_from_progress_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); -} - -DUCKDB_V2_ERROR duckdb_v2_copy_from_progress_set_progress(duckdb_v2_copy_from_progress_info_handle info, - double progress, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - return WithErrorHandler(err, [&]() { Convert(info)->out_progress = progress; }); -} - //---------------------------------------------------------------------------------------------------------------------- // Register / destroy //---------------------------------------------------------------------------------------------------------------------- diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp index 97a251697..7612aeaa9 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp @@ -1,37 +1,27 @@ #include "duckdb/main/capi_v2/capi_v2_internal.hpp" +#include "duckdb/main/capi_v2/capi_v2_data_source_internal.hpp" #include "duckdb/main/capi_v2/capi_v2_function_internal.hpp" #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry/table_function_catalog_entry.hpp" #include "duckdb/common/multi_file/base_file_reader.hpp" #include "duckdb/common/multi_file/multi_file_data.hpp" -#include "duckdb/common/multi_file/table_function_multi_file.hpp" -#include "duckdb/execution/expression_executor.hpp" -#include "duckdb/execution/partition_info.hpp" -#include "duckdb/function/partition_stats.hpp" -#include "duckdb/main/profiler/metrics.hpp" -#include "duckdb/parallel/pipeline.hpp" -#include "duckdb/parser/parsed_data/create_table_function_info.hpp" -#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/common/multi_file/multi_file_reader.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" -#include "duckdb/planner/filter/expression_filter.hpp" -#include "duckdb/planner/filter/table_filter_functions.hpp" #include "duckdb/planner/operator/logical_get.hpp" -#include "duckdb/planner/table_filter_set.hpp" -#include "duckdb/planner/table_filter_state.hpp" +#include "duckdb/common/multi_file/table_function_multi_file.hpp" +#include "duckdb/parser/parsed_data/create_table_function_info.hpp" #include "duckdb/storage/statistics/node_statistics.hpp" -#include "duckdb/storage/table/column_segment.hpp" namespace duckdb::capiv2 { class CV2TableFunctionInfo; -//! The bind data of a bound call site. Besides the user's own bind data it carries a borrowed pointer back to the -//! function info: the progress hook only receives the bind data, so it is its only route to the callbacks. The -//! registered function owns the info and outlives every call site bound against it. -class CV2TableFunctionData final : public FunctionData { +//! The bind data of a bound call site: what the data source it scans with needs, and what is only known to the call. +//! It also carries a borrowed pointer back to the function info, which the registered function owns and which outlives +//! every call site bound against it. +class CV2TableFunctionData final : public CV2DataSourceBindData { public: - shared_ptr handle; optional_ptr info; // The static estimate a bind callback may set via table_function_bind_set_cardinality. @@ -39,118 +29,18 @@ class CV2TableFunctionData final : public FunctionData { bool cardinality_is_exact = false; bool cardinality_set = false; - vector column_types; vector column_names; auto Copy() const -> unique_ptr override { auto copy = make_uniq(); - copy->handle = handle; + CopyTo(*copy); copy->info = info; copy->cardinality = cardinality; copy->cardinality_is_exact = cardinality_is_exact; copy->cardinality_set = cardinality_set; - copy->column_types = column_types; copy->column_names = column_names; return std::move(copy); } - - auto Equals(const FunctionData &other) const -> bool override { - const auto &other_data = other.Cast(); - return handle && other_data.handle && handle->Equals(*other_data.handle); - } -}; - -class CV2TableGlobalState final : public GlobalTableFunctionState { -public: - auto MaxThreads() const -> idx_t override { - return max_threads; - } - - CV2UserData handle; - idx_t max_threads = 1; - - // The declared column each vector of the output chunk stands for, kept here so the exec callback can ask. - vector scan_columns; -}; - -class CV2TableLocalState final : public LocalTableFunctionState { -public: - CV2UserData handle; - //! Whether the caller claims the batches of this thread (see TableFunction::claim_batch) - bool claimed_externally = false; - //! Whether this thread has claimed a batch it has not exhausted yet - bool batch_claimed = false; - //! Written into by the exec callback when the scan requests no columns, as the function produces its rows through - //! its first column - unique_ptr row_chunk; - //! The filters of the query the engine applies to what the function produces, as the position of the scan column - //! each applies to and its state. Only for a function that reads the filters. - vector>> filters; - //! A column the multi-file scan wants converted before its filters apply: the position of the scan column it - //! produces and the expression doing the conversion, on the columns that follow it in what the function produced - struct ConvertedColumn { - idx_t position; - unique_ptr expression; - unique_ptr executor; - unique_ptr input; - }; - vector converted_columns; - //! For each scan column, whether it is one of the converted columns - vector converted_position; - //! What the function produces, in the types of its file, when some columns are converted afterwards - unique_ptr file_chunk; - - // Requested partition columns as declared columns, fixed for the lifetime of the local state's pipeline. - const vector &PartitionColumns(const OperatorPartitionInfo &partition_info, - const vector &scan_columns) { - if (!partition_columns_resolved) { - for (auto scan_position : partition_info.partition_columns) { - D_ASSERT(scan_position < scan_columns.size()); - partition_columns.push_back(scan_columns[scan_position]); - } - partition_columns_resolved = true; - } - D_ASSERT(partition_columns.size() == partition_info.partition_columns.size()); - return partition_columns; - } - - void CheckPartitionData(const Identifier &function_name, const OperatorPartitionData &data) { - if (last_batch_index.IsValid()) { - auto last_index = last_batch_index.GetIndex(); - // The engine would otherwise raise an InternalException, which invalidates the database. - if (data.batch_index < last_index) { - throw InvalidInputException( - "The partition data callback of table function %s reported batch index %llu after " - "previously reporting %llu on the same thread; the batch index must not decrease.", - function_name, data.batch_index, last_index); - } - // The engine only reads the values when the batch index changes; a changed value would silently be ignored. - if (data.batch_index == last_index) { - D_ASSERT(data.partition_data.size() == last_partition_values.size()); - for (idx_t i = 0; i < last_partition_values.size(); i++) { - if (Value::NotDistinctFrom(data.partition_data[i].min_val, last_partition_values[i])) { - continue; - } - throw InvalidInputException( - "The partition data callback of table function %s reported a different partitioning " - "column value at index %llu without changing the batch index.", - function_name, i); - } - return; - } - } - last_batch_index = data.batch_index; - last_partition_values.clear(); - for (auto &entry : data.partition_data) { - last_partition_values.push_back(entry.min_val); - } - } - -private: - bool partition_columns_resolved = false; - vector partition_columns; - optional_idx last_batch_index; - vector last_partition_values; }; class CV2TableBindInfo { @@ -170,178 +60,6 @@ static auto Convert(CV2TableBindInfo *info) -> duckdb_v2_table_function_bind_inf return reinterpret_cast(info); } -class CV2TableInitGlobalInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - const vector *in_scan_columns = nullptr; - - duckdb_v2_opaque out_global_state = {}; - idx_t out_max_threads = 1; -}; - -static auto Convert(duckdb_v2_table_function_init_global_info_handle info) -> CV2TableInitGlobalInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2TableInitGlobalInfo *info) -> duckdb_v2_table_function_init_global_info_handle { - return reinterpret_cast(info); -} - -class CV2TableInitLocalInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - void *in_global_state = nullptr; - const vector *in_scan_columns = nullptr; - - duckdb_v2_opaque out_local_state = {}; -}; - -static auto Convert(duckdb_v2_table_function_init_local_info_handle info) -> CV2TableInitLocalInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2TableInitLocalInfo *info) -> duckdb_v2_table_function_init_local_info_handle { - return reinterpret_cast(info); -} - -class CV2TableExecInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - void *in_global_state = nullptr; - void *in_local_state = nullptr; - const vector *in_scan_columns = nullptr; - - DataChunk *output = nullptr; -}; - -static auto Convert(duckdb_v2_table_function_exec_info_handle info) -> CV2TableExecInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2TableExecInfo *info) -> duckdb_v2_table_function_exec_info_handle { - return reinterpret_cast(info); -} - -class CV2TableProgressInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - void *in_global_state = nullptr; - - double out_progress = 0.0; -}; - -static auto Convert(duckdb_v2_table_function_progress_info_handle info) -> CV2TableProgressInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2TableProgressInfo *info) -> duckdb_v2_table_function_progress_info_handle { - return reinterpret_cast(info); -} - -class CV2TableMetricsInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - void *in_global_state = nullptr; - - //! The metrics the callback reported, by name, applied to the scan's metrics afterwards - vector> out_metrics; -}; - -//! The operator metrics a table function scan can report, by the name the profiler uses for them -static auto CV2TableApplyMetric(OperatorMetrics &metrics, const string &name, uint64_t value) -> bool { - if (name == MetricOperatorRowsScanned::Name) { - metrics.rows_scanned = value; - } else if (name == MetricOperatorRowGroupsScanned::Name) { - metrics.row_groups_scanned = value; - } else if (name == MetricOperatorTotalRowGroupsToScan::Name) { - metrics.total_row_groups_to_scan = value; - } else if (name == MetricOperatorBytesScanned::Name) { - metrics.bytes_scanned = value; - metrics.bytes_scanned_reported = true; - } else { - return false; - } - return true; -} - -static void CV2TableAddMetric(CV2TableMetricsInfo &info, const char *name, idx_t name_length, uint64_t value) { - string metric_name(name, name_length); - OperatorMetrics probe; - if (!CV2TableApplyMetric(probe, metric_name, value)) { - throw InvalidInputException("\"%s\" is not a metric a table function can report, expected one of " - "\"%s\", \"%s\", \"%s\" or \"%s\"", - metric_name, MetricOperatorRowsScanned::Name, MetricOperatorRowGroupsScanned::Name, - MetricOperatorTotalRowGroupsToScan::Name, MetricOperatorBytesScanned::Name); - } - info.out_metrics.emplace_back(std::move(metric_name), value); -} - -static auto Convert(duckdb_v2_table_function_metrics_info_handle info) -> CV2TableMetricsInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2TableMetricsInfo *info) -> duckdb_v2_table_function_metrics_info_handle { - return reinterpret_cast(info); -} - -class CV2TableClaimBatchInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - void *in_global_state = nullptr; - void *in_local_state = nullptr; - - bool out_claimed = false; -}; - -static auto Convert(duckdb_v2_table_function_claim_batch_info_handle info) -> CV2TableClaimBatchInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2TableClaimBatchInfo *info) -> duckdb_v2_table_function_claim_batch_info_handle { - return reinterpret_cast(info); -} - -class CV2TableFilterPushdownInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - // The predicates the optimizer offers, borrowed from the engine for the duration of the callback. - const vector> *in_filters = nullptr; - // What the column references inside the predicates index: the scan's columns, as the function sees them. - vector in_column_ids; - - vector out_handled; -}; - -static auto Convert(duckdb_v2_table_function_filter_pushdown_info_handle info) -> CV2TableFilterPushdownInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2TableFilterPushdownInfo *info) -> duckdb_v2_table_function_filter_pushdown_info_handle { - return reinterpret_cast(info); -} - -class CV2TablePartitionDataInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - void *in_global_state = nullptr; - void *in_local_state = nullptr; - const OperatorPartitionInfo *in_partition_info = nullptr; - const vector *in_partition_columns = nullptr; - const vector *in_column_types = nullptr; - - optional_idx out_batch_index; - vector out_partition_value_set; - vector out_partition_values; -}; - -static auto Convert(duckdb_v2_table_function_partition_data_info_handle info) -> CV2TablePartitionDataInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2TablePartitionDataInfo *info) -> duckdb_v2_table_function_partition_data_info_handle { - return reinterpret_cast(info); -} - class CV2TableStatsInfo { public: explicit CV2TableStatsInfo(BaseStatistics &result) : result_stats(CV2Stats::Writable(result)) { @@ -361,43 +79,6 @@ static auto Convert(CV2TableStatsInfo *info) -> duckdb_v2_table_function_stats_i return reinterpret_cast(info); } -class CV2TablePartitioningInfo { -public: - void *in_user_data = nullptr; - void *in_bind_data = nullptr; - const vector *in_partition_ids = nullptr; - - // Not calling the setter is not a caller error: it means "not partitioned", the conservative default. - TablePartitionInfo out_partition_info = TablePartitionInfo::NOT_PARTITIONED; -}; - -static auto Convert(duckdb_v2_table_function_partitioning_info_handle info) -> CV2TablePartitioningInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2TablePartitioningInfo *info) -> duckdb_v2_table_function_partitioning_info_handle { - return reinterpret_cast(info); -} - -static_assert(static_cast(TablePartitionInfo::NOT_PARTITIONED) == DUCKDB_V2_TABLE_PARTITION_INFO_NOT_PARTITIONED, - "TablePartitionInfo::NOT_PARTITIONED mismatch"); -static_assert(static_cast(TablePartitionInfo::SINGLE_VALUE_PARTITIONS) == - DUCKDB_V2_TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS, - "TablePartitionInfo::SINGLE_VALUE_PARTITIONS mismatch"); -static_assert(static_cast(TablePartitionInfo::OVERLAPPING_PARTITIONS) == - DUCKDB_V2_TABLE_PARTITION_INFO_OVERLAPPING_PARTITIONS, - "TablePartitionInfo::OVERLAPPING_PARTITIONS mismatch"); -static_assert(static_cast(TablePartitionInfo::DISJOINT_PARTITIONS) == - DUCKDB_V2_TABLE_PARTITION_INFO_DISJOINT_PARTITIONS, - "TablePartitionInfo::DISJOINT_PARTITIONS mismatch"); - -static auto CV2ConvertPartitionInfo(DUCKDB_V2_TABLE_PARTITION_INFO value) -> TablePartitionInfo { - if (static_cast(value) > DUCKDB_V2_TABLE_PARTITION_INFO_DISJOINT_PARTITIONS) { - throw duckdb::InvalidInputException( - "Invalid value in duckdb_v2_table_function_partitioning_set_partition_info"); - } - return static_cast(value); -} - static_assert(static_cast(OrderPreservationType::NO_ORDER) == DUCKDB_V2_ORDER_PRESERVATION_NO_ORDER, "OrderPreservationType::NO_ORDER mismatch"); static_assert(static_cast(OrderPreservationType::INSERTION_ORDER) == DUCKDB_V2_ORDER_PRESERVATION_INSERTION_ORDER, @@ -412,42 +93,20 @@ static auto CV2ConvertOrderPreservation(DUCKDB_V2_ORDER_PRESERVATION value) -> O return static_cast(value); } -//! Virtual columns are told apart from declared ones in the column lists of the scan by this plus their value in the -//! public enum -static constexpr column_t CV2_VIRTUAL_COLUMN_START = UINT64_C(9223372036854775808); - -//! The index the scan's column lists hold for a virtual column of the engine, which is invalid if there is no such -//! virtual column -static auto CV2VirtualColumnIndex(column_t engine_id) -> column_t { - if (engine_id == MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER) { - return CV2_VIRTUAL_COLUMN_START + DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER; - } - throw InternalException("Unsupported virtual column %llu in a table function scan", engine_id); -} - class CV2TableFunctionInfo : public TableFunctionInfo { public: duckdb_v2_table_function_bind_callback_fn bind_cb = nullptr; - duckdb_v2_table_function_init_global_callback_fn init_global_cb = nullptr; - duckdb_v2_table_function_init_local_callback_fn init_local_cb = nullptr; - duckdb_v2_table_function_exec_callback_fn exec_cb = nullptr; - duckdb_v2_table_function_progress_callback_fn progress_cb = nullptr; - duckdb_v2_table_function_filter_pushdown_callback_fn filter_pushdown_cb = nullptr; - duckdb_v2_table_function_partition_data_callback_fn partition_data_cb = nullptr; - duckdb_v2_table_function_partitioning_callback_fn partitioning_cb = nullptr; duckdb_v2_table_function_stats_callback_fn stats_cb = nullptr; - duckdb_v2_table_function_claim_batch_callback_fn claim_batch_cb = nullptr; duckdb_v2_table_function_get_bind_info_callback_fn get_bind_info_cb = nullptr; - duckdb_v2_table_function_metrics_callback_fn metrics_cb = nullptr; duckdb_v2_table_function_to_string_callback_fn to_string_cb = nullptr; + duckdb_v2_table_function_partitioning_callback_fn partitioning_cb = nullptr; shared_ptr user_data = nullptr; - bool projection_pushdown = false; - //! Whether the function sees the filters of the scan: it has a filter pushdown callback and projection pushdown - bool ReadsFilters() const { - return filter_pushdown_cb && projection_pushdown; - } //! Whether the function can produce the file_row_number virtual column bool file_row_number = false; + //! How the scan runs, as decided at plan time + CV2ScanOptions scan; + //! The data source the function scans with. The bind data of a call refers to it, which the function outlives. + CV2DataSourceInfo source; Identifier name; }; @@ -554,6 +213,8 @@ static auto CV2TableBind(ClientContext &context, TableFunctionBindInput &input, // Take ownership of whatever the callback set before reporting an error, so it is destroyed either way. auto result = make_uniq(); result->info = &info; + result->source = &info.source; + result->scan = &info.scan; result->handle = std::move(bind_info.out_bind_data); result->cardinality = args.out_cardinality; result->cardinality_is_exact = args.out_cardinality_is_exact; @@ -578,554 +239,114 @@ static auto CV2TableBind(ClientContext &context, TableFunctionBindInput &input, return std::move(result); } -//! The index the function sees for a column of the scan. A virtual column of a function wrapped in a multi-file -//! function has an index of its own past the declared columns, and the wrapper tells which virtual column that is. -static auto CV2ScanColumnIndex(column_t column, optional_ptr> virtual_columns) - -> column_t { - if (virtual_columns) { - auto entry = virtual_columns->find(column); - if (entry != virtual_columns->end()) { - return CV2VirtualColumnIndex(entry->second); - } +//! An exact estimate also pins the maximum; otherwise only the estimate is known. +static auto CV2TableMakeStatistics(idx_t cardinality, bool is_exact) -> unique_ptr { + if (is_exact) { + return make_uniq(cardinality, cardinality); } - return IsVirtualColumn(column) ? CV2VirtualColumnIndex(column) : column; + return make_uniq(cardinality); } -//! The declared column behind each vector of the output chunk. With projection pushdown the engine sizes the chunk -//! to the columns it asked for; without it the chunk always holds every declared column, whatever the engine asked. -static auto CV2TableScanColumns(const CV2TableFunctionData &bind_data, const TableFunctionInitInput &input) - -> vector { - if (bind_data.info->projection_pushdown) { - if (input.column_ids.empty()) { - // the scan only produces rows (e.g. for count(*)) - the function produces them through its first column - return {0}; - } - const auto &virtual_columns = TableFunctionFileInitInput::Get(input).virtual_columns; - vector columns; - columns.reserve(input.column_ids.size()); - for (auto column : input.column_ids) { - columns.push_back(CV2ScanColumnIndex(column, virtual_columns)); - } - return columns; - } - vector columns; - for (idx_t i = 0; i < bind_data.column_types.size(); i++) { - columns.push_back(i); - } - return columns; -} - -//! The filters of the query that apply to a single column of the scan, as the position of the column among the scan's -//! columns and the predicate on it. A filter the engine applies speculatively is handed out as the predicate it -//! applies. -static auto CV2TableFilters(const TableFunctionInitInput &input) -> vector> { - //! The predicate behind a filter that is applied speculatively, which wraps it - auto unwrap = [](Expression &expression) -> Expression & { - reference current(expression); - while (current.get().GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { - auto &function = current.get().Cast(); - if (!function.BindInfo()) { - break; - } - auto &name = function.Function().GetName(); - if (name == OptionalFilterScalarFun::NAME) { - current = *function.BindInfo()->Cast().child_filter_expr; - } else if (name == SelectivityOptionalFilterScalarFun::NAME) { - current = *function.BindInfo()->Cast().child_filter_expr; - } else { - break; - } - } - return current.get(); - }; - vector> result; - if (!input.filters) { - return result; - } - for (auto &entry : *input.filters) { - auto &filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "CV2TableFilters"); - result.emplace_back(entry.GetIndex().GetIndex(), &unwrap(*filter.expr)); +static auto CV2TableCardinality(ClientContext &context, const FunctionData *bind_data) -> unique_ptr { + const auto &data = bind_data->Cast(); + if (!data.cardinality_set) { + // No estimate at all: the optimizer falls back on its own defaults. + return nullptr; } - return result; + return CV2TableMakeStatistics(data.cardinality, data.cardinality_is_exact); } -//! Offers the filters the scan applies to the filter pushdown callback once more, for the scan that is about to start. -//! The callback only sees the predicates at optimization time, which a function wrapped in a multi-file function does -//! not: the optimizer asks the wrapper. The engine applies the filters to what the function produces, so accepting a -//! predicate has no effect here. -static auto CV2TableOfferFilters(ClientContext &context, const CV2TableFunctionData &bind_data, - const TableFunctionInitInput &input) -> void { - const auto &info = *bind_data.info; - const auto &file_input = TableFunctionFileInitInput::Get(input); - auto filters = CV2TableFilters(input); - if (file_input.expression_map) { - // the predicate on a converted column is written against the converted values, not those of the file - vector> on_file_columns; - for (auto &entry : filters) { - if (file_input.expression_map->find(ProjectionIndex(entry.first)) == file_input.expression_map->end()) { - on_file_columns.push_back(entry); - } - } - filters = std::move(on_file_columns); - } - if (filters.empty()) { - return; - } - // A table filter refers to the one column it applies to by a physical reference; the callback is offered column - // references, like at optimization time, which it resolves through the column list - vector> predicates; - for (auto &entry : filters) { - auto predicate = entry.second->Copy(); - ExpressionIterator::EnumerateExpression(predicate, [&](unique_ptr &child) { - if (child->GetExpressionClass() == ExpressionClass::BOUND_REF) { - child = make_uniq(child->GetAlias(), child->GetReturnType(), - ColumnBinding(TableIndex(0), ProjectionIndex(entry.first))); - } - }); - predicates.push_back(std::move(predicate)); +static auto CV2TableStats(ClientContext &context, TableFunctionGetStatisticsInput &input) + -> unique_ptr { + const auto &data = input.bind_data->Cast(); + const auto &info = *data.info; + + // The callback only describes whole declared columns, not virtual columns or fields extracted from a column + const auto &column_index = input.column_index; + if (!column_index.HasPrimaryIndex() || column_index.HasChildren() || column_index.IsVirtualColumn() || + column_index.GetPrimaryIndex() >= data.column_types.size()) { + return nullptr; } - CV2TableFilterPushdownInfo args = {}; + auto result = BaseStatistics::CreateUnknown(data.column_types[column_index.GetPrimaryIndex()]); + CV2TableStatsInfo args(result); args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; - args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; - args.in_filters = &predicates; - for (auto column : input.column_ids) { - args.in_column_ids.push_back(CV2ScanColumnIndex(column, file_input.virtual_columns)); - } - args.out_handled.resize(predicates.size(), false); + args.in_bind_data = data.handle ? data.handle->GetData() : nullptr; + args.in_column_index = column_index.GetPrimaryIndex(); CV2ErrorInfo err = {}; auto err_ptr = Convert(&err); CV2CallbackContext callback_context(context); - info.filter_pushdown_cb(Convert(&args), Convert(&callback_context), &err_ptr); + info.stats_cb(Convert(&args), Convert(&callback_context), &err_ptr); + if (err.HasError()) { err.ThrowAsException(); } + + return result.ToUnique(); } -static auto CV2TableInitGlobal(ClientContext &context, TableFunctionInitInput &input) - -> unique_ptr { - const auto &bind_data = input.bind_data->Cast(); - const auto &info = *bind_data.info; +class CV2TablePartitioningInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + const vector *in_partition_ids = nullptr; + + // Not calling the setter is not a caller error: it means "not partitioned", the conservative default. + TablePartitionInfo out_partition_info = TablePartitionInfo::NOT_PARTITIONED; +}; + +static auto Convert(duckdb_v2_table_function_partitioning_info_handle info) -> CV2TablePartitioningInfo * { + return reinterpret_cast(info); +} +static auto Convert(CV2TablePartitioningInfo *info) -> duckdb_v2_table_function_partitioning_info_handle { + return reinterpret_cast(info); +} + +static_assert(static_cast(TablePartitionInfo::NOT_PARTITIONED) == DUCKDB_V2_TABLE_PARTITION_INFO_NOT_PARTITIONED, + "TablePartitionInfo::NOT_PARTITIONED mismatch"); +static_assert(static_cast(TablePartitionInfo::SINGLE_VALUE_PARTITIONS) == + DUCKDB_V2_TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS, + "TablePartitionInfo::SINGLE_VALUE_PARTITIONS mismatch"); +static_assert(static_cast(TablePartitionInfo::OVERLAPPING_PARTITIONS) == + DUCKDB_V2_TABLE_PARTITION_INFO_OVERLAPPING_PARTITIONS, + "TablePartitionInfo::OVERLAPPING_PARTITIONS mismatch"); +static_assert(static_cast(TablePartitionInfo::DISJOINT_PARTITIONS) == + DUCKDB_V2_TABLE_PARTITION_INFO_DISJOINT_PARTITIONS, + "TablePartitionInfo::DISJOINT_PARTITIONS mismatch"); - // Always produced, even without a callback: it carries the thread count and column list the scan runs with. - auto result = make_uniq(); - result->scan_columns = CV2TableScanColumns(bind_data, input); - if (info.ReadsFilters()) { - CV2TableOfferFilters(context, bind_data, input); +static auto CV2ConvertPartitionInfo(DUCKDB_V2_TABLE_PARTITION_INFO value) -> TablePartitionInfo { + if (static_cast(value) > DUCKDB_V2_TABLE_PARTITION_INFO_DISJOINT_PARTITIONS) { + throw duckdb::InvalidInputException( + "Invalid value in duckdb_v2_table_function_partitioning_set_partition_info"); } - if (!info.init_global_cb) { - return std::move(result); + return static_cast(value); +} + +//! The optimizer hands over the predicates it would otherwise evaluate above the scan; whatever the callback accepts +//! is removed from the list, and the engine keeps applying the rest itself. +static auto CV2TableFilterPushdown(ClientContext &context, LogicalGet &get, + optional_ptr bind_data_p, + vector> &filters) -> void { + if (filters.empty()) { + return; } + const auto &bind_data = bind_data_p->Cast(); + const auto &info = *bind_data.info; - CV2TableInitGlobalInfo args = {}; + CV2TableFilterPushdownInfo args = {}; args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; - args.in_scan_columns = &result->scan_columns; + args.in_filters = &filters; + for (auto &column : get.GetColumnIds()) { + args.in_column_ids.push_back(CV2ScanColumnIndex(column.GetPrimaryIndex(), nullptr)); + } + args.out_handled.resize(filters.size(), false); CV2ErrorInfo err = {}; auto err_ptr = Convert(&err); CV2CallbackContext callback_context(context); - info.init_global_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (args.out_global_state.ptr) { - result->handle = - CV2UserData(args.out_global_state.ptr, args.out_global_state.destroy, args.out_global_state.equals); - } - result->max_threads = args.out_max_threads; - - // Throw after taking ownership of the state, so that it is destroyed even if we error. - if (err.HasError()) { - err.ThrowAsException(); - } - - return std::move(result); -} - -//! Prepares the conversions the multi-file scan asks for (see TableFunctionFileInitInput::expression_map). The function -//! produces the values of its file, and the conversion turns them into the values the filters are written against. -static auto CV2TableInitConvertedColumns(ClientContext &context, const CV2TableFunctionData &bind_data, - const TableFunctionInitInput &input, const vector &scan_columns, - CV2TableLocalState &local_state) -> void { - const auto &expression_map = TableFunctionFileInitInput::Get(input).expression_map; - if (!expression_map || expression_map->empty()) { - return; - } - vector file_types; - for (auto column : scan_columns) { - file_types.push_back(IsVirtualColumn(column) ? LogicalType::BIGINT : bind_data.column_types[column]); - } - for (auto &entry : *expression_map) { - const auto position = entry.first.GetIndex(); - const auto input_count = entry.second.column_indexes.size(); - if (position + input_count > file_types.size()) { - throw InternalException("Converted column %llu of a table function scan is out of range", position); - } - CV2TableLocalState::ConvertedColumn converted; - converted.position = position; - converted.expression = entry.second.expression->Copy(); - converted.executor = make_uniq(context, *converted.expression); - vector input_types(file_types.begin() + NumericCast(position), - file_types.begin() + NumericCast(position + input_count)); - converted.input = make_uniq(); - converted.input->InitializeEmpty(input_types); - local_state.converted_columns.push_back(std::move(converted)); - } - local_state.converted_position.assign(file_types.size(), false); - for (auto &converted : local_state.converted_columns) { - local_state.converted_position[converted.position] = true; - } - local_state.file_chunk = make_uniq(); - local_state.file_chunk->Initialize(context, file_types); -} - -//! Produces the converted columns from what the function produced in the types of its file -static auto CV2TableConvertColumns(CV2TableLocalState &local_state, DataChunk &output) -> void { - auto &file_chunk = *local_state.file_chunk; - D_ASSERT(local_state.converted_position.size() == output.ColumnCount()); - for (idx_t i = 0; i < output.ColumnCount(); i++) { - if (!local_state.converted_position[i]) { - output.data[i].Reference(file_chunk.data[i]); - } - } - for (auto &converted : local_state.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(file_chunk.size()); - converted.executor->ExecuteExpression(converted_input, output.data[converted.position]); - } - output.SetChildCardinality(file_chunk.size()); -} - -static auto CV2TableInitLocal(ExecutionContext &context, TableFunctionInitInput &input, - GlobalTableFunctionState *global_state) -> unique_ptr { - const auto &bind_data = input.bind_data->Cast(); - const auto &info = *bind_data.info; - - // Always produced, even without a callback: get_partition_data keeps its per-thread guard state here. - auto result = make_uniq(); - if (info.ReadsFilters() && input.filters) { - // The function only reads the filters, so it is left to the engine to apply them to what it produces - for (auto &entry : *input.filters) { - result->filters.emplace_back(entry.GetIndex().GetIndex(), - TableFilterState::Initialize(context.client, entry.Filter())); - } - } - auto scan_columns = CV2TableScanColumns(bind_data, input); - if (info.ReadsFilters()) { - CV2TableInitConvertedColumns(context.client, bind_data, input, scan_columns, *result); - } - if (!info.init_local_cb) { - return std::move(result); - } - - CV2TableInitLocalInfo args = {}; - args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; - args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; - args.in_scan_columns = &scan_columns; - if (global_state) { - args.in_global_state = global_state->Cast().handle.GetData(); - } - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context.client); - info.init_local_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (args.out_local_state.ptr) { - result->handle = - CV2UserData(args.out_local_state.ptr, args.out_local_state.destroy, args.out_local_state.equals); - } - - // Throw after taking ownership of the state, so that it is destroyed even if we error. - if (err.HasError()) { - err.ThrowAsException(); - } - - return std::move(result); -} - -//! Calls the claim batch callback for the local state of the given input - returns whether a batch was claimed -static auto CV2TableClaimNextBatch(ClientContext &context, TableFunctionInput &input) -> bool { - const auto &bind_data = input.bind_data->Cast(); - const auto &info = *bind_data.info; - auto &local_state = input.local_state->Cast(); - - CV2TableClaimBatchInfo args = {}; - args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; - args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; - if (input.global_state) { - args.in_global_state = input.global_state->Cast().handle.GetData(); - } - args.in_local_state = local_state.handle.GetData(); - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context); - info.claim_batch_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (err.HasError()) { - err.ThrowAsException(); - } - local_state.batch_claimed = args.out_claimed; - return args.out_claimed; -} - -//! The caller claims the batches of this local state itself - every exec then scans the claimed batch only -static auto CV2TableClaimBatch(ClientContext &context, TableFunctionInput &input) -> bool { - input.local_state->Cast().claimed_externally = true; - return CV2TableClaimNextBatch(context, input); -} - -static auto CV2TableExecBatch(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void; - -static auto CV2TableExec(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { - const auto &info = *input.bind_data->Cast().info; - if (!info.claim_batch_cb) { - CV2TableExecBatch(context, input, output); - return; - } - auto &local_state = input.local_state->Cast(); - if (local_state.claimed_externally) { - // an empty chunk ends the batch, after which the caller claims the next one - CV2TableExecBatch(context, input, output); - return; - } - // nobody claims the batches for us - move on to the next batch whenever the current one is exhausted - while (true) { - if (!local_state.batch_claimed && !CV2TableClaimNextBatch(context, input)) { - return; - } - CV2TableExecBatch(context, input, output); - if (output.size() > 0) { - return; - } - local_state.batch_claimed = false; - } -} - -static auto CV2TableExecBatchOnce(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void; - -//! Runs the exec callback and, for a function that reads the filters of the query, applies them to what it produced: -//! the function is free to produce rows that do not pass them -static auto CV2TableExecBatch(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { - auto &local_state = input.local_state->Cast(); - while (true) { - if (local_state.file_chunk) { - local_state.file_chunk->Reset(); - CV2TableExecBatchOnce(context, input, *local_state.file_chunk); - CV2TableConvertColumns(local_state, output); - } else { - CV2TableExecBatchOnce(context, input, output); - } - if (local_state.filters.empty() || output.size() == 0) { - return; - } - const auto count = output.size(); - idx_t remaining = count; - SelectionVector selection; - selection.Initialize(nullptr); - for (auto &filter : local_state.filters) { - if (remaining == 0) { - break; - } - ColumnSegment::FilterSelection(selection, output.data[filter.first], *filter.second, count, remaining); - } - if (remaining == count) { - return; - } - if (remaining > 0) { - output.Slice(selection, remaining); - return; - } - // Nothing of this batch passed, but an empty chunk means that the batch is exhausted - output.Reset(); - context.FastInterruptCheck(); - } -} - -static auto CV2TableExecBatchOnce(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { - const auto &bind_data = input.bind_data->Cast(); - const auto &info = *bind_data.info; - - CV2TableExecInfo args = {}; - args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; - args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; - if (input.global_state) { - auto &global_state = input.global_state->Cast(); - args.in_global_state = global_state.handle.GetData(); - args.in_scan_columns = &global_state.scan_columns; - } - auto &local_state = input.local_state->Cast(); - args.in_local_state = local_state.handle.GetData(); - reference target(output); - if (output.ColumnCount() == 0) { - // the scan requests no columns (e.g. for count(*)), only rows - the function writes them into its first column - if (!local_state.row_chunk) { - local_state.row_chunk = make_uniq(); - local_state.row_chunk->Initialize(context, {bind_data.column_types[0]}); - } - local_state.row_chunk->Reset(); - target = *local_state.row_chunk; - } - args.output = &target.get(); - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context); - info.exec_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (err.HasError()) { - err.ThrowAsException(); - } - - // The vector write API sizes per vector, while the engine reads the chunk's cardinality. Callers typically size - // only the first vector and write the rest through direct buffer writes, so take the first vector's size as the - // batch's row count and propagate it to the others. A table function always has at least one result column. - auto row_count = target.get().data[0].size(); - if (output.ColumnCount() == 0) { - output.SetCardinalityUnsafe(row_count); - return; - } - output.SetChildCardinality(row_count); -} - -//! An exact estimate also pins the maximum; otherwise only the estimate is known. -static auto CV2TableMakeStatistics(idx_t cardinality, bool is_exact) -> unique_ptr { - if (is_exact) { - return make_uniq(cardinality, cardinality); - } - return make_uniq(cardinality); -} - -static auto CV2TableCardinality(ClientContext &context, const FunctionData *bind_data) -> unique_ptr { - const auto &data = bind_data->Cast(); - if (!data.cardinality_set) { - // No estimate at all: the optimizer falls back on its own defaults. - return nullptr; - } - return CV2TableMakeStatistics(data.cardinality, data.cardinality_is_exact); -} - -static auto CV2TableStats(ClientContext &context, TableFunctionGetStatisticsInput &input) - -> unique_ptr { - const auto &data = input.bind_data->Cast(); - const auto &info = *data.info; - - // The callback only describes whole declared columns, not virtual columns or fields extracted from a column - const auto &column_index = input.column_index; - if (!column_index.HasPrimaryIndex() || column_index.HasChildren() || column_index.IsVirtualColumn() || - column_index.GetPrimaryIndex() >= data.column_types.size()) { - return nullptr; - } - - auto result = BaseStatistics::CreateUnknown(data.column_types[column_index.GetPrimaryIndex()]); - CV2TableStatsInfo args(result); - args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; - args.in_bind_data = data.handle ? data.handle->GetData() : nullptr; - args.in_column_index = column_index.GetPrimaryIndex(); - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context); - info.stats_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (err.HasError()) { - err.ThrowAsException(); - } - - return result.ToUnique(); -} - -static auto CV2TableProgress(ClientContext &context, const FunctionData *bind_data, - const GlobalTableFunctionState *global_state) -> double { - const auto &data = bind_data->Cast(); - const auto &info = *data.info; - - CV2TableProgressInfo args = {}; - args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; - args.in_bind_data = data.handle ? data.handle->GetData() : nullptr; - if (global_state) { - // The callback runs concurrently with the scan, so the state it reads is the shared one, unsynchronized. - args.in_global_state = global_state->Cast().handle.GetData(); - } - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context); - info.progress_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (err.HasError()) { - err.ThrowAsException(); - } - - // The API contract is a 0.0-1.0 fraction, the engine reads a 0-100 percentage. - return MinValue(MaxValue(args.out_progress, 0.0), 1.0) * 100.0; -} - -static auto CV2TableGetMetrics(TableFunctionGetMetricsInput &input) -> void { - if (!input.bind_data) { - return; - } - const auto &data = input.bind_data->Cast(); - const auto &info = *data.info; - - CV2TableMetricsInfo args = {}; - args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; - args.in_bind_data = data.handle ? data.handle->GetData() : nullptr; - if (input.global_state) { - // The callback can run while the scan does, so the state it reads is the shared one, unsynchronized. - args.in_global_state = input.global_state->Cast().handle.GetData(); - } - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(input.context); - info.metrics_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (err.HasError()) { - err.ThrowAsException(); - } - - for (auto &metric : args.out_metrics) { - CV2TableApplyMetric(input.operator_metrics, metric.first, metric.second); - } -} - -//! Registered only for functions that declared the file_row_number virtual column, which is all there is to know -static auto CV2TableGetFileRowNumberColumn(ClientContext &, optional_ptr) -> virtual_column_map_t { - virtual_column_map_t result; - result.insert(make_pair(MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER, - TableColumn("file_row_number", LogicalType::BIGINT))); - return result; -} - -//! The optimizer hands over the predicates it would otherwise evaluate above the scan; whatever the callback accepts -//! is removed from the list, and the engine keeps applying the rest itself. -static auto CV2TableFilterPushdown(ClientContext &context, LogicalGet &get, - optional_ptr bind_data_p, - vector> &filters) -> void { - if (filters.empty()) { - return; - } - const auto &bind_data = bind_data_p->Cast(); - const auto &info = *bind_data.info; - - CV2TableFilterPushdownInfo args = {}; - args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; - args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; - args.in_filters = &filters; - for (auto &column : get.GetColumnIds()) { - args.in_column_ids.push_back(CV2ScanColumnIndex(column.GetPrimaryIndex(), nullptr)); - } - args.out_handled.resize(filters.size(), false); - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context); - info.filter_pushdown_cb(Convert(&args), Convert(&callback_context), &err_ptr); + info.scan.filter_pushdown_cb(Convert(&args), Convert(&callback_context), &err_ptr); if (err.HasError()) { err.ThrowAsException(); @@ -1140,61 +361,6 @@ static auto CV2TableFilterPushdown(ClientContext &context, LogicalGet &get, filters = std::move(remaining); } -//! Batch index is required on every call, even when unrequested: the pipeline range-checks it regardless. -static auto CV2TakePartitionData(CV2TablePartitionDataInfo &args, const Identifier &function_name) - -> OperatorPartitionData { - if (!args.out_batch_index.IsValid()) { - throw InvalidInputException("The partition data callback of table function %s did not set a batch index.", - function_name); - } - OperatorPartitionData result(args.out_batch_index.GetIndex()); - result.partition_data.reserve(args.out_partition_values.size()); - for (idx_t i = 0; i < args.out_partition_values.size(); i++) { - if (!args.out_partition_value_set[i]) { - throw InvalidInputException("The partition data callback of table function %s did not set the " - "partitioning column value at index %llu.", - function_name, i); - } - result.partition_data.emplace_back(std::move(args.out_partition_values[i])); - } - return result; -} - -static auto CV2TableGetPartitionData(ClientContext &context, TableFunctionGetPartitionInput &input) - -> OperatorPartitionData { - const auto &bind_data = input.bind_data->Cast(); - const auto &info = *bind_data.info; - - auto &global_state = input.global_state->Cast(); - auto &local_state = input.local_state->Cast(); - - CV2TablePartitionDataInfo args = {}; - args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; - args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; - args.in_global_state = global_state.handle.GetData(); - args.in_local_state = local_state.handle.GetData(); - args.in_partition_info = &input.partition_info; - // The planner resolves these to scan positions, unlike get_partition_info's, which it resolves to declared - // columns; the callback is promised declared columns in both. - args.in_partition_columns = &local_state.PartitionColumns(input.partition_info, global_state.scan_columns); - args.in_column_types = &bind_data.column_types; - args.out_partition_value_set.resize(args.in_partition_columns->size(), false); - args.out_partition_values.resize(args.in_partition_columns->size()); - - CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(context); - info.partition_data_cb(Convert(&args), Convert(&callback_context), &err_ptr); - - if (err.HasError()) { - err.ThrowAsException(); - } - - auto result = CV2TakePartitionData(args, info.name); - local_state.CheckPartitionData(info.name, result); - return result; -} - //! Runs at plan time and must be deterministic: the optimizer may call it for a plan shape it later discards. static auto CV2TableGetPartitionInfo(ClientContext &context, TableFunctionPartitionInput &input) -> TablePartitionInfo { const auto &bind_data = input.bind_data->Cast(); @@ -1217,6 +383,14 @@ static auto CV2TableGetPartitionInfo(ClientContext &context, TableFunctionPartit return args.out_partition_info; } +//! Registered only for functions that declared the file_row_number virtual column, which is all there is to know +static auto CV2TableGetFileRowNumberColumn(ClientContext &, optional_ptr) -> virtual_column_map_t { + virtual_column_map_t result; + result.insert(make_pair(MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER, + TableColumn("file_row_number", LogicalType::BIGINT))); + return result; +} + class CV2TableFunction { public: explicit CV2TableFunction(DatabaseInstance &db) : db(db) { @@ -1231,70 +405,67 @@ class CV2TableFunction { if (!info.bind_cb) { throw InvalidInputException("Bind callback must be set for the function."); } - if (!info.exec_cb) { - throw InvalidInputException("Exec callback must be set for the function."); - } - // The engine calls get_partition_data without a null check once get_partition_info claims partitions. - if (info.partitioning_cb && !info.partition_data_cb) { - throw InvalidInputException("Partition data callback must be set when the partitioning callback is set."); - } // A table function declares the columns it returns from its bind callback, not through a return type. if (signature.GetReturnType().id() != LogicalTypeId::INVALID) { throw InvalidInputException("A table function signature cannot set a return type."); } - // Both are told apart from the declared columns by their place among the columns the scan was asked for - if (info.file_row_number && !info.projection_pushdown) { + info.source.Verify(); + // The engine calls get_partition_data without a null check once get_partition_info claims partitions. + if (info.partitioning_cb && !info.source.partition_data_cb) { + throw InvalidInputException( + "The data source must have a partition data callback when the partitioning callback is set."); + } + // Virtual columns are told apart from the declared columns by their place among the columns the scan was asked + // for + if (info.file_row_number && !info.scan.projection_pushdown) { throw InvalidInputException( "A table function that produces a virtual column requires projection pushdown."); } - signature.Verify(); // A table function holds a signature of its own, so the declared one is handed over as-is - TableFunction function(name, {}, CV2TableExec, CV2TableBind, CV2TableInitGlobal, CV2TableInitLocal); + TableFunction function(name, {}, CV2DataSourceExec, CV2TableBind, CV2DataSourceInitGlobal, + CV2DataSourceInitLocal); function.GetSignature() = signature; // Always wired: it serves the estimate a bind callback may set, which is not known at registration. It // reports no estimate when the bind callback sets none. function.cardinality = CV2TableCardinality; - if (info.progress_cb) { - function.table_scan_progress = CV2TableProgress; + // The extended variant: setting the plain one would turn off pushing field extraction into the scan + if (info.stats_cb) { + function.statistics_extended = CV2TableStats; } - if (info.filter_pushdown_cb) { - function.pushdown_complex_filter = CV2TableFilterPushdown; + if (info.get_bind_info_cb) { + function.get_bind_info = CV2TableGetBindInfo; + } + if (info.to_string_cb) { + function.to_string = CV2TableToString; } - if (info.partition_data_cb) { - function.get_partition_data = CV2TableGetPartitionData; + info.source.ConfigureScan(function); + if (info.scan.filter_pushdown_cb) { + function.pushdown_complex_filter = CV2TableFilterPushdown; } if (info.partitioning_cb) { function.get_partition_info = CV2TableGetPartitionInfo; } - // The extended variant: setting the plain one would turn off pushing field extraction into the scan - if (info.stats_cb) { - function.statistics_extended = CV2TableStats; - } - function.projection_pushdown = info.projection_pushdown; - if (info.ReadsFilters()) { + function.projection_pushdown = info.scan.projection_pushdown; + if (info.scan.ReadsFilters()) { // The engine applies the filters to what the function produces, so they only need to reach the scan function.filter_pushdown = true; } if (info.file_row_number) { function.get_virtual_columns = CV2TableGetFileRowNumberColumn; } - if (info.metrics_cb) { - function.get_metrics = CV2TableGetMetrics; - } - if (info.get_bind_info_cb) { - function.get_bind_info = CV2TableGetBindInfo; - } - if (info.to_string_cb) { - function.to_string = CV2TableToString; - } // a function registered through the C API makes no stability promise unless one was declared function.stability = stability; + // Only once nothing can refuse the registration: a refused one leaves the configuration as it was. + // The data source gets the name for its error messages, and the user data of the function unless it has some. + info.source.name = name; + info.source.InheritUserData(info.user_data); + info.scan.user_data = info.user_data; info.name = name; function.function_info = make_shared_ptr(std::move(info)); @@ -1350,10 +521,10 @@ class CV2MultiFileFunction { settings.glob_input = FileGlobInput(FileGlobOptions::FALLBACK_GLOB, file_extension); } auto single_file = SelectSingleFileFunction(std::move(single_file_overloads)); - if (single_file.function == CV2TableExec && single_file.function_info) { + if (single_file.function == CV2DataSourceExec && single_file.function_info) { // the multi-file scan claims the batches of a C API function that scans one batch at a time - if (single_file.function_info->Cast().claim_batch_cb) { - settings.claim_batch = CV2TableClaimBatch; + if (single_file.function_info->Cast().source.claim_batch_cb) { + settings.claim_batch = CV2DataSourceClaimBatch; } } auto function = TableFunctionMultiFileWrapper::CreateFunctionSet(std::move(single_file), name, settings); @@ -1443,377 +614,147 @@ DUCKDB_V2_ERROR duckdb_v2_table_function_get_signature(duckdb_v2_table_function_ return WithErrorHandler(err, [&]() { *sig = Convert(&Convert(function)->signature); }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_set_user_data(duckdb_v2_table_function_handle function, duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { - Convert(function)->info.user_data = - duckdb::make_shared_ptr(data->ptr, data->destroy, data->equals); - }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_set_bind_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_bind_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.bind_cb = callback; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_set_init_global_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_init_global_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.init_global_cb = callback; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_set_init_local_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_init_local_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.init_local_cb = callback; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_set_exec_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.exec_cb = callback; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_set_progress_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_progress_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.progress_cb = callback; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_set_projection_pushdown(duckdb_v2_table_function_handle function, bool enable, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.projection_pushdown = enable; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_add_virtual_column(duckdb_v2_table_function_handle function, - DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { - switch (column) { - case DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER: - Convert(function)->info.file_row_number = true; - break; - default: - throw duckdb::InvalidInputException("Invalid value in duckdb_v2_table_function_add_virtual_column"); - } - }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_set_metrics_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_metrics_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.metrics_cb = callback; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_set_filter_pushdown_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_filter_pushdown_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.filter_pushdown_cb = callback; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_set_partition_data_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_partition_data_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.partition_data_cb = callback; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_set_partitioning_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_partitioning_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.partitioning_cb = callback; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_set_stats_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_stats_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.stats_cb = callback; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_bind_add_result_column(duckdb_v2_table_function_bind_info_handle info, - const char *name, idx_t name_length, - duckdb_v2_logical_type_handle type, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_STR_ARG(name, name_length); - DUCKDB_CHECK_ARG(type); - return WithErrorHandler(err, [&]() { - auto column_type_ref = Convert(type); - const auto &column_type = *column_type_ref; - // A result column carries data, so a wildcard or otherwise incomplete type has no meaning here. - if (!column_type.IsComplete()) { - throw duckdb::InvalidInputException("Result column type must be a fully defined concrete type"); - } - auto &bind_info = *Convert(info); - bind_info.out_column_names.emplace_back(ConvertIdentifierName(name, name_length)); - bind_info.out_column_types.push_back(column_type); - }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_bind_set_cardinality(duckdb_v2_table_function_bind_info_handle info, - idx_t cardinality, bool is_exact, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - return WithErrorHandler(err, [&]() { - auto &bind_info = *Convert(info); - bind_info.out_cardinality = cardinality; - bind_info.out_cardinality_is_exact = is_exact; - bind_info.out_cardinality_set = true; - }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_bind_set_order_preservation(duckdb_v2_table_function_bind_info_handle info, - DUCKDB_V2_ORDER_PRESERVATION order, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - return WithErrorHandler(err, [&]() { Convert(info)->out_order_preservation = CV2ConvertOrderPreservation(order); }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_init_global_get_user_data(duckdb_v2_table_function_init_global_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_init_global_get_bind_data(duckdb_v2_table_function_init_global_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_init_global_set_global_state(duckdb_v2_table_function_init_global_info_handle info, - duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { Convert(info)->out_global_state = *data; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_init_global_set_max_threads(duckdb_v2_table_function_init_global_info_handle info, - idx_t max_threads, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - return WithErrorHandler(err, [&]() { - if (max_threads == 0) { - throw duckdb::InvalidInputException("The maximum number of threads must be at least 1"); - } - Convert(info)->out_max_threads = max_threads; - }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_init_global_get_column_count(duckdb_v2_table_function_init_global_info_handle info, - idx_t *count, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(count); - return WithErrorHandler(err, [&]() { *count = Convert(info)->in_scan_columns->size(); }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_init_global_get_column_index(duckdb_v2_table_function_init_global_info_handle info, - idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(column_index); - return WithErrorHandler(err, [&]() { - const auto &columns = *Convert(info)->in_scan_columns; - if (index >= columns.size()) { - throw duckdb::InvalidInputException( - "Index out of bounds in duckdb_v2_table_function_init_global_get_column_index"); - } - *column_index = columns[index]; - }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_init_local_get_user_data(duckdb_v2_table_function_init_local_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_init_local_get_bind_data(duckdb_v2_table_function_init_local_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_init_local_get_global_state(duckdb_v2_table_function_init_local_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_init_local_set_local_state(duckdb_v2_table_function_init_local_info_handle info, - duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { Convert(info)->out_local_state = *data; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_init_local_get_column_count(duckdb_v2_table_function_init_local_info_handle info, idx_t *count, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(count); - return WithErrorHandler(err, [&]() { *count = Convert(info)->in_scan_columns->size(); }); +DUCKDB_V2_ERROR duckdb_v2_table_function_set_user_data(duckdb_v2_table_function_handle function, duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { + Convert(function)->info.user_data = + duckdb::make_shared_ptr(data->ptr, data->destroy, data->equals); + }); } -DUCKDB_V2_ERROR -duckdb_v2_table_function_init_local_get_column_index(duckdb_v2_table_function_init_local_info_handle info, idx_t index, - idx_t *column_index, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(column_index); +DUCKDB_V2_ERROR duckdb_v2_table_function_set_data_source(duckdb_v2_table_function_handle function, + duckdb_v2_data_source_handle data_source, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_ARG(data_source); return WithErrorHandler(err, [&]() { - const auto &columns = *Convert(info)->in_scan_columns; - if (index >= columns.size()) { - throw duckdb::InvalidInputException( - "Index out of bounds in duckdb_v2_table_function_init_local_get_column_index"); - } - *column_index = columns[index]; + auto &self = *Convert(function); + auto &source = *Convert(data_source); + CheckRegistrationTarget(source.db, self.db, "data source"); + // The function keeps a copy: changing the data source afterwards does not change the function + self.info.source = source.info; }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_exec_get_user_data(duckdb_v2_table_function_exec_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +DUCKDB_V2_ERROR duckdb_v2_table_function_set_bind_callback(duckdb_v2_table_function_handle function, + duckdb_v2_table_function_bind_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { Convert(function)->info.bind_cb = callback; }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_exec_get_bind_data(duckdb_v2_table_function_exec_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +DUCKDB_V2_ERROR duckdb_v2_table_function_set_projection_pushdown(duckdb_v2_table_function_handle function, bool enable, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { Convert(function)->info.scan.projection_pushdown = enable; }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_exec_get_global_state(duckdb_v2_table_function_exec_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +DUCKDB_V2_ERROR duckdb_v2_table_function_add_virtual_column(duckdb_v2_table_function_handle function, + DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { + switch (column) { + case DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER: + Convert(function)->info.file_row_number = true; + break; + default: + throw duckdb::InvalidInputException("Invalid value in duckdb_v2_table_function_add_virtual_column"); + } + }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_exec_get_local_state(duckdb_v2_table_function_exec_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_local_state; }); +DUCKDB_V2_ERROR +duckdb_v2_table_function_set_filter_pushdown_callback(duckdb_v2_table_function_handle function, + duckdb_v2_table_function_filter_pushdown_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { Convert(function)->info.scan.filter_pushdown_cb = callback; }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_exec_get_output_chunk(duckdb_v2_table_function_exec_info_handle info, - duckdb_v2_data_chunk_handle *chunk, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(chunk); - return WithErrorHandler(err, [&]() { *chunk = Convert(Convert(info)->output); }); +DUCKDB_V2_ERROR +duckdb_v2_table_function_set_partitioning_callback(duckdb_v2_table_function_handle function, + duckdb_v2_table_function_partitioning_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { Convert(function)->info.partitioning_cb = callback; }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_exec_get_column_count(duckdb_v2_table_function_exec_info_handle info, - idx_t *count, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(count); - return WithErrorHandler(err, [&]() { *count = Convert(info)->in_scan_columns->size(); }); +DUCKDB_V2_ERROR duckdb_v2_table_function_set_stats_callback(duckdb_v2_table_function_handle function, + duckdb_v2_table_function_stats_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { Convert(function)->info.stats_cb = callback; }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_exec_get_column_index(duckdb_v2_table_function_exec_info_handle info, - idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_table_function_bind_add_result_column(duckdb_v2_table_function_bind_info_handle info, + const char *name, idx_t name_length, + duckdb_v2_logical_type_handle type, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(column_index); + DUCKDB_CHECK_STR_ARG(name, name_length); + DUCKDB_CHECK_ARG(type); return WithErrorHandler(err, [&]() { - const auto &columns = *Convert(info)->in_scan_columns; - if (index >= columns.size()) { - throw duckdb::InvalidInputException( - "Index out of bounds in duckdb_v2_table_function_exec_get_column_index"); + auto column_type_ref = Convert(type); + const auto &column_type = *column_type_ref; + // A result column carries data, so a wildcard or otherwise incomplete type has no meaning here. + if (!column_type.IsComplete()) { + throw duckdb::InvalidInputException("Result column type must be a fully defined concrete type"); } - *column_index = columns[index]; + auto &bind_info = *Convert(info); + bind_info.out_column_names.emplace_back(ConvertIdentifierName(name, name_length)); + bind_info.out_column_types.push_back(column_type); }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_progress_get_user_data(duckdb_v2_table_function_progress_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_progress_get_bind_data(duckdb_v2_table_function_progress_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_progress_get_global_state(duckdb_v2_table_function_progress_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_table_function_bind_set_cardinality(duckdb_v2_table_function_bind_info_handle info, + idx_t cardinality, bool is_exact, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); + return WithErrorHandler(err, [&]() { + auto &bind_info = *Convert(info); + bind_info.out_cardinality = cardinality; + bind_info.out_cardinality_is_exact = is_exact; + bind_info.out_cardinality_set = true; + }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_progress_set_progress(duckdb_v2_table_function_progress_info_handle info, - double progress, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_table_function_bind_set_order_preservation(duckdb_v2_table_function_bind_info_handle info, + DUCKDB_V2_ORDER_PRESERVATION order, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - return WithErrorHandler(err, [&]() { Convert(info)->out_progress = progress; }); + return WithErrorHandler(err, [&]() { Convert(info)->out_order_preservation = CV2ConvertOrderPreservation(order); }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_get_user_data(duckdb_v2_table_function_metrics_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_user_data(duckdb_v2_table_function_stats_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(data); return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_get_bind_data(duckdb_v2_table_function_metrics_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_bind_data(duckdb_v2_table_function_stats_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(data); return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_get_global_state(duckdb_v2_table_function_metrics_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_column_index(duckdb_v2_table_function_stats_info_handle info, + idx_t *column_index, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); + DUCKDB_CHECK_ARG(column_index); + return WithErrorHandler(err, [&]() { *column_index = Convert(info)->in_column_index; }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_metrics_set(duckdb_v2_table_function_metrics_info_handle info, - const char *name, idx_t name_length, uint64_t value, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_result_stats(duckdb_v2_table_function_stats_info_handle info, + duckdb_v2_stats_handle *stats, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(name); - return WithErrorHandler(err, [&]() { CV2TableAddMetric(*Convert(info), name, name_length, value); }); + DUCKDB_CHECK_ARG(stats); + return WithErrorHandler(err, [&]() { *stats = Convert(&Convert(info)->result_stats); }); } DUCKDB_V2_ERROR @@ -1895,116 +836,6 @@ duckdb_v2_table_function_filter_pushdown_get_column_index(duckdb_v2_table_functi }); } -DUCKDB_V2_ERROR -duckdb_v2_table_function_partition_data_get_user_data(duckdb_v2_table_function_partition_data_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_partition_data_get_bind_data(duckdb_v2_table_function_partition_data_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_partition_data_get_global_state(duckdb_v2_table_function_partition_data_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_partition_data_get_local_state(duckdb_v2_table_function_partition_data_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_local_state; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_partition_data_requires_batch_index(duckdb_v2_table_function_partition_data_info_handle info, - bool *required, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(required); - return WithErrorHandler(err, [&]() { *required = Convert(info)->in_partition_info->RequiresBatchIndex(); }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_partition_data_requires_partition_columns( - duckdb_v2_table_function_partition_data_info_handle info, bool *required, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(required); - return WithErrorHandler(err, [&]() { *required = Convert(info)->in_partition_info->RequiresPartitionColumns(); }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_partition_data_get_partition_column_count( - duckdb_v2_table_function_partition_data_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(count); - return WithErrorHandler(err, [&]() { *count = Convert(info)->in_partition_columns->size(); }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_partition_data_get_partition_column_index( - duckdb_v2_table_function_partition_data_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(column_index); - return WithErrorHandler(err, [&]() { - const auto &columns = *Convert(info)->in_partition_columns; - if (index >= columns.size()) { - throw duckdb::InvalidInputException( - "Index out of bounds in duckdb_v2_table_function_partition_data_get_partition_column_index"); - } - *column_index = columns[index]; - }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_partition_data_set_batch_index(duckdb_v2_table_function_partition_data_info_handle info, - idx_t batch_index, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - return WithErrorHandler(err, [&]() { - // ToPipelinePartitionData adds base + 1 and throws an InternalException from BATCH_INCREMENT - 1 on. - if (batch_index >= duckdb::PipelineBuildState::BATCH_INCREMENT - 2) { - throw duckdb::InvalidInputException( - "duckdb_v2_table_function_partition_data_set_batch_index: batch_index %llu must be less than " - "%llu", - batch_index, duckdb::PipelineBuildState::BATCH_INCREMENT - 2); - } - Convert(info)->out_batch_index = batch_index; - }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_partition_data_set_partition_value(duckdb_v2_table_function_partition_data_info_handle info, - idx_t index, duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(value); - return WithErrorHandler(err, [&]() { - auto &args = *Convert(info); - if (index >= args.out_partition_values.size()) { - throw duckdb::InvalidInputException( - "Index out of bounds in duckdb_v2_table_function_partition_data_set_partition_value"); - } - const auto &expected_type = (*args.in_column_types)[(*args.in_partition_columns)[index]]; - const auto &actual = *Convert(value); - if (actual.type() != expected_type) { - throw duckdb::InvalidInputException( - "duckdb_v2_table_function_partition_data_set_partition_value: expected type %s for the " - "partitioning column at index %llu, got %s", - expected_type.ToString(), index, actual.type().ToString()); - } - args.out_partition_values[index] = actual; - args.out_partition_value_set[index] = true; - }); -} - DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_user_data(duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err) { @@ -2054,35 +885,6 @@ duckdb_v2_table_function_partitioning_set_partition_info(duckdb_v2_table_functio [&]() { Convert(info)->out_partition_info = CV2ConvertPartitionInfo(partition_info); }); } -DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_user_data(duckdb_v2_table_function_stats_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_bind_data(duckdb_v2_table_function_stats_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_column_index(duckdb_v2_table_function_stats_info_handle info, - idx_t *column_index, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(column_index); - return WithErrorHandler(err, [&]() { *column_index = Convert(info)->in_column_index; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_result_stats(duckdb_v2_table_function_stats_info_handle info, - duckdb_v2_stats_handle *stats, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(stats); - return WithErrorHandler(err, [&]() { *stats = Convert(&Convert(info)->result_stats); }); -} - DUCKDB_V2_ERROR duckdb_v2_connection_register_table_function(duckdb_v2_connection_handle conn, duckdb_v2_table_function_handle function, duckdb_v2_error_info_handle *err) { @@ -2129,56 +931,6 @@ DUCKDB_V2_ERROR duckdb_v2_table_function_destroy(duckdb_v2_table_function_handle }); } -//---------------------------------------------------------------------------------------------------------------------- -// Batch claiming -//---------------------------------------------------------------------------------------------------------------------- - -DUCKDB_V2_ERROR -duckdb_v2_table_function_set_claim_batch_callback(duckdb_v2_table_function_handle function, - duckdb_v2_table_function_claim_batch_callback_fn callback, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->info.claim_batch_cb = callback; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_claim_batch_get_user_data(duckdb_v2_table_function_claim_batch_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_claim_batch_get_bind_data(duckdb_v2_table_function_claim_batch_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_claim_batch_get_global_state(duckdb_v2_table_function_claim_batch_info_handle info, - void **data, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); -} - -DUCKDB_V2_ERROR -duckdb_v2_table_function_claim_batch_get_local_state(duckdb_v2_table_function_claim_batch_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_local_state; }); -} - -DUCKDB_V2_ERROR duckdb_v2_table_function_claim_batch_set_claimed(duckdb_v2_table_function_claim_batch_info_handle info, - bool claimed, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - return WithErrorHandler(err, [&]() { Convert(info)->out_claimed = claimed; }); -} - //---------------------------------------------------------------------------------------------------------------------- // File readers //---------------------------------------------------------------------------------------------------------------------- diff --git a/src/duckdb/src/main/client_context.cpp b/src/duckdb/src/main/client_context.cpp index 2b432af7b..1d02ca552 100644 --- a/src/duckdb/src/main/client_context.cpp +++ b/src/duckdb/src/main/client_context.cpp @@ -237,6 +237,19 @@ void ClientContext::Destroy() { CleanupInternal(lock); } +void ClientContext::LeaveSharedTransaction() { + if (Exception::UncaughtException() || !transaction.IsInSharedTransaction()) { + return; + } + try { + Destroy(); + } catch (...) { + // the transaction cannot be left while the active query may still be running + return; + } + RollbackActiveTransaction(); +} + void ClientContext::ProcessError(ErrorData &error, const string &query) const { error.FinalizeError(); if (Settings::Get(*this)) { @@ -1226,6 +1239,10 @@ void ClientContext::RegisterFunction(CreateFunctionInfo &info) { void ClientContext::RunTransactionStatementInternal(const TransactionInfo &info) { auto type = info.type; + if (transaction.IsInherited()) { + throw TransactionException( + "a connection that inherited its transaction cannot start, join, commit or roll back a transaction"); + } if (type == TransactionType::COMMIT && transaction.HasActiveTransaction() && ValidChecker::IsInvalidated(ActiveTransaction())) { // transaction is invalidated - turn COMMIT into ROLLBACK @@ -1253,6 +1270,9 @@ void ClientContext::RunTransactionStatementInternal(const TransactionInfo &info) } break; } + case TransactionType::JOIN_TRANSACTION: + transaction.JoinTransaction(info.share_id); + break; case TransactionType::COMMIT: if (transaction.IsAutoCommit()) { throw TransactionException("cannot commit - no transaction is active"); diff --git a/src/duckdb/src/main/client_context_execution.cpp b/src/duckdb/src/main/client_context_execution.cpp index ac1260ec9..cf78d0935 100644 --- a/src/duckdb/src/main/client_context_execution.cpp +++ b/src/duckdb/src/main/client_context_execution.cpp @@ -24,6 +24,7 @@ #include "duckdb/main/result_format.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/main/valid_checker.hpp" +#include "duckdb/common/exception/transaction_exception.hpp" #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/transaction/meta_transaction.hpp" #include "duckdb/transaction/transaction_context.hpp" @@ -125,6 +126,13 @@ ErrorData ClientContext::EndQueryInternal(ClientContextLock &lock, bool success, if (transaction.HasActiveTransaction()) { transaction.ResetActiveQuery(); if (transaction.IsAutoCommit()) { + if (success && ValidChecker::IsInvalidated(ActiveTransaction())) { + // a connection that inherited the transaction failed a statement in it + ErrorData invalidated(ExceptionType::TRANSACTION, + ValidChecker::InvalidatedMessage(ActiveTransaction())); + transaction.Rollback(&invalidated); + throw TransactionException("Failed to commit: %s", invalidated.RawMessage()); + } if (success) { transaction.Commit(); } else { diff --git a/src/duckdb/src/main/client_data.cpp b/src/duckdb/src/main/client_data.cpp index 9caedfa85..dcfe62431 100644 --- a/src/duckdb/src/main/client_data.cpp +++ b/src/duckdb/src/main/client_data.cpp @@ -3,7 +3,7 @@ #include "duckdb/catalog/catalog_search_path.hpp" #include "duckdb/common/constants.hpp" -#include "duckdb/common/opener_file_system.hpp" +#include "duckdb/common/file_system.hpp" #include "duckdb/common/random_engine.hpp" #include "duckdb/common/serializer/buffered_file_writer.hpp" #include "duckdb/main/attached_database.hpp" @@ -32,7 +32,10 @@ ClientData::~ClientData() { // This needs to be destroyed first because PreparedStatementData holds a PhysicalPlan, // and the PhysicalPlan holds objects that might rely on the client file opener/file system/buffer manager prepared_statements.clear(); - temporary_objects->Close(DatabaseCloseAction::SKIP_CHECKPOINT); + if (temporary_objects.use_count() == 1) { + // otherwise a shared transaction still uses it and the last reference closes it + temporary_objects->Close(DatabaseCloseAction::SKIP_CHECKPOINT); + } } ClientData &ClientData::Get(ClientContext &context) { diff --git a/src/duckdb/src/main/connection.cpp b/src/duckdb/src/main/connection.cpp index 77b949a2e..36dc226e5 100644 --- a/src/duckdb/src/main/connection.cpp +++ b/src/duckdb/src/main/connection.cpp @@ -38,6 +38,15 @@ Connection Connection::CreateInternal(ClientContext &caller) { return con; } +Connection Connection::CreateInTransaction(ClientContext &context) { + Connection con(*context.db); + auto &new_context = *con.context; + new_context.base_context = context.base_context ? context.base_context : context.shared_from_this(); + new_context.internal_depth = context.internal_depth + 1; + new_context.transaction.InheritTransaction(context); + return con; +} + Connection::Connection(Connection &&other) noexcept { std::swap(context, other.context); std::swap(connection_id, other.connection_id); @@ -54,6 +63,8 @@ Connection::~Connection() { return; } ConnectionManager::Get(*context->db).RemoveConnection(*context); + // outstanding results can keep the context alive, but the connection stops participating in a shared transaction + context->LeaveSharedTransaction(); } string Connection::GetProfilingInformation(const ProfilerPrintFormat &format) { diff --git a/src/duckdb/src/main/context.cpp b/src/duckdb/src/main/context.cpp index 1d385560d..8179b48a6 100644 --- a/src/duckdb/src/main/context.cpp +++ b/src/duckdb/src/main/context.cpp @@ -1,7 +1,7 @@ #include "duckdb/main/context.hpp" #include "duckdb/catalog/catalog_transaction.hpp" -#include "duckdb/common/opener_file_system.hpp" +#include "duckdb/common/file_system.hpp" #include "duckdb/logging/log_manager.hpp" #include "duckdb/logging/logger.hpp" #include "duckdb/main/client_config.hpp" @@ -19,12 +19,11 @@ namespace duckdb { //! The file system of a client: the database file system with the client file opener -class ClientFileSystem : public OpenerFileSystem { +class ClientFileSystem : public FileSystem { public: explicit ClientFileSystem(ClientContext &context_p) : context(context_p) { } -private: VirtualFileSystem &GetFileSystem() const override { return VirtualFileSystem::Get(context); } diff --git a/src/duckdb/src/main/database.cpp b/src/duckdb/src/main/database.cpp index 7f405ef51..a0834d665 100644 --- a/src/duckdb/src/main/database.cpp +++ b/src/duckdb/src/main/database.cpp @@ -407,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, GetFileSystem(), {config.options.database_type}); + ExtensionHelper::LoadExternalExtension(*this, fs, {config.options.database_type}); } } @@ -492,7 +492,7 @@ VirtualFileSystem &LocalDatabaseFileSystem::GetFileSystem() const { return file_system; } -optional_ptr LocalDatabaseFileSystem::GetFixedFileSystem() const { +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()); diff --git a/src/duckdb/src/main/database_manager.cpp b/src/duckdb/src/main/database_manager.cpp index b729292f2..2443d021e 100644 --- a/src/duckdb/src/main/database_manager.cpp +++ b/src/duckdb/src/main/database_manager.cpp @@ -62,7 +62,7 @@ optional_ptr DatabaseManager::GetDatabase(ClientContext &conte lock_guard guard(databases_lock); shared_ptr db; if (name == TEMP_CATALOG) { - db = context.client_data->temporary_objects; + db = meta_transaction.GetTemporaryObjectsPtr(); } else { db = GetDatabaseInternal(guard, name); } @@ -579,7 +579,11 @@ vector> DatabaseManager::GetDatabases(ClientContext result.push_back(system); } if (!max_db_count.IsValid() || max_db_count.GetIndex() >= 2) { - result.push_back(context.client_data->temporary_objects); + if (context.transaction.HasActiveTransaction()) { + result.push_back(context.transaction.ActiveTransaction().GetTemporaryObjectsPtr()); + } else { + result.push_back(context.client_data->temporary_objects); + } } return result; diff --git a/src/duckdb/src/main/extension/extension_helper.cpp b/src/duckdb/src/main/extension/extension_helper.cpp index 88d380a8f..559b123f1 100644 --- a/src/duckdb/src/main/extension/extension_helper.cpp +++ b/src/duckdb/src/main/extension/extension_helper.cpp @@ -96,6 +96,7 @@ static const DefaultExtension internal_extensions[] = { {"unity_catalog", "Adds support for connecting to Unity Catalog"}, {"glue", "Adds support for the AWS Glue Data Catalog"}, {"legacy_parser", "Adds the SQL parser DuckDB used up to 1.5"}, + {"test", "Runs SQL logic tests and compiled test bundles"}, {nullptr, nullptr}}; idx_t ExtensionHelper::DefaultExtensionCount() { diff --git a/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp b/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp index 7aa17ae3e..edb1d01b1 100644 --- a/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp +++ b/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp @@ -116,10 +116,10 @@ static idx_t MaxDynamicFilterTargetCardinality(LogicalOperator &op, const Expres return 0; } - vector columns {std::move(column)}; + vector columns; + columns.push_back(std::move(column)); vector targets; - JoinFilterPushdownOptimizer::GetPushdownFilterTargets(op, std::move(columns), targets, - EqualityPropagation::ENABLED); + JoinFilterPushdownOptimizer::GetPushdownFilterTargets(op, columns, targets, EqualityPropagation::ENABLED); // Dynamic filters are applied at the scan target found here. Estimate the work that the // filter can avoid at that point, even if later filters reduce the cardinality at the join. diff --git a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp index a2435e925..a6c699d15 100644 --- a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp +++ b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp @@ -604,96 +604,47 @@ class PlanSignatureTableIndexMap { vector> children; }; -class PlanSignatureCreateState { -public: - explicit PlanSignatureCreateState(ClientContext &context) - : stream(DEFAULT_BLOCK_ALLOC_SIZE), serializer(stream), allocator(BufferAllocator::Get(context)), - table_index_map(allocator) { - } - -public: -public: - //! For serializing operators to a binary string - MemoryStream stream; - BinarySerializer serializer; - - //! For batching allocations together - ArenaAllocator allocator; - - //! Manages mappings - PlanSignatureTableIndexMap table_index_map; -}; +class PlanSignatureCreateState; class PlanSignature { -public: +private: PlanSignature(const MemoryStream &stream_p, idx_t offset_p, idx_t length_p, - vector> &&child_signatures_p, idx_t operator_count_p) + vector> &&child_signatures_p, idx_t operator_count_p) : stream(stream_p), offset(offset_p), length(length_p), - signature_hash(Hash(stream_p.GetData() + offset, length)), child_signatures(std::move(child_signatures_p)), - operator_count(operator_count_p) { + signature_hash(ComputeHash(stream_p, offset_p, length_p, child_signatures_p)), + child_signatures(std::move(child_signatures_p)), operator_count(operator_count_p) { } public: - static arena_ptr Create(PlanSignatureCreateState &state, LogicalOperator &op, - vector> &&child_signatures, - const vector> &positional_inputs = {}) { - if (!OperatorIsSupported(op)) { - return nullptr; - } - - auto can_materialize = state.table_index_map.Convert(op); - - // Serialize canonical representation of operator - const auto offset = state.stream.GetPosition(); - state.serializer.Begin(); - state.serializer.WriteProperty(100, "positional_inputs", positional_inputs); - state.serializer.End(); - state.serializer.Begin(); - try { // Operators will throw if they cannot serialize, so we need to try/catch here - op.Serialize(state.serializer); - } catch (std::exception &) { - can_materialize = false; - } - state.serializer.End(); - const auto length = state.stream.GetPosition() - offset; + static optional_ptr Create(PlanSignatureCreateState &state, LogicalOperator &op, + vector> &&child_signatures, + const vector> &positional_inputs = {}); - // Convert back from canonical - state.table_index_map.Convert(op); - - if (!can_materialize) { - return nullptr; // Cannot materialize, no point in adding it - } - - // Collect some statistics so we can select a good candidate later - idx_t operator_count = 1; - for (auto &child_signature : child_signatures) { - operator_count += child_signature.get().OperatorCount(); - } - return state.allocator.MakePtr(state.stream, offset, length, std::move(child_signatures), - operator_count); - } + PlanSignature(PlanSignature &&) = default; + PlanSignature(const PlanSignature &) = delete; idx_t OperatorCount() const { return operator_count; } hash_t HashSignature() const { - auto res = signature_hash; - for (auto &child : child_signatures) { - res = CombineHash(res, child.get().HashSignature()); - } - return res; + return signature_hash; } bool Equals(const PlanSignature &other) const { + D_ASSERT(RefersToSameObject(stream, other.stream)); + if (RefersToSameObject(*this, other)) { + return true; + } if (this->GetSignature() != other.GetSignature()) { return false; } if (this->child_signatures.size() != other.child_signatures.size()) { return false; } + // Children are interned before their parents, so their identities prove exact subtree equality. for (idx_t child_idx = 0; child_idx < this->child_signatures.size(); ++child_idx) { - if (!this->child_signatures[child_idx].get().Equals(other.child_signatures[child_idx].get())) { + if (!RefersToSameObject(this->child_signatures[child_idx].get(), other.child_signatures[child_idx].get())) { return false; } } @@ -701,8 +652,17 @@ class PlanSignature { } private: + static hash_t ComputeHash(const MemoryStream &stream, idx_t offset, idx_t length, + const vector> &children) { + auto result = Hash(stream.GetData() + offset, length); + for (auto &child : children) { + result = Hash(CombineHash(result, child.get().HashSignature())); + } + return result; + } + String GetSignature() const { - return String(char_ptr_cast(stream.GetData() + offset), NumericCast(length)); + return String::Reference(char_ptr_cast(stream.GetData() + offset), NumericCast(length)); } static bool OperatorIsSupported(LogicalOperator &op) { @@ -775,7 +735,7 @@ class PlanSignature { const hash_t signature_hash; - const vector> child_signatures; + vector> child_signatures; const idx_t operator_count; }; @@ -791,6 +751,84 @@ struct PlanSignatureEquality { } }; +class PlanSignatureCreateState { +public: + explicit PlanSignatureCreateState(ClientContext &context) + : stream(DEFAULT_BLOCK_ALLOC_SIZE), serializer(stream), allocator(BufferAllocator::Get(context)), + table_index_map(allocator) { + } + +private: + //! For serializing operators to a binary string + MemoryStream stream; + BinarySerializer serializer; + +public: + //! For batching allocations together + ArenaAllocator allocator; + + //! Manages mappings + PlanSignatureTableIndexMap table_index_map; + +private: + friend class PlanSignature; + + const PlanSignature &Intern(PlanSignature signature) { + auto entry = signatures.find(signature); + if (entry != signatures.end()) { + return entry->first.get(); + } + auto owned = allocator.MakePtr(std::move(signature)); + auto &result = *owned; + signatures.emplace(result, std::move(owned)); + return result; + } + +private: + //! Own canonical signatures for this discovery pass; parent signatures borrow their children. + unordered_map, arena_ptr, PlanSignatureHash, PlanSignatureEquality> + signatures; +}; + +optional_ptr PlanSignature::Create(PlanSignatureCreateState &state, LogicalOperator &op, + vector> &&child_signatures, + const vector> &positional_inputs) { + if (!OperatorIsSupported(op)) { + return nullptr; + } + + auto can_materialize = state.table_index_map.Convert(op); + + // Serialize canonical representation of operator + const auto offset = state.stream.GetPosition(); + state.serializer.Begin(); + state.serializer.WriteProperty(100, "positional_inputs", positional_inputs); + state.serializer.End(); + state.serializer.Begin(); + try { // Operators will throw if they cannot serialize, so we need to try/catch here + op.Serialize(state.serializer); + } catch (std::exception &) { + can_materialize = false; + } + state.serializer.End(); + const auto length = state.stream.GetPosition() - offset; + + // Convert back from canonical + state.table_index_map.Convert(op); + + if (!can_materialize) { + return nullptr; // Cannot materialize, no point in adding it + } + + // Collect some statistics so we can select a good candidate later + idx_t operator_count = 1; + for (auto &child_signature : child_signatures) { + D_ASSERT(RefersToSameObject(state.stream, child_signature.get().stream)); + operator_count += child_signature.get().OperatorCount(); + } + return state.Intern(PlanSignature(state.stream, offset, length, std::move(child_signatures), operator_count)); +} + struct Subplan { reference> op; arena_vector canonical_bindings; @@ -808,7 +846,50 @@ struct SubplanInfo { reference> lowest_common_ancestor; }; -using subplan_map_t = unordered_map, SubplanInfo, PlanSignatureHash, PlanSignatureEquality>; +using subplan_map_t = + unordered_map, SubplanInfo, PlanSignatureHash, PlanSignatureEquality>; + +//! Append generated CTEs in extraction order at each original lowest common ancestor. +class CommonSubplanCTEPlacement { +public: + void Insert(unique_ptr &ancestor, Identifier name, TableIndex index, idx_t column_count, + unique_ptr producer) { + auto entry = insertion_points.emplace(ancestor, ancestor).first; + auto &consumer = entry->second.get(); + auto cte = make_uniq(std::move(name), index, column_count, std::move(producer), + std::move(consumer), CTEMaterialize::CTE_MATERIALIZE_DEFAULT); + auto &result = *cte; + consumer = std::move(cte); + entry->second = result.children[1]; + } + +private: + //! Earlier CTEs must enclose later ones to preserve pipeline dependencies. The original ancestor slots + //! identify insertion sites; their consumer tails move into the newly appended CTEs. + //! Subplans are extracted smallest first, so a site's extractions finish before an enclosing subplan can remove it. + reference_map_t, reference>> insertion_points; +}; + +//! Rewrite a consumer scope without revisiting the producers already finalized by this extraction. +class CommonSubplanBindingRewriter : public ColumnBindingReplacer { +public: + CommonSubplanBindingRewriter(const BindingReplacementGraph &replacements, TableIndex first_cte_index_p) + : ColumnBindingReplacer(replacements), first_cte_index(first_cte_index_p) { + } + + void VisitOperator(LogicalOperator &op) override { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && + op.Cast().table_index >= first_cte_index) { + VisitOperator(*op.children[1]); + VisitOperatorBindings(op); + return; + } + ColumnBindingReplacer::VisitOperator(op); + } + +private: + TableIndex first_cte_index; +}; //===--------------------------------------------------------------------===// // CommonSubplanFinder @@ -825,7 +906,7 @@ class CommonSubplanFinder { unique_ptr &parent; const idx_t depth; - arena_ptr signature; + optional_ptr signature; }; struct StackNode { @@ -846,16 +927,13 @@ class CommonSubplanFinder { }; struct SubplanStats { - idx_t base_table_count; - idx_t max_base_table_cardinality; - - void Combine(const SubplanStats &other) { - this->base_table_count += other.base_table_count; - this->max_base_table_cardinality = - MaxValue(this->max_base_table_cardinality, other.max_base_table_cardinality); - } + idx_t base_table_count = 0; + idx_t max_base_table_cardinality = 0; + bool ends_in_aggregate_or_distinct = false; }; + using subplan_stats_map_t = reference_map_t; + struct SubplanBindings { struct ExpressionSource { ExpressionSource(LogicalOperator &op, const vector> &expressions, @@ -924,6 +1002,14 @@ class CommonSubplanFinder { public: void FindCommonSubplans(reference> root) { + // Filtering does not change the tree. Discard its statistics before CTE extraction starts. + subplan_stats_map_t subplan_stats; + CollectCommonSubplans(root, subplan_stats); + FilterSubplans(subplan_stats); + } + +private: + void CollectCommonSubplans(reference> root, subplan_stats_map_t &subplan_stats) { // Find first operator with more than 1 child while (root.get()->children.size() == 1) { root = root.get()->children[0]; @@ -945,6 +1031,11 @@ class CommonSubplanFinder { continue; } + subplan_stats.emplace( + *current.op, GetSubplanStats(*current.op, [&](const LogicalOperator &child) -> const SubplanStats & { + return subplan_stats.at(child); + })); + if (!RefersToSameObject(current.op, root.get())) { // We have all child information for this operator now, compute signature D_ASSERT(operator_infos.find(current.op) != operator_infos.end()); @@ -992,7 +1083,7 @@ class CommonSubplanFinder { } } - void FilterSubplans() { + void FilterSubplans(const subplan_stats_map_t &subplan_stats) { // Filter out redundant or ineligible subplans before returning vector to_remove; for (auto &entry : subplans) { @@ -1019,7 +1110,7 @@ class CommonSubplanFinder { const auto parent_subplan_count = parent_it->second.subplans.size(); const auto parent_count = parent_subplan_count * parent_signature->OperatorCount(); if (parent_subplan_count != 1 && parent_count >= subplan_count && - ShouldMaterialize(parent_it->second)) { + ShouldMaterialize(parent_it->second, subplan_stats)) { to_remove.push_back(signature); // Parent is better, this one is redundant continue; } @@ -1056,8 +1147,12 @@ class CommonSubplanFinder { } } +public: void ConvertSubplansToCTEs(Optimizer &optimizer, unique_ptr &op) { const auto sorted_subplans = GetSortedSubplans(); + CommonSubplanCTEPlacement placement; + BindingReplacementGraph pending_replacements; + TableIndex first_cte_index; idx_t index = 1; for (auto &entry : sorted_subplans) { auto &subplan_info = entry.get().second; @@ -1070,10 +1165,9 @@ class CommonSubplanFinder { const auto cte_index = optimizer.binder.GenerateTableIndex(); const auto cte_name = StringUtil::Format("__common_subplan_%llu", index++); - if (!min_cte_idx.IsValid()) { - min_cte_idx = cte_index; + if (!first_cte_index.IsValid()) { + first_cte_index = cte_index; } - const auto &primary_subplan = subplan_info.subplans[0]; vector> old_bindings(subplan_info.subplans.size()); @@ -1182,10 +1276,8 @@ class CommonSubplanFinder { } // Create the materialized CTE and replace the common subplans with references to it - auto &lowest_common_ancestor = subplan_info.lowest_common_ancestor.get(); const auto materialized_column_count = types.size(); auto materialized_subplan = std::move(primary_subplan.op.get()); - auto remainder = std::move(lowest_common_ancestor); vector> materialized_select_list; for (idx_t i = 0; i < materialized_output_bindings.size(); i++) { materialized_select_list.emplace_back( @@ -1194,40 +1286,25 @@ class CommonSubplanFinder { auto materialized_projection = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(materialized_select_list)); materialized_projection->children.emplace_back(std::move(materialized_subplan)); - auto cte = make_uniq(Identifier(cte_name), cte_index, materialized_column_count, - std::move(materialized_projection), std::move(remainder), - CTEMaterialize::CTE_MATERIALIZE_DEFAULT); + // Finish this producer using only earlier extractions. Its own output replacements apply to + // its readers, never to the retained definition. Later extractions cannot occur inside it. + if (!pending_replacements.Empty()) { + CommonSubplanBindingRewriter rewriter(pending_replacements, first_cte_index); + rewriter.VisitOperator(*materialized_projection); + } for (idx_t subplan_idx = 0; subplan_idx < subplan_info.subplans.size(); subplan_idx++) { const auto &subplan = subplan_info.subplans[subplan_idx]; subplan.op.get() = std::move(cte_refs[subplan_idx]); } - lowest_common_ancestor = std::move(cte); - - // Replace bindings of subplans with those of the CTE refs - ColumnBindingReplacer replacer(replacements); - replacer.stop_operator = lowest_common_ancestor.get(); - replacer.VisitOperator(*op); // Replace from the root until CTE - replacer.VisitOperator(*lowest_common_ancestor->children[1]); // Replace in CTE child - - // We have to be careful with the order in which we place the CTEs created by this optimizer - // Pipeline dependencies cannot be set up if CTEs are in the wrong order - // This performs "CTE pushdown" until the CTEs are in the correct order - reference> current_op = lowest_common_ancestor; - while (true) { - auto &rhs_child = current_op.get()->children[1]; - if (rhs_child->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { - const auto child_table_index = rhs_child->Cast().table_index; - if (child_table_index >= min_cte_idx && child_table_index < cte_index) { - auto tmp = std::move(rhs_child->children[1]); - rhs_child->children[1] = std::move(current_op.get()); - current_op.get() = std::move(rhs_child); - rhs_child = std::move(tmp); - current_op = current_op.get()->children[1]; - continue; - } - } - break; - } + placement.Insert(subplan_info.lowest_common_ancestor, Identifier(cte_name), cte_index, + materialized_column_count, std::move(materialized_projection)); + pending_replacements.Merge(replacements); + } + // Selection reads output bindings and canonical expressions, which do not require rewriting + // the remaining consumer expressions after every extraction. + if (!pending_replacements.Empty()) { + CommonSubplanBindingRewriter rewriter(pending_replacements, first_cte_index); + rewriter.VisitOperator(*op); } } @@ -1298,8 +1375,8 @@ class CommonSubplanFinder { } } - arena_ptr CreatePlanSignature(unique_ptr &op) { - vector> child_signatures; + optional_ptr CreatePlanSignature(unique_ptr &op) { + vector> child_signatures; for (auto &child : op->children) { auto it = operator_infos.find(child); D_ASSERT(it != operator_infos.end()); @@ -1499,32 +1576,48 @@ class CommonSubplanFinder { IsSelectiveMultiTablePlan(*subplan, subplan->estimated_cardinality)); } + bool ShouldMaterialize(const SubplanInfo &subplan_info, const subplan_stats_map_t &subplan_stats) const { + auto &subplan = *subplan_info.subplans[0].op.get(); + const auto &stats = subplan_stats.at(subplan); + return stats.ends_in_aggregate_or_distinct || + (subplan.has_estimated_cardinality && IsSelectiveMultiTablePlan(stats, subplan.estimated_cardinality)); + } + static bool CanExpandScan(const LogicalGet &get) { return get.children.empty() && !get.has_pushed_projection && !get.extra_info.sample_options && !get.dynamic_filters; } - static SubplanStats GetSubplanStats(const LogicalOperator &op) { + template + static SubplanStats GetSubplanStats(const LogicalOperator &op, GET_CHILD_STATS get_child_stats) { SubplanStats subplan_stats; + subplan_stats.ends_in_aggregate_or_distinct = CTEInlining::IsAggregateOrWindow(op); if (op.children.empty()) { subplan_stats.base_table_count = 1; subplan_stats.max_base_table_cardinality = op.has_estimated_cardinality ? op.estimated_cardinality : 0; } else { - subplan_stats = GetSubplanStats(*op.children[0]); - for (idx_t i = 1; i < op.children.size(); i++) { - subplan_stats.Combine(GetSubplanStats(*op.children[i])); + for (auto &child : op.children) { + const auto &child_stats = get_child_stats(*child); + subplan_stats.base_table_count += child_stats.base_table_count; + subplan_stats.max_base_table_cardinality = + MaxValue(subplan_stats.max_base_table_cardinality, child_stats.max_base_table_cardinality); + if (op.children.size() == 1) { + subplan_stats.ends_in_aggregate_or_distinct |= child_stats.ends_in_aggregate_or_distinct; + } } } return subplan_stats; } -public: - static bool IsSelectiveMultiTablePlan(const LogicalOperator &op, idx_t cardinality) { + static SubplanStats GetSubplanStats(const LogicalOperator &op) { + return GetSubplanStats(op, [](const LogicalOperator &child) { return GetSubplanStats(child); }); + } + + static bool IsSelectiveMultiTablePlan(const SubplanStats &subplan_stats, idx_t cardinality) { static constexpr idx_t CARDINALITY_THRESHOLD = 2048; static constexpr idx_t CARDINALITY_RATIO = 2; // Must select more than 1 base table - const auto subplan_stats = GetSubplanStats(op); if (subplan_stats.base_table_count < 2) { return false; } @@ -1538,6 +1631,11 @@ class CommonSubplanFinder { return cardinality < subplan_stats.max_base_table_cardinality / CARDINALITY_RATIO; } +public: + static bool IsSelectiveMultiTablePlan(const LogicalOperator &op, idx_t cardinality) { + return IsSelectiveMultiTablePlan(GetSubplanStats(op), cardinality); + } + private: vector> GetSortedSubplans() { // Grab entries from map, and sort by smallest plans first @@ -1565,8 +1663,6 @@ class CommonSubplanFinder { column_binding_map_t generated_binding_map; //! Output expressions in canonical input bindings, indexed by canonical output column. unordered_map>> canonical_expressions; - //! Minimum CTE index created by this optimizer - TableIndex min_cte_idx; }; //===--------------------------------------------------------------------===// @@ -1648,7 +1744,7 @@ class CommonJoinFilters { op.Cast().join_type == JoinType::INNER; } - optional_ptr Signature(unique_ptr &op, Candidate &candidate, bool movable) { + optional_ptr Signature(unique_ptr &op, Candidate &candidate, bool movable) { const bool traverse = movable && (IsInnerJoin(*op) || op->type == LogicalOperatorType::LOGICAL_FILTER); if (traverse) { bool safe = true; @@ -1658,7 +1754,7 @@ class CommonJoinFilters { return nullptr; } } - vector> children; + vector> children; for (auto &child : op->children) { auto signature = Signature(child, candidate, traverse); if (!signature) { @@ -1667,8 +1763,7 @@ class CommonJoinFilters { children.emplace_back(*signature); } auto create = [&]() { - signatures.push_back(PlanSignature::Create(state, *op, std::move(children))); - return optional_ptr(signatures.back().get()); + return PlanSignature::Create(state, *op, std::move(children)); }; if (!movable || op->type != LogicalOperatorType::LOGICAL_GET) { return create(); @@ -1802,9 +1897,8 @@ class CommonJoinFilters { private: PlanSignatureCreateState state; - //! Parent signatures and candidate keys reference these objects. - vector> signatures; - unordered_map, vector, PlanSignatureHash, PlanSignatureEquality> candidates; + unordered_map, vector, PlanSignatureHash, PlanSignatureEquality> + candidates; }; //===--------------------------------------------------------------------===// @@ -1819,7 +1913,6 @@ unique_ptr CommonSubplanOptimizer::Optimize(unique_ptr expression_p, uniq struct CMHelper { static bool TypeRequiresRestore(CompressedMaterializationType materialization_type); - static unique_ptr CreateProjection(const Optimizer &optimizer, const LogicalOperator &source, + //! Construct a projection with resolved output types over an already resolved child. + static unique_ptr CreateProjection(const Optimizer &optimizer, unique_ptr child, vector> projections); static unique_ptr CreateStatsAwareCast(ClientContext &context, unique_ptr input, const LogicalType &target_type, @@ -118,13 +119,15 @@ bool CMHelper::TypeRequiresRestore(CompressedMaterializationType materialization return materialization_type != CompressedMaterializationType::INVALID; } -unique_ptr CMHelper::CreateProjection(const Optimizer &optimizer, const LogicalOperator &source, +unique_ptr CMHelper::CreateProjection(const Optimizer &optimizer, unique_ptr child, vector> projections) { const auto table_index = optimizer.binder.GenerateTableIndex(); auto projection = make_uniq(table_index, std::move(projections)); - if (source.has_estimated_cardinality) { - projection->SetEstimatedCardinality(source.estimated_cardinality); + if (child->has_estimated_cardinality) { + projection->SetEstimatedCardinality(child->estimated_cardinality); } + projection->children.push_back(std::move(child)); + projection->ResolveOperatorTypesFromChildren(); return projection; } @@ -451,8 +454,6 @@ void CompressedMaterialization::Compress(unique_ptr &op) { return; } - op->ResolveOperatorTypes(); - switch (op->type) { case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: CompressAggregate(op); @@ -529,11 +530,7 @@ void CompressedMaterialization::CreateCompressProjection(unique_ptrexpression)); } - auto compress_projection = CMHelper::CreateProjection(optimizer, *child_op, std::move(projections)); - compress_projection->ResolveOperatorTypes(); - - compress_projection->children.emplace_back(std::move(child_op)); - child_op = std::move(compress_projection); + child_op = CMHelper::CreateProjection(optimizer, std::move(child_op), std::move(projections)); // Get the new bindings and types child_info.bindings_after = child_op->GetColumnBindings(); @@ -595,7 +592,7 @@ unique_ptr CompressedMaterialization::CreateRestoreExpression(unique void CompressedMaterialization::CreateDecompressProjection(unique_ptr &op, CompressedMaterializationInfo &info) { const auto bindings = op->GetColumnBindings(); - op->ResolveOperatorTypes(); + op->ResolveOperatorTypesFromChildren(); const auto &types = op->types; // Create decompress expressions for everything we compressed @@ -621,10 +618,7 @@ void CompressedMaterialization::CreateDecompressProjection(unique_ptrchildren.emplace_back(std::move(op)); - op = std::move(decompress_projection); + op = CMHelper::CreateProjection(optimizer, std::move(op), std::move(decompress_exprs)); // Check if we're placing a projection on top of the root if (RefersToSameObject(*op->children[0], *root)) { @@ -634,7 +628,6 @@ void CompressedMaterialization::CreateDecompressProjection(unique_ptrGetColumnBindings(); - op->ResolveOperatorTypes(); auto &new_types = op->types; // Initialize a ColumnBindingReplacer with the new bindings and types diff --git a/src/duckdb/src/optimizer/cte_inlining.cpp b/src/duckdb/src/optimizer/cte_inlining.cpp index b2ea273c8..a8ed7426d 100644 --- a/src/duckdb/src/optimizer/cte_inlining.cpp +++ b/src/duckdb/src/optimizer/cte_inlining.cpp @@ -67,13 +67,19 @@ static bool ContainsLimit(const LogicalOperator &op) { return false; } -bool CTEInlining::EndsInAggregateOrDistinct(const LogicalOperator &op) { +bool CTEInlining::IsAggregateOrWindow(const LogicalOperator &op) { switch (op.type) { case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: case LogicalOperatorType::LOGICAL_WINDOW: return true; default: - break; + return false; + } +} + +bool CTEInlining::EndsInAggregateOrDistinct(const LogicalOperator &op) { + if (IsAggregateOrWindow(op)) { + return true; } if (op.children.size() != 1) { return false; diff --git a/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp b/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp index cab2585b7..5577bf0bd 100644 --- a/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp +++ b/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp @@ -16,7 +16,7 @@ namespace duckdb { -static bool CanAffordCTEJoinSource(ClientContext &context, LogicalOperator &op, idx_t target_cardinality) { +static bool CanAffordCTEJoinSource(ClientContext &context, LogicalOperator &op, CardinalityValue target_cardinality) { if (op.type == LogicalOperatorType::LOGICAL_FILTER || op.type == LogicalOperatorType::LOGICAL_PROJECTION) { return op.children.size() == 1 && CanAffordCTEJoinSource(context, *op.children[0], target_cardinality); } @@ -115,8 +115,8 @@ void CTEJoinFilterPusher::Optimize(LogicalOperator &op) { continue; } optional_ptr best; - double best_fraction = 1; - idx_t best_source_count = 0; + CardinalityValue best_fraction(1); + CardinalityValue best_source_count(0); for (auto &filter : join_filters) { if (filter.target != target || filter.target_scan != cte.filter_dependency->row_scan) { continue; @@ -143,11 +143,10 @@ void CTEJoinFilterPusher::Optimize(LogicalOperator &op) { cached == restricted_stats.end() ? extractor.Extract(*source_cte.children[0]) : &cached->second; } // The hash build should be small relative to the input being restricted. - if (!source_stats || static_cast(source_stats->cardinality) > - static_cast(target_stats->cardinality) * MAX_SOURCE_RATIO) { + if (!source_stats || source_stats->cardinality > target_stats->cardinality * MAX_SOURCE_RATIO) { continue; } - double fraction = 1; + CardinalityValue fraction(1); bool valid_columns = true; for (idx_t i = 0; i < filter.comparisons.size(); i++) { auto source_col = filter.source_keys[i].column.GetIndex(); @@ -163,7 +162,11 @@ void CTEJoinFilterPusher::Optimize(LogicalOperator &op) { } auto source_count = MinValue(source_distinct.distinct_count, source_stats->cardinality); auto target_count = MinValue(target_distinct.distinct_count, target_stats->cardinality); - fraction = MinValue(fraction, static_cast(source_count) / static_cast(target_count)); + if (target_count.IsZero()) { + valid_columns = false; + break; + } + fraction = MinValue(fraction, source_count / target_count); } if (valid_columns && fraction <= MAX_KEY_RATIO && (!best || fraction < best_fraction || @@ -210,8 +213,7 @@ void CTEJoinFilterPusher::Optimize(LogicalOperator &op) { best->comparisons[i]); } auto stats = *target_stats; - auto cardinality = LossyNumericCast(std::ceil(static_cast(stats.cardinality) * best_fraction)); - RelationStatisticsHelper::ApplyCardinality(stats, cardinality); + RelationStatisticsHelper::ApplyCardinality(stats, stats.cardinality * best_fraction); for (auto &column : stats.columns) { column.semi_anti_join_domain_evidence.Invalidate(); } diff --git a/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp b/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp index 6c24a023c..76278675a 100644 --- a/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp +++ b/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp @@ -98,7 +98,7 @@ void JoinFilterPushdownOptimizer::GenerateCTEFilters(LogicalMaterializedCTE &cte columns.push_back(std::move(column)); } reference_map_t> targets; - GetCTEFilterTargets(*join.children[0], std::move(columns), targets); + GetCTEFilterTargets(*join.children[0], columns, targets); for (auto &target : targets) { auto &ref = target.first.get(); auto consumer = consumer_indexes.find(ref.table_index); @@ -107,8 +107,10 @@ void JoinFilterPushdownOptimizer::GenerateCTEFilters(LogicalMaterializedCTE &cte } for (auto &column : target.second) { column.probe_column_index = bindings.at(column.probe_column_index.column_index.GetIndex()); + vector producer_columns; + producer_columns.push_back(std::move(column)); vector scans; - GetPushdownFilterTargets(*cte.children[0], {std::move(column)}, scans); + GetPushdownFilterTargets(*cte.children[0], producer_columns, scans); for (auto &scan : scans) { for (auto &scan_column : scan.columns) { auto index = scan_column.probe_column_index.column_index; diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp index af8e6ebe4..d828ac914 100644 --- a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp @@ -673,13 +673,12 @@ static double EstimateKeyProductionWork(RelationStatsExtractor &extractor, Logic } if (input.type == LogicalOperatorType::LOGICAL_CTE_REF) { // This reader disappears; its shared definition may still be used elsewhere. - return static_cast(rows->cardinality) * static_cast(input.GetColumnBindings().size()); + return rows->cardinality.GetDouble() * static_cast(input.GetColumnBindings().size()); } if (input.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { auto child_rows = extractor.Extract(*input.children[0]); if (child_rows) { - return EstimateFixedDomainWork(static_cast(child_rows->cardinality), - static_cast(rows->cardinality)) + + return EstimateFixedDomainWork(child_rows->cardinality.GetDouble(), rows->cardinality.GetDouble()) + EstimateKeyProductionWork(extractor, *input.children[0]); } } @@ -744,8 +743,8 @@ double DomainCostModel::EstimateReleasedWork(RelationStatsExtractor &extractor, if (released.source) { auto stats = extractor.Extract(*released.source); if (stats) { - source_values = static_cast(stats->cardinality) * - static_cast(released.source->GetColumnBindings().size()); + source_values = + stats->cardinality.GetDouble() * static_cast(released.source->GetColumnBindings().size()); } } return RELEASED_WORK_SCALE * (production_work + source_values); @@ -770,7 +769,7 @@ double DomainCostModel::EstimateSemiJoinWork(double input_rows, double output_ro } double DomainCostModel::EstimateRecoveryDomainRows(const RelationStats &domain) { - idx_t distinct_count = 1; + CardinalityValue distinct_count(1); for (auto &column : domain.columns) { // Key independence and range-based estimates can hide repeated tuples. if (column.total_domain.source == DistinctCountSource::HLL || @@ -778,7 +777,7 @@ double DomainCostModel::EstimateRecoveryDomainRows(const RelationStats &domain) distinct_count = MaxValue(distinct_count, column.current_domain.distinct_count); } } - return static_cast(MinValue(distinct_count, domain.cardinality)); + return MinValue(distinct_count, domain.cardinality).GetDouble(); } double DomainCostModel::EstimateRecoveryRowWork(double expression_work, idx_t single_row_joins) { @@ -812,7 +811,7 @@ double DomainCostModel::EstimateAggregateWork(const RelationStats &input, domains.push_back(column->current_domain); } auto group_count = RelationStatisticsHelper::EstimateDistinctCardinality(domains, input.cardinality); - return EstimateAggregateWork(static_cast(input.cardinality), static_cast(group_count)); + return EstimateAggregateWork(input.cardinality.GetDouble(), group_count.GetDouble()); } static optional EstimateRestrictionStats(LogicalComparisonJoin &restriction, const RelationStats &input, @@ -842,8 +841,7 @@ optional DomainCostModel::EstimateRestriction(co } auto groups = RelationStatisticsHelper::EstimateDistinctCardinality({column->current_domain}, restricted->cardinality); - return TupleDomainRestrictionEstimate {static_cast(restricted->cardinality), - static_cast(groups)}; + return TupleDomainRestrictionEstimate {restricted->cardinality.GetDouble(), groups.GetDouble()}; } return RelationStatisticsHelper::EstimateTupleDomainRestriction(restriction, input, keys, extractor); } @@ -866,11 +864,11 @@ bool DomainCostModel::IsProfitable(LogicalComparisonJoin &restriction, LogicalOp // The inserted SEMI is the new aggregate input; old input-shape refinements no longer apply. auto group_count = RelationStatisticsHelper::EstimateDistinctCardinality({column->current_domain}, restricted->cardinality); - auto input_rows = static_cast(input->cardinality); - auto restricted_rows = static_cast(restricted->cardinality); - auto original_groups = static_cast(groups->cardinality); - auto restricted_groups = static_cast(group_count); - auto distinct_key_rows = static_cast(keys->cardinality); + auto input_rows = input->cardinality.GetDouble(); + auto restricted_rows = restricted->cardinality.GetDouble(); + auto original_groups = groups->cardinality.GetDouble(); + auto restricted_groups = group_count.GetDouble(); + auto distinct_key_rows = keys->cardinality.GetDouble(); // Cancel unchanged input/caller work and the consumer's identical output. auto canonical = EstimateAggregateWork(input_rows, original_groups); auto candidate = EstimateAggregateWork(restricted_rows, restricted_groups) + @@ -892,13 +890,13 @@ RestrictionDecision DomainCostModel::ChooseRestrictionAction(const DomainRestric return {}; } auto old_input = EstimateRestriction(existing, *input, *old_keys); - auto old_key_rows = static_cast(old_keys->cardinality); + auto old_key_rows = old_keys->cardinality.GetDouble(); auto old_producer_work = EstimateKeyProductionWork(extractor, *restriction.children[1]); vector group_bindings; for (idx_t key = 0; key < aggregate.groups.size(); key++) { group_bindings.push_back(existing.GetCondition(key).GetLHS().Cast().Binding()); } - auto input_rows = static_cast(input->cardinality); + auto input_rows = input->cardinality.GetDouble(); auto best_work = old_input ? EstimateAggregateWork(old_input->rows, old_input->groups) + EstimateSemiJoinWork(input_rows, old_input->rows, old_key_rows) + old_producer_work + released_work @@ -920,7 +918,7 @@ RestrictionDecision DomainCostModel::ChooseRestrictionAction(const DomainRestric replacement.conditions.emplace_back(condition.GetLHS().Copy(), DomainKey(*domain), condition.GetComparisonType()); auto restricted = EstimateRestrictionStats(replacement, *input, *new_keys); - auto distinct_key_rows = static_cast(new_keys->cardinality); + auto distinct_key_rows = new_keys->cardinality.GetDouble(); auto new_producer_work = EstimateFixedDomainWork(key_input_rows, distinct_key_rows) + source_read_write_work; auto new_key_work = distinct_key_rows + new_producer_work; @@ -933,8 +931,7 @@ RestrictionDecision DomainCostModel::ChooseRestrictionAction(const DomainRestric } if (restricted) { consider(EstimateAggregateWork(*restricted, group_bindings) + - EstimateSemiJoinWork(input_rows, static_cast(restricted->cardinality), - distinct_key_rows) + + EstimateSemiJoinWork(input_rows, restricted->cardinality.GetDouble(), distinct_key_rows) + new_producer_work, RestrictionAction::REPLACE); } else if (!keys_may_expand) { @@ -968,8 +965,10 @@ static bool HasRuntimeFilterTargets(LogicalAggregate &aggregate) { if (!JoinFilterPushdownUtil::PushdownJoinFilterExpression(*aggregate.groups[0], column)) { return false; } + vector columns; + columns.push_back(std::move(column)); vector targets; - JoinFilterPushdownOptimizer::GetPushdownFilterTargets(*aggregate.children[0], {std::move(column)}, targets, + JoinFilterPushdownOptimizer::GetPushdownFilterTargets(*aggregate.children[0], columns, targets, EqualityPropagation::ENABLED); return !targets.empty(); } @@ -1266,10 +1265,10 @@ static void FindScanKeySource(const unique_ptr &input, idx_t ke RelationStatsExtractor &extractor, ClientContext &context, ScanKeySource &source) { if (auto scan = FindClosedScan(*input)) { auto stats = extractor.Extract(*input); - if (stats && (!source.input || static_cast(stats->cardinality) < source.rows)) { + if (stats && (!source.input || stats->cardinality.GetDouble() < source.rows)) { source.input = input; source.key = key; - source.rows = static_cast(stats->cardinality); + source.rows = stats->cardinality.GetDouble(); source.scan_rows = static_cast(scan->EstimateSourceCardinality(context)); } return; @@ -1749,7 +1748,7 @@ bool DuplicateEliminatedDomainOptimizer::TryOptimizeRuntimeDomain(unique_ptr(JoinType::SEMI); restriction->conditions.emplace_back(aggregate.groups[0]->Copy(), DomainKey(*domain), comparison); - auto source_rows = static_cast(source_stats->cardinality); + auto source_rows = source_stats->cardinality.GetDouble(); // CTE readers scan the full row. A new owner also writes it and replaces the consumer with another reader. auto source_read_write_work = (source.owner ? 1 : 3) * source_rows * static_cast(source_types.size()); DomainCostModel costs(extractor, aggregate, source_rows, source_read_write_work); @@ -1855,7 +1854,7 @@ static bool RecoveryIsProfitable(LogicalComparisonJoin &join, const OuterDomainJ if (!outer || !domain) { return false; } - auto outer_rows = static_cast(outer->cardinality); + auto outer_rows = outer->cardinality.GetDouble(); return DomainCostModel::IsRecoveryProfitable(outer_rows, *domain, expression_work, single_row_joins, DomainCostModel::EstimateReleasedWork(extractor, released), restriction_savings); diff --git a/src/duckdb/src/optimizer/filter_combiner.cpp b/src/duckdb/src/optimizer/filter_combiner.cpp index 920412a82..4927d8150 100644 --- a/src/duckdb/src/optimizer/filter_combiner.cpp +++ b/src/duckdb/src/optimizer/filter_combiner.cpp @@ -28,16 +28,12 @@ #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "utf8proc_wrapper.hpp" -#include "duckdb/optimizer/in_clause_rewriter.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" namespace duckdb { using ExpressionValueInformation = FilterCombiner::ExpressionValueInformation; -static ValueComparisonResult CompareValueInformation(ExpressionValueInformation &left, - ExpressionValueInformation &right); - FilterCombiner::FilterCombiner(ClientContext &context) : context(context) { } @@ -73,34 +69,73 @@ idx_t FilterCombiner::GetEquivalenceSet(Expression &expr) { } } -FilterResult FilterCombiner::AddConstantComparison(vector &info_list, - ExpressionValueInformation info) { - if (info.constant.IsNull()) { - return FilterResult::UNSATISFIABLE; - } - for (idx_t i = 0; i < info_list.size(); i++) { - auto comparison = CompareValueInformation(info_list[i], info); - switch (comparison) { - case ValueComparisonResult::PRUNE_LEFT: - // prune the entry from the info list - info_list.erase_at(i); - i--; - break; - case ValueComparisonResult::PRUNE_RIGHT: - // prune the current info - return FilterResult::SUCCESS; - case ValueComparisonResult::UNSATISFIABLE_CONDITION: - // combination of filters is unsatisfiable: prune the entire branch - info_list.push_back(info); - return FilterResult::UNSATISFIABLE; - default: - // prune nothing, move to the next condition - break; +bool FilterCombiner::CanMatchExpression(const Expression &expr) { + if (expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { + // Expression equality must not conflate constants a function can distinguish, such as signed zeros. + return expr.GetReturnType().EqualValuesAreIdentical(); + } + if (expr.GetExpressionClass() == ExpressionClass::BOUND_LAMBDA) { + return false; + } + bool can_match = true; + ExpressionIterator::EnumerateChildren(expr, + [&](const Expression &child) { can_match &= CanMatchExpression(child); }); + return can_match; +} + +bool FilterCombiner::CanCopyFilter(const Expression &filter) { + if (filter.IsVolatile() || filter.CanThrow() || filter.HasParameter()) { + return false; + } + auto compared = GetComparedExpression(filter); + const bool merged_comparison = BoundComparisonExpression::IsComparison(filter) || + filter.GetExpressionType() == ExpressionType::COMPARE_BETWEEN; + return CanMatchExpression(compared && merged_comparison ? *compared : filter); +} + +bool FilterCombiner::IsKeyConstraint(const Expression &filter, const vector> &keys) { + if (!CanCopyFilter(filter)) { + return false; + } + switch (filter.GetExpressionType()) { + case ExpressionType::CONJUNCTION_AND: + case ExpressionType::CONJUNCTION_OR: + case ExpressionType::OPERATOR_NOT: { + bool valid = true; + ExpressionIterator::EnumerateChildren(filter, + [&](const Expression &child) { valid &= IsKeyConstraint(child, keys); }); + return valid; + } + default: + break; + } + auto compared = FilterCombiner::GetComparedExpression(filter); + if (filter.GetExpressionType() == ExpressionType::OPERATOR_IS_NULL || + filter.GetExpressionType() == ExpressionType::OPERATOR_IS_NOT_NULL) { + ExpressionIterator::EnumerateChildren(filter, [&](const Expression &child) { compared = &child; }); + } + if (!compared) { + return false; + } + for (auto &key : keys) { + if (FilterCombiner::CanMatchExpression(key) && key.get().Equals(*compared)) { + return true; } } - // finally add the entry to the list - info_list.push_back(info); - return FilterResult::SUCCESS; + return false; +} + +void FilterCombiner::DeduplicateFilters(vector> &filters) { + expression_set_t seen; + vector> unique_filters; + for (auto &filter : filters) { + if (!filter->IsVolatile() && !filter->CanThrow() && CanMatchExpression(*filter) && + !seen.insert(*filter).second) { + continue; + } + unique_filters.push_back(std::move(filter)); + } + filters = std::move(unique_filters); } FilterResult FilterCombiner::AddFilter(unique_ptr expr) { @@ -135,6 +170,10 @@ void FilterCombiner::GenerateEquivalentFilters(const Expression &filter, // collect every column reference that belongs to an equivalence set vector> candidate_columns; ExpressionIterator::VisitExpression(filter, [&](const BoundColumnRefExpression &col) { + // An arbitrary expression can distinguish equal values with different representations. + if (!col.GetReturnType().EqualValuesAreIdentical()) { + return; + } auto entry = equivalence_set_map.find(col); if (entry == equivalence_set_map.end()) { return; @@ -151,7 +190,8 @@ void FilterCombiner::GenerateEquivalentFilters(const Expression &filter, auto &col = col_ref.get(); auto set_id = equivalence_set_map.find(col)->second; for (auto &item : equivalence_map[set_id]) { - if (item.get().Equals(col)) { + if (item.get().Equals(col) || item.get().CanThrow() || item.get().IsVolatile() || + !CanMatchExpression(item)) { continue; } callback(ExpressionIterator::ReplaceExpression(filter, col, item.get())); @@ -159,12 +199,142 @@ void FilterCombiner::GenerateEquivalentFilters(const Expression &filter, } } +static optional_ptr GetConstraintKey(const Expression &filter) { + auto key = FilterCombiner::GetComparedExpression(filter); + if (key) { + return key; + } + switch (filter.GetExpressionType()) { + case ExpressionType::OPERATOR_IS_NULL: + case ExpressionType::OPERATOR_IS_NOT_NULL: + ExpressionIterator::EnumerateChildren(filter, [&](const Expression &child) { key = &child; }); + break; + case ExpressionType::CONJUNCTION_AND: + case ExpressionType::CONJUNCTION_OR: + case ExpressionType::OPERATOR_NOT: + ExpressionIterator::EnumerateChildren(filter, [&](const Expression &child) { + if (!key) { + key = GetConstraintKey(child); + } + }); + break; + default: + break; + } + return key; +} + +void FilterCombiner::GenerateProjectionFilters(ClientContext &context, const vector> &filters, + const std::function &can_project, + const std::function)> &callback) { + FilterCombiner combiner(context); + auto &groups = combiner.equivalence_map; + auto &group_ids = combiner.equivalence_set_map; + for (auto &filter : filters) { + if (filter->GetExpressionType() != ExpressionType::COMPARE_EQUAL || !CanCopyFilter(*filter)) { + continue; + } + auto &comparison = filter->Cast(); + if (BoundComparisonExpression::Left(comparison).IsScalar() || + BoundComparisonExpression::Right(comparison).IsScalar()) { + continue; + } + auto left = combiner.GetEquivalenceSet(combiner.GetNode(*BoundComparisonExpression::LeftMutable(comparison))); + auto right = combiner.GetEquivalenceSet(combiner.GetNode(*BoundComparisonExpression::RightMutable(comparison))); + if (left == right) { + continue; + } + // Merge smaller classes and discard old buckets: hidden chains must not retain quadratic state. + if (groups[left].size() < groups[right].size()) { + std::swap(left, right); + } + auto &target = groups[left]; + for (auto &member : groups[right]) { + group_ids[member] = left; + target.push_back(member); + } + groups.erase(right); + combiner.constant_values.erase(right); + } + unordered_map> representatives; + for (auto &entry : groups) { + for (auto &member : entry.second) { + if (!can_project(member)) { + continue; + } + auto representative = representatives.find(entry.first); + if (representative == representatives.end()) { + representatives.emplace(entry.first, member.get()); + } else { + // A star connects the visible members without generating pairs involving hidden keys. + callback(BoundComparisonExpression::Create(ExpressionType::COMPARE_EQUAL, + representative->second.get().Copy(), member.get().Copy())); + } + } + } + for (auto &filter : filters) { + auto key = GetConstraintKey(*filter); + if (!key || !IsKeyConstraint(*filter, {*key})) { + continue; + } + auto entry = group_ids.find(*key); + if (entry == group_ids.end()) { + continue; + } + auto representative = representatives.find(entry->second); + if (representative != representatives.end() && !key->Equals(representative->second)) { + callback(ExpressionIterator::ReplaceExpression(*filter, *key, representative->second)); + } + } +} + +void FilterCombiner::GenerateEquivalentKeyFilters(const Expression &filter, + const std::function filter)> &callback) { + if (!CanMatchExpression(filter)) { + return; + } + auto source = GetConstraintKey(filter); + if (!source || !IsKeyConstraint(filter, {*source})) { + return; + } + auto entry = equivalence_set_map.find(*source); + if (entry == equivalence_set_map.end()) { + return; + } + // Replace the whole key: repeated passes cannot form combinations of independent substitutions. + for (auto &target : equivalence_map[entry->second]) { + if (!source->Equals(target) && !target.get().CanThrow() && !target.get().IsVolatile() && + CanMatchExpression(target)) { + callback(ExpressionIterator::ReplaceExpression(filter, *source, target)); + } + } +} + void FilterCombiner::GenerateFilters(const std::function filter)> &callback) { - // first loop over the remaining filters + vector> inferred; + { + expression_set_t seen; + for (auto &filter : remaining_filters) { + if (!filter->IsVolatile() && !filter->CanThrow() && CanMatchExpression(*filter)) { + seen.insert(*filter); + } + } + for (auto &filter : remaining_filters) { + GenerateEquivalentKeyFilters(*filter, [&](unique_ptr copy) { + if (seen.insert(*copy).second) { + inferred.push_back(std::move(copy)); + } + }); + } + } + // Scan pushdown results refer to the unchanged prefix of original filters. for (auto &filter : remaining_filters) { callback(std::move(filter)); } remaining_filters.clear(); + for (auto &filter : inferred) { + callback(std::move(filter)); + } // now loop over the equivalence sets for (auto &entry : equivalence_map) { auto equivalence_set = entry.first; @@ -293,9 +463,7 @@ static unique_ptr CreateOptionalExpressionFilter(unique_ptr CreateAdaptiveInFilter(unique_ptr in_expr, const LogicalType &type) { // Keep large lists pruning-only; evaluating them per row is expensive. - if (in_expr->Cast().GetChildren().size() >= - InClauseRewriter::IN_CLAUSE_REWRITE_THRESHOLD || - !ExpressionFilterExecutor::TryCreate(*in_expr)) { + if (!ExpressionFilter::IsSmallNativeInFilter(*in_expr)) { return CreateOptionalExpressionFilter(std::move(in_expr), type); } return ExpressionFilter::CreateSelectivityOptionalFilter(std::move(in_expr), type, @@ -340,26 +508,12 @@ bool FilterCombiner::IsDenseRange(vector &in_list) { return true; } -static bool SupportedFilterComparison(ExpressionType expression_type) { - switch (expression_type) { - case ExpressionType::COMPARE_EQUAL: - case ExpressionType::COMPARE_GREATERTHAN: - case ExpressionType::COMPARE_GREATERTHANOREQUALTO: - case ExpressionType::COMPARE_LESSTHAN: - case ExpressionType::COMPARE_LESSTHANOREQUALTO: - case ExpressionType::COMPARE_NOTEQUAL: - return true; - default: - return false; - } -} - optional_ptr FilterCombiner::GetComparedExpression(const Expression &filter) { const auto filter_type = filter.GetExpressionType(); // BETWEEN and IN compare their first child with the others const bool compares_first_child = filter_type == ExpressionType::COMPARE_BETWEEN || filter_type == ExpressionType::COMPARE_IN; - if ((!SupportedFilterComparison(filter_type) && !compares_first_child) || filter.IsVolatile()) { + if ((!ConstantFilterCombiner::IsSupportedComparison(filter_type) && !compares_first_child) || filter.IsVolatile()) { return nullptr; } optional_ptr compared; @@ -380,7 +534,7 @@ void FilterCombiner::GenerateJoinFilters(const vector &conditions const std::function filter)> &callback) { D_ASSERT(target_side == JoinSide::LEFT || target_side == JoinSide::RIGHT); for (auto &cond : conditions) { - // a comparison with constants is false for NULL, so NOT DISTINCT FROM acts as equality for it + // A matched row has the same key value, including NULL for NOT DISTINCT FROM. if (!cond.IsComparison() || (cond.GetComparisonType() != ExpressionType::COMPARE_EQUAL && cond.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { continue; @@ -393,24 +547,13 @@ void FilterCombiner::GenerateJoinFilters(const vector &conditions continue; } for (auto &filter : filters) { - auto compared = GetComparedExpression(filter.get()); - if (compared && compared->Equals(source)) { + if (CanMatchExpression(target) && IsKeyConstraint(filter, {source})) { callback(ExpressionIterator::ReplaceExpression(filter.get(), source, target)); } } } } -static bool TypeSupportsConstantFilter(const LogicalType &type) { - if (TypeIsNumeric(type.InternalType())) { - return true; - } - if (type.InternalType() == PhysicalType::VARCHAR || type.InternalType() == PhysicalType::BOOL) { - return true; - } - return false; -} - FilterPushdownResult FilterCombiner::TryPushdownConstantFilter(TableFilterSet &table_filters, const vector &column_ids, column_t expr_id, vector &info_list) { @@ -420,11 +563,11 @@ FilterPushdownResult FilterCombiner::TryPushdownConstantFilter(TableFilterSet &t } auto &constant_info = info_list[0]; // check if the type is supported - if (!TypeSupportsConstantFilter(constant_info.constant.type())) { + if (!ExpressionFilter::SupportsConstantFilterPushdown(constant_info.constant.type())) { // not supported return FilterPushdownResult::NO_PUSHDOWN; } - if (!SupportedFilterComparison(constant_info.comparison_type)) { + if (!ConstantFilterCombiner::IsSupportedComparison(constant_info.comparison_type)) { return FilterPushdownResult::NO_PUSHDOWN; } //! Here we check if these filters are column references @@ -737,7 +880,7 @@ FilterPushdownResult FilterCombiner::TryPushdownInFilter(TableFilterSet &table_f auto &fst_const_value_expr = func.GetChildren()[1]->Cast(); auto &type = fst_const_value_expr.GetValue().type(); - if (func.GetChildren().size() == 2 && TypeSupportsConstantFilter(type)) { + if (func.GetChildren().size() == 2 && ExpressionFilter::SupportsConstantFilterPushdown(type)) { // col IN (literal) is equivalent to an equality comparison - push that down auto bound_eq_comparison = CreateComparisonExpression(*func.GetChildren()[0], ExpressionType::COMPARE_EQUAL, fst_const_value_expr.GetValue()); @@ -856,14 +999,6 @@ FilterPushdownResult FilterCombiner::TryPushdownOrClause(TableFilterSet &table_f return FilterPushdownResult::PUSHED_DOWN_PARTIALLY; } -static bool IsGreaterThan(ExpressionType type) { - return type == ExpressionType::COMPARE_GREATERTHAN || type == ExpressionType::COMPARE_GREATERTHANOREQUALTO; -} - -static bool IsLessThan(ExpressionType type) { - return type == ExpressionType::COMPARE_LESSTHAN || type == ExpressionType::COMPARE_LESSTHANOREQUALTO; -} - //! Returns the relaxation margin in native units of the source type for a temporal cast. //! Returns -1 if the cast pair is not supported for relaxed pushdown. //! Margins: 48h for timestamp casts that read the time zone, 1 day DATE->TIMESTAMPTZ, 24h for time of day, 1s rounding. @@ -1041,7 +1176,7 @@ FilterPushdownResult FilterCombiner::TryPushdownTemporalCastFilter(TableFilterSe return FilterPushdownResult::NO_PUSHDOWN; } auto &comp = expr.Cast(); - if (!SupportedFilterComparison(comp.GetExpressionType())) { + if (!ConstantFilterCombiner::IsSupportedComparison(comp.GetExpressionType())) { return FilterPushdownResult::NO_PUSHDOWN; } if (comp.GetExpressionType() == ExpressionType::COMPARE_NOTEQUAL) { @@ -1098,14 +1233,14 @@ FilterPushdownResult FilterCombiner::TryPushdownTemporalCastFilter(TableFilterSe // push relaxed filter(s) as OptionalFilter auto comparison_type = invert ? FlipComparisonExpression(comp.GetExpressionType()) : comp.GetExpressionType(); - if (IsGreaterThan(comparison_type) || comparison_type == ExpressionType::COMPARE_EQUAL) { + if (ConstantFilterCombiner::IsLowerBound(comparison_type) || comparison_type == ExpressionType::COMPARE_EQUAL) { Value lower = cast_value; if (!AdjustTemporalValue(lower, -margin)) { return FilterPushdownResult::NO_PUSHDOWN; } push_optional(ExpressionType::COMPARE_GREATERTHANOREQUALTO, std::move(lower)); } - if (IsLessThan(comparison_type) || comparison_type == ExpressionType::COMPARE_EQUAL) { + if (ConstantFilterCombiner::IsUpperBound(comparison_type) || comparison_type == ExpressionType::COMPARE_EQUAL) { Value upper = cast_value; if (!AdjustTemporalValue(upper, margin)) { return FilterPushdownResult::NO_PUSHDOWN; @@ -1155,9 +1290,9 @@ void FilterCombiner::TryPushdownRelaxedFilter(TableFilterSet &table_filters, con } } -TableFilterSet FilterCombiner::GenerateTableScanFilters(const vector &column_ids, - vector &pushdown_results) { - TableFilterSet table_filters; +void FilterCombiner::GenerateTableScanFilters(TableFilterSet &table_filters, const vector &column_ids, + vector &pushdown_results) { + DeduplicateFilters(remaining_filters); //! First, we figure the filters that have constant expressions that we can push down to the table scan for (auto &constant_value : constant_values) { auto expr_id = constant_value.first; @@ -1178,12 +1313,11 @@ TableFilterSet FilterCombiner::GenerateTableScanFilters(const vector(); - if (!SupportedFilterComparison(comparison.GetExpressionType())) { + if (!ConstantFilterCombiner::IsSupportedComparison(comparison.GetExpressionType())) { // only support [>, >=, <, <=, ==, !=] expressions return FilterResult::UNSUPPORTED; } @@ -1219,7 +1353,7 @@ FilterResult FilterCombiner::AddBoundComparisonFilter(Expression &expr) { return FilterResult::UNSUPPORTED; } // check the existing constant comparisons to see if we can do any pruning - auto ret = AddConstantComparison(info_list, info); + auto ret = ConstantFilterCombiner::AddComparison(info_list, info); auto &non_scalar = left_is_scalar ? *right : *left; auto transitive_filter = FindTransitiveFilter(non_scalar); @@ -1273,7 +1407,8 @@ FilterResult FilterCombiner::AddBoundComparisonFilter(Expression &expr) { auto &left_constant_bucket = constant_values.find(left_equivalence_set)->second; auto &right_constant_bucket = constant_values.find(right_equivalence_set)->second; for (auto &right_constant : right_constant_bucket) { - if (AddConstantComparison(left_constant_bucket, right_constant) == FilterResult::UNSATISFIABLE) { + if (ConstantFilterCombiner::AddComparison(left_constant_bucket, right_constant) == + FilterResult::UNSATISFIABLE) { return FilterResult::UNSATISFIABLE; } } @@ -1339,7 +1474,7 @@ FilterResult FilterCombiner::AddFilter(Expression &expr) { D_ASSERT(constant_values.find(equivalence_set) != constant_values.end()); auto &info_list = constant_values.find(equivalence_set)->second; // check the existing constant comparisons to see if we can do any pruning - result = AddConstantComparison(info_list, info); + result = ConstantFilterCombiner::AddComparison(info_list, info); } else { D_ASSERT(upper_is_scalar); const auto type = lower_inclusive ? ExpressionType::COMPARE_GREATERTHANOREQUALTO @@ -1374,7 +1509,7 @@ FilterResult FilterCombiner::AddFilter(Expression &expr) { // get the current bucket of constant values D_ASSERT(constant_values.find(equivalence_set) != constant_values.end()); // check the existing constant comparisons to see if we can do any pruning - result = AddConstantComparison(constant_values.find(equivalence_set)->second, info); + result = ConstantFilterCombiner::AddComparison(constant_values.find(equivalence_set)->second, info); } else { D_ASSERT(lower_is_scalar); const auto type = @@ -1396,7 +1531,8 @@ FilterResult FilterCombiner::AddFilter(Expression &expr) { // Infer constant bounds from comparisons between non-scalar expressions. FilterResult FilterCombiner::AddTransitiveFilters(BoundFunctionExpression &comparison, bool is_root) { - if (!IsGreaterThan(comparison.GetExpressionType()) && !IsLessThan(comparison.GetExpressionType())) { + if (!ConstantFilterCombiner::IsLowerBound(comparison.GetExpressionType()) && + !ConstantFilterCombiner::IsUpperBound(comparison.GetExpressionType())) { return FilterResult::UNSUPPORTED; } // Derived bounds must not duplicate volatile or throwing expressions. @@ -1445,9 +1581,9 @@ FilterResult FilterCombiner::AddTransitiveFilters(BoundFunctionExpression &compa // and the filter j >= i can be pruned by not adding it into the remaining filters info.comparison_type = comparison.GetExpressionType(); } else if ((comparison.GetExpressionType() == ExpressionType::COMPARE_GREATERTHANOREQUALTO && - IsGreaterThan(right_constant.comparison_type)) || + ConstantFilterCombiner::IsLowerBound(right_constant.comparison_type)) || (comparison.GetExpressionType() == ExpressionType::COMPARE_LESSTHANOREQUALTO && - IsLessThan(right_constant.comparison_type))) { + ConstantFilterCombiner::IsUpperBound(right_constant.comparison_type))) { // filters (j >= i AND i [>, >=] 10) OR (j <= i AND i [<, <=] 10) // create filter j [>, >=] 10 and add the filter j [>=, <=] i into the remaining filters info.comparison_type = right_constant.comparison_type; // create filter j [>, >=, <, <=] 10 @@ -1459,9 +1595,9 @@ FilterResult FilterCombiner::AddTransitiveFilters(BoundFunctionExpression &compa is_inserted = true; } } else if ((comparison.GetExpressionType() == ExpressionType::COMPARE_GREATERTHAN && - IsGreaterThan(right_constant.comparison_type)) || + ConstantFilterCombiner::IsLowerBound(right_constant.comparison_type)) || (comparison.GetExpressionType() == ExpressionType::COMPARE_LESSTHAN && - IsLessThan(right_constant.comparison_type))) { + ConstantFilterCombiner::IsUpperBound(right_constant.comparison_type))) { // filters (j > i AND i [>, >=] 10) OR j < i AND i [<, <=] 10 // create filter j [>, <] 10 and add the filter j [>, <] i into the remaining filters // the comparisons j > i and j < i are more restrictive @@ -1478,7 +1614,7 @@ FilterResult FilterCombiner::AddTransitiveFilters(BoundFunctionExpression &compa continue; } // Add the new filer into the left set - if (AddConstantComparison(left_constants, info) == FilterResult::UNSATISFIABLE) { + if (ConstantFilterCombiner::AddComparison(left_constants, info) == FilterResult::UNSATISFIABLE) { return FilterResult::UNSATISFIABLE; } is_successful = true; @@ -1531,148 +1667,4 @@ unique_ptr FilterCombiner::FindTransitiveFilter(const Expression &ex return nullptr; } -static ValueComparisonResult InvertValueComparisonResult(ValueComparisonResult result) { - if (result == ValueComparisonResult::PRUNE_RIGHT) { - return ValueComparisonResult::PRUNE_LEFT; - } - if (result == ValueComparisonResult::PRUNE_LEFT) { - return ValueComparisonResult::PRUNE_RIGHT; - } - return result; -} - -ValueComparisonResult CompareValueInformation(ExpressionValueInformation &left, ExpressionValueInformation &right) { - if (left.comparison_type == ExpressionType::COMPARE_EQUAL) { - // left is COMPARE_EQUAL, we can either - // (1) prune the right side or - // (2) return UNSATISFIABLE - bool prune_right_side = false; - switch (right.comparison_type) { - case ExpressionType::COMPARE_LESSTHAN: - prune_right_side = left.constant < right.constant; - break; - case ExpressionType::COMPARE_LESSTHANOREQUALTO: - prune_right_side = left.constant <= right.constant; - break; - case ExpressionType::COMPARE_GREATERTHAN: - prune_right_side = left.constant > right.constant; - break; - case ExpressionType::COMPARE_GREATERTHANOREQUALTO: - prune_right_side = left.constant >= right.constant; - break; - case ExpressionType::COMPARE_NOTEQUAL: - prune_right_side = left.constant != right.constant; - break; - default: - D_ASSERT(right.comparison_type == ExpressionType::COMPARE_EQUAL); - prune_right_side = left.constant == right.constant; - break; - } - if (prune_right_side) { - return ValueComparisonResult::PRUNE_RIGHT; - } else { - return ValueComparisonResult::UNSATISFIABLE_CONDITION; - } - } else if (right.comparison_type == ExpressionType::COMPARE_EQUAL) { - // right is COMPARE_EQUAL - return InvertValueComparisonResult(CompareValueInformation(right, left)); - } else if (left.comparison_type == ExpressionType::COMPARE_NOTEQUAL) { - // left is COMPARE_NOTEQUAL, we can either - // (1) prune the left side or - // (2) not prune anything - bool prune_left_side = false; - switch (right.comparison_type) { - case ExpressionType::COMPARE_LESSTHAN: - prune_left_side = left.constant >= right.constant; - break; - case ExpressionType::COMPARE_LESSTHANOREQUALTO: - prune_left_side = left.constant > right.constant; - break; - case ExpressionType::COMPARE_GREATERTHAN: - prune_left_side = left.constant <= right.constant; - break; - case ExpressionType::COMPARE_GREATERTHANOREQUALTO: - prune_left_side = left.constant < right.constant; - break; - default: - D_ASSERT(right.comparison_type == ExpressionType::COMPARE_NOTEQUAL); - prune_left_side = left.constant == right.constant; - break; - } - if (prune_left_side) { - return ValueComparisonResult::PRUNE_LEFT; - } else { - return ValueComparisonResult::PRUNE_NOTHING; - } - } else if (right.comparison_type == ExpressionType::COMPARE_NOTEQUAL) { - return InvertValueComparisonResult(CompareValueInformation(right, left)); - } else if (IsGreaterThan(left.comparison_type) && IsGreaterThan(right.comparison_type)) { - // both comparisons are [>], we can either - // (1) prune the left side or - // (2) prune the right side - if (left.constant > right.constant) { - // left constant is more selective, prune right - return ValueComparisonResult::PRUNE_RIGHT; - } else if (left.constant < right.constant) { - // right constant is more selective, prune left - return ValueComparisonResult::PRUNE_LEFT; - } else { - // constants are equivalent - // however we can still have the scenario where one is [>=] and the other is [>] - // we want to prune the [>=] because [>] is more selective - // if left is [>=] we prune the left, else we prune the right - if (left.comparison_type == ExpressionType::COMPARE_GREATERTHANOREQUALTO) { - return ValueComparisonResult::PRUNE_LEFT; - } else { - return ValueComparisonResult::PRUNE_RIGHT; - } - } - } else if (IsLessThan(left.comparison_type) && IsLessThan(right.comparison_type)) { - // both comparisons are [<], we can either - // (1) prune the left side or - // (2) prune the right side - if (left.constant < right.constant) { - // left constant is more selective, prune right - return ValueComparisonResult::PRUNE_RIGHT; - } else if (left.constant > right.constant) { - // right constant is more selective, prune left - return ValueComparisonResult::PRUNE_LEFT; - } else { - // constants are equivalent - // however we can still have the scenario where one is [<=] and the other is [<] - // we want to prune the [<=] because [<] is more selective - // if left is [<=] we prune the left, else we prune the right - if (left.comparison_type == ExpressionType::COMPARE_LESSTHANOREQUALTO) { - return ValueComparisonResult::PRUNE_LEFT; - } else { - return ValueComparisonResult::PRUNE_RIGHT; - } - } - } else if (IsLessThan(left.comparison_type)) { - D_ASSERT(IsGreaterThan(right.comparison_type)); - // left is [<] and right is [>], in this case we can either - // (1) prune nothing or - // (2) return UNSATISFIABLE - // the SMALLER THAN constant has to be greater than the BIGGER THAN constant - if (left.constant > right.constant) { - return ValueComparisonResult::PRUNE_NOTHING; - } else if (left.constant < right.constant) { - return ValueComparisonResult::UNSATISFIABLE_CONDITION; - } else { - // the constants are equal - // This is only satisfiable if both bounds are inclusive - if (left.comparison_type == ExpressionType::COMPARE_LESSTHANOREQUALTO && - right.comparison_type == ExpressionType::COMPARE_GREATERTHANOREQUALTO) { - return ValueComparisonResult::PRUNE_NOTHING; - } else { - return ValueComparisonResult::UNSATISFIABLE_CONDITION; - } - } - } else { - // left is [>] and right is [<] or [!=] - D_ASSERT(IsLessThan(right.comparison_type) && IsGreaterThan(left.comparison_type)); - return InvertValueComparisonResult(CompareValueInformation(right, left)); - } -} - } // namespace duckdb diff --git a/src/duckdb/src/optimizer/filter_pullup.cpp b/src/duckdb/src/optimizer/filter_pullup.cpp index 374eef567..b53874fcd 100644 --- a/src/duckdb/src/optimizer/filter_pullup.cpp +++ b/src/duckdb/src/optimizer/filter_pullup.cpp @@ -1,17 +1,82 @@ #include "duckdb/optimizer/filter_pullup.hpp" #include "duckdb/common/enum_util.hpp" -#include "duckdb/optimizer/filter_pushdown.hpp" +#include "duckdb/optimizer/filter_combiner.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/operator/logical_any_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cross_product.hpp" #include "duckdb/planner/operator/logical_join.hpp" -#include "duckdb/planner/operator/logical_window.hpp" +#include "duckdb/planner/subquery/column_binding_layout.hpp" namespace duckdb { +static bool HasComputedJoinOperands(const Expression &lhs, const Expression &rhs) { + return !lhs.IsScalar() && !rhs.IsScalar() && + (lhs.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF || + rhs.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF); +} + +static bool NeedsEarlyJoinKeys(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &join = op.Cast(); + if (join.join_type != JoinType::INNER) { + return false; + } + for (auto &condition : join.conditions) { + if (condition.IsComparison() && condition.GetComparisonType() == ExpressionType::COMPARE_EQUAL && + HasComputedJoinOperands(condition.GetLHS(), condition.GetRHS())) { + return true; + } + } + return false; + } + if (op.type != LogicalOperatorType::LOGICAL_FILTER || + op.children[0]->type != LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + return false; + } + auto &cross = *op.children[0]; + unordered_set left_bindings, right_bindings; + for (auto &expression : op.expressions) { + if (expression->GetExpressionType() != ExpressionType::COMPARE_EQUAL) { + continue; + } + auto &comparison = expression->Cast(); + auto &lhs = BoundComparisonExpression::Left(comparison); + auto &rhs = BoundComparisonExpression::Right(comparison); + if (!HasComputedJoinOperands(lhs, rhs)) { + continue; + } + if (left_bindings.empty() && right_bindings.empty()) { + LogicalJoin::GetTableReferences(*cross.children[0], left_bindings); + LogicalJoin::GetTableReferences(*cross.children[1], right_bindings); + } + auto lhs_side = JoinSide::GetCurrentJoinSide(lhs, left_bindings, right_bindings); + auto rhs_side = JoinSide::GetCurrentJoinSide(rhs, left_bindings, right_bindings); + if ((lhs_side == JoinSide::LEFT && rhs_side == JoinSide::RIGHT) || + (lhs_side == JoinSide::RIGHT && rhs_side == JoinSide::LEFT)) { + return true; + } + } + return false; +} + unique_ptr FilterPullup::Rewrite(unique_ptr op) { + if (op->HasProjectionMap()) { + return FinishPullup(std::move(op)); + } + if (!can_pullup && !can_add_column && NeedsEarlyJoinKeys(*op)) { + // Carry hidden keys within this join region and keep its output bindings unchanged. + auto output = op->GetColumnBindings(); + FilterPullup join_pullup(context, false, true); + auto rewritten = join_pullup.Rewrite(std::move(op)); + ColumnBindingLayout layout(rewritten->GetColumnBindings()); + if (layout.HasSameLayout(output)) { + return rewritten; + } + return LogicalJoin::PromoteJoinSide(std::move(rewritten), layout.CreateProjectionMap(output)); + } switch (op->type) { case LogicalOperatorType::LOGICAL_FILTER: return PullupFilter(std::move(op)); @@ -27,6 +92,10 @@ unique_ptr FilterPullup::Rewrite(unique_ptr op case LogicalOperatorType::LOGICAL_INTERSECT: case LogicalOperatorType::LOGICAL_EXCEPT: return PullupSetOperation(std::move(op)); + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + return PullupAggregate(std::move(op)); + case LogicalOperatorType::LOGICAL_UNION: + return PullupUnion(std::move(op)); case LogicalOperatorType::LOGICAL_WINDOW: return PullupWindow(std::move(op)); case LogicalOperatorType::LOGICAL_ORDER_BY: { @@ -44,6 +113,21 @@ unique_ptr FilterPullup::PullupJoin(unique_ptr op->type == LogicalOperatorType::LOGICAL_ASOF_JOIN || op->type == LogicalOperatorType::LOGICAL_ANY_JOIN || op->type == LogicalOperatorType::LOGICAL_DELIM_JOIN); auto &join = op->Cast(); + if (op->type == LogicalOperatorType::LOGICAL_ANY_JOIN) { + if (op->Cast().condition->IsVolatile()) { + return FinishPullup(std::move(op)); + } + } else { + for (auto &condition : op->Cast().conditions) { + if (condition.IsComparison() ? condition.GetLHS().IsVolatile() || condition.GetRHS().IsVolatile() + : condition.GetJoinExpression().IsVolatile()) { + return FinishPullup(std::move(op)); + } + } + } + if (can_add_column && (join.join_type != JoinType::INNER || op->type == LogicalOperatorType::LOGICAL_ASOF_JOIN)) { + return FinishPullup(std::move(op)); + } switch (join.join_type) { case JoinType::INNER: @@ -87,10 +171,14 @@ unique_ptr FilterPullup::PullupSemiJoin(unique_ptr left_filter) { left_filters.push_back(std::move(left_filter)); }); op->children[1] = GeneratePullupFilter(std::move(op->children[1]), right_pullup.filters_expr_pullup); } - if (left_filters.empty()) { - return op; + vector> constraints; + for (auto &filter : left_filters) { + if (FilterCombiner::CanCopyFilter(*filter)) { + constraints.push_back(filter->Copy()); + } } - return GeneratePullupFilter(std::move(op), left_filters); + op->children[0] = GeneratePullupFilter(std::move(op->children[0]), left_filters); + return ReturnConstraints(std::move(op), std::move(constraints)); } unique_ptr FilterPullup::PullupInnerJoin(unique_ptr op) { @@ -146,41 +234,12 @@ unique_ptr FilterPullup::PullupCrossProduct(unique_ptr FilterPullup::PullupWindow(unique_ptr op) { - if (!can_pullup) { - return FinishPullup(std::move(op)); - } - // above the window, the window expressions also run for the partitions the filters remove - auto &window = op->Cast(); - if (!FilterPushdown::OnlyRanksWithoutArguments(window)) { - return FinishPullup(std::move(op)); - } - const auto pulled_before_child = filters_expr_pullup.size(); - op->children[0] = Rewrite(std::move(op->children[0])); - - // a filter that compares the partitions with constants keeps or removes whole partitions - // a filter that stays below the window and can throw keeps the filters that guard it there - bool keep_all = false; - for (idx_t i = pulled_before_child; i < filters_expr_pullup.size(); i++) { - keep_all = keep_all || (filters_expr_pullup[i]->CanThrow() && - !FilterPushdown::ComparesWindowPartitions(window, *filters_expr_pullup[i])); - } - vector> kept_filters; - for (idx_t i = pulled_before_child; i < filters_expr_pullup.size(); i++) { - if (keep_all || !FilterPushdown::ComparesWindowPartitions(window, *filters_expr_pullup[i])) { - kept_filters.push_back(std::move(filters_expr_pullup[i])); - filters_expr_pullup.erase_at(i); - i--; - } - } - if (!kept_filters.empty()) { - op->children[0] = GeneratePullupFilter(std::move(op->children[0]), kept_filters); - } - return op; -} - unique_ptr FilterPullup::GeneratePullupFilter(unique_ptr child, vector> &expressions) { + if (expressions.empty()) { + return child; + } + FilterCombiner::DeduplicateFilters(expressions); unique_ptr filter = make_uniq(); for (idx_t i = 0; i < expressions.size(); ++i) { filter->expressions.push_back(std::move(expressions[i])); diff --git a/src/duckdb/src/optimizer/filter_pushdown.cpp b/src/duckdb/src/optimizer/filter_pushdown.cpp index f89dc4816..fb0cc1ca1 100644 --- a/src/duckdb/src/optimizer/filter_pushdown.cpp +++ b/src/duckdb/src/optimizer/filter_pushdown.cpp @@ -1,6 +1,7 @@ #include "duckdb/optimizer/filter_pushdown.hpp" #include "duckdb/optimizer/filter_combiner.hpp" #include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/planner/operator/logical_any_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_join.hpp" @@ -108,6 +109,20 @@ unique_ptr FilterPushdown::PushdownJoin(unique_ptrtype == LogicalOperatorType::LOGICAL_DELIM_JOIN); auto &join = op->Cast(); + // Filters must not change the rows seen by volatile join conditions. + if (op->type == LogicalOperatorType::LOGICAL_ANY_JOIN) { + if (op->Cast().condition->IsVolatile()) { + return FinishPushdown(std::move(op)); + } + } else { + for (auto &condition : op->Cast().conditions) { + if (condition.IsComparison() ? condition.GetLHS().IsVolatile() || condition.GetRHS().IsVolatile() + : condition.GetJoinExpression().IsVolatile()) { + return FinishPushdown(std::move(op)); + } + } + } + unordered_set left_bindings, right_bindings; LogicalJoin::GetTableReferences(*op->children[0], left_bindings); LogicalJoin::GetTableReferences(*op->children[1], right_bindings); diff --git a/src/duckdb/src/optimizer/in_clause_rewriter.cpp b/src/duckdb/src/optimizer/in_clause_rewriter.cpp index 557c1f82b..fc40a4143 100644 --- a/src/duckdb/src/optimizer/in_clause_rewriter.cpp +++ b/src/duckdb/src/optimizer/in_clause_rewriter.cpp @@ -18,7 +18,7 @@ bool InClauseRewriter::HasRewritableInClause(const Expression &expr) { (expr.GetExpressionType() == ExpressionType::COMPARE_IN || expr.GetExpressionType() == ExpressionType::COMPARE_NOT_IN)) { auto &op = expr.Cast(); - if (op.GetChildren().size() >= InClauseRewriter::IN_CLAUSE_REWRITE_THRESHOLD) { + if (op.GetChildren().size() >= IN_CLAUSE_REWRITE_THRESHOLD) { bool all_foldable = true; for (idx_t child_idx = 1; child_idx < op.GetChildren().size(); child_idx++) { if (!op.GetChildren()[child_idx]->IsFoldable()) { diff --git a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp index 07759139e..d8fb43835 100644 --- a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp +++ b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp @@ -8,6 +8,7 @@ #include "duckdb/function/builtin_function_lookup.hpp" #include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/function/scalar/struct_utils.hpp" +#include "duckdb/optimizer/filter_combiner.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" @@ -17,6 +18,7 @@ #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/filter/table_filter_functions.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_any_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" @@ -197,13 +199,106 @@ bool JoinFilterPushdownUtil::JoinTypeIsSupported(JoinType join_type) { } } -static void PushdownProjectionColumns(LogicalProjection &proj, const vector &columns, - vector &projected_columns) { +struct FilterColumnHash { + static hash_t HashWithBinding(const JoinFilterPushdownColumn &column, ColumnBinding binding) { + auto result = CombineHash(Hash(column.join_filter_idx), ColumnBindingHashFunction()(binding)); + result = CombineHash(result, column.storage_type.Hash()); + result = CombineHash(result, Hash(uint8_t(column.mode))); + if (column.input_expression) { + result = CombineHash(result, column.input_expression->Hash()); + } + return result; + } + + hash_t operator()(const JoinFilterPushdownColumn &column) const { + return HashWithBinding(column, column.probe_column_index); + } +}; + +struct FilterColumnEquality { + static bool EqualsIgnoringBinding(const JoinFilterPushdownColumn &a, const JoinFilterPushdownColumn &b) { + if (a.join_filter_idx != b.join_filter_idx || a.storage_type != b.storage_type || a.mode != b.mode || + bool(a.input_expression) != bool(b.input_expression)) { + return false; + } + return !a.input_expression || a.input_expression->Equals(*b.input_expression); + } + + bool operator()(const JoinFilterPushdownColumn &a, const JoinFilterPushdownColumn &b) const { + return a.probe_column_index == b.probe_column_index && EqualsIgnoringBinding(a, b); + } +}; + +using filter_column_set_t = unordered_set; +using filter_equality_graph_t = column_binding_map_t>; + +enum class FilterTargetMode : uint8_t { SCANS, SCANS_AND_CTE_REFERENCES }; + +class FilterTargetFinder { +public: + explicit FilterTargetFinder(FilterTargetMode mode, + EqualityPropagation equality_propagation = EqualityPropagation::DISABLED, + bool cross_secure_views = false) + : mode(mode), equality_propagation(equality_propagation), cross_secure_views(cross_secure_views) { + } + + void Find(LogicalOperator &op, const vector &columns, vector &targets) { + FindTargets(op, FilterColumns(columns), targets); + } + +private: + //! Borrowed for synchronous traversal; remapped columns start without an expansion region. + struct FilterColumns { + explicit FilterColumns(const vector &columns, + optional_ptr expanded_for = nullptr) + : columns(columns), expanded_for(expanded_for) { + } + + const vector &columns; + const optional_ptr expanded_for; + }; + + void FindTargets(LogicalOperator &op, const FilterColumns &state, vector &targets); + void FindJoinFilterTargets(LogicalOperator &op, const FilterColumns &state, vector &targets); + void FindSetOperationFilterTargets(LogicalSetOperation &setop, const vector &columns, + vector &targets); + void FindWindowFilterTargets(LogicalWindow &window, const vector &columns, + vector &targets); + static void FindScanFilterTargets(LogicalGet &get, const vector &columns, + vector &targets); + static void PushdownProjectionColumns(LogicalProjection &proj, const vector &columns, + vector &projected_columns); + static void PushdownAggregateColumns(LogicalAggregate &aggr, const vector &columns, + vector &group_columns); + static vector + ExpandEquivalentFilterColumns(const filter_equality_graph_t &equalities, + const vector &columns); + static void AddFilterEquality(filter_equality_graph_t &equalities, ColumnBinding lhs, ColumnBinding rhs); + static void CollectJoinFilterEqualities(const LogicalComparisonJoin &join, filter_equality_graph_t &equalities); + static bool OperatorHasVolatileExpressions(const LogicalOperator &op); + static bool FilterTargetPreservesLeftInput(JoinType type); + + const filter_equality_graph_t &GetEqualities(const LogicalOperator &op); + void CollectEqualities(const LogicalOperator &op, const shared_ptr &graph); + bool CanSkipSubtree(const LogicalOperator &op); + bool CanSkipSubtreeInternal(const LogicalOperator &op); + +private: + const FilterTargetMode mode; + const EqualityPropagation equality_propagation; + const bool cross_secure_views; + reference_map_t skippable_subtrees; + reference_map_t> equality_graphs; +}; + +void FilterTargetFinder::PushdownProjectionColumns(LogicalProjection &proj, + const vector &columns, + vector &projected_columns) { for (auto &filter : columns) { if (filter.probe_column_index.table_index != proj.table_index) { continue; } - auto candidate = filter; + auto candidate = filter.Copy(); auto &expr = proj.GetExpression(candidate.probe_column_index); if (!JoinFilterPushdownUtil::PushdownJoinFilterExpression(expr, candidate)) { continue; @@ -212,8 +307,9 @@ static void PushdownProjectionColumns(LogicalProjection &proj, const vector &columns, - vector &group_columns) { +void FilterTargetFinder::PushdownAggregateColumns(LogicalAggregate &aggr, + const vector &columns, + vector &group_columns) { for (auto &filter : columns) { if (filter.probe_column_index.table_index != aggr.group_index) { continue; @@ -226,7 +322,7 @@ static void PushdownAggregateColumns(LogicalAggregate &aggr, const vectorHash()); - } - return result; - } -}; - -struct FilterColumnEquality { - bool operator()(const JoinFilterPushdownColumn &a, const JoinFilterPushdownColumn &b) const { - if (a.join_filter_idx != b.join_filter_idx || a.probe_column_index != b.probe_column_index || - a.storage_type != b.storage_type || a.mode != b.mode || - bool(a.input_expression) != bool(b.input_expression)) { - return false; - } - return !a.input_expression || a.input_expression->Equals(*b.input_expression); - } -}; - -using filter_column_set_t = unordered_set; -using filter_equality_graph_t = column_binding_map_t>; - -static void AddFilterEquality(filter_equality_graph_t &equalities, ColumnBinding lhs, ColumnBinding rhs) { +void FilterTargetFinder::AddFilterEquality(filter_equality_graph_t &equalities, ColumnBinding lhs, ColumnBinding rhs) { equalities[lhs].push_back(rhs); equalities[rhs].push_back(lhs); } -static void CollectJoinFilterEqualities(const LogicalComparisonJoin &join, filter_equality_graph_t &equalities) { +void FilterTargetFinder::CollectJoinFilterEqualities(const LogicalComparisonJoin &join, + filter_equality_graph_t &equalities) { for (auto &condition : join.conditions) { if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL || condition.GetLHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || @@ -281,24 +352,25 @@ static void CollectJoinFilterEqualities(const LogicalComparisonJoin &join, filte } } -static void FindScanFilterTargets(LogicalGet &get, vector columns, - vector &targets) { +void FilterTargetFinder::FindScanFilterTargets(LogicalGet &get, const vector &columns, + vector &targets) { if (!get.function.filter_pushdown || get.ordinality_idx.IsValid() || get.extra_info.sample_options) { return; } const auto bindings = get.GetColumnBindings(); vector accepted_columns; filter_column_set_t seen; - for (auto &filter : columns) { - if (filter.probe_column_index.table_index != get.table_index) { + for (auto &input_filter : columns) { + if (input_filter.probe_column_index.table_index != get.table_index) { continue; } if (get.function.supports_pushdown_type) { - auto column_id = get.GetColumnIndex(filter.probe_column_index).GetPrimaryIndex(); + auto column_id = get.GetColumnIndex(input_filter.probe_column_index).GetPrimaryIndex(); if (!get.function.supports_pushdown_type(*get.bind_data, column_id)) { continue; } } + auto filter = input_filter.Copy(); for (idx_t i = 0; i < bindings.size(); i++) { if (filter.probe_column_index.column_index == bindings[i].column_index) { filter.storage_type = get.GetColumnType(get.GetColumnIndex(bindings[i])); @@ -315,8 +387,9 @@ static void FindScanFilterTargets(LogicalGet &get, vectorCopy()); } } if (!accepted_columns.empty()) { @@ -324,96 +397,16 @@ static void FindScanFilterTargets(LogicalGet &get, vector *expr) { result |= (*expr)->IsVolatile(); }); return result; } -class FilterTargetContext { -public: - explicit FilterTargetContext(EqualityPropagation equality_propagation, bool cross_secure_views = false) - : equality_propagation(equality_propagation), cross_secure_views(cross_secure_views) { - } - - EqualityPropagation equality_propagation; - bool cross_secure_views; - bool include_cte_references = false; - -public: - const filter_equality_graph_t &GetEqualities(const LogicalOperator &op) { - auto entry = equality_graphs.find(op); - if (entry != equality_graphs.end()) { - return *entry->second; - } - auto graph = make_shared_ptr(); - CollectEqualities(op, graph); - return *graph; - } - - bool CanSkipSubtree(const LogicalOperator &op) { - auto entry = skippable_subtrees.find(op); - if (entry != skippable_subtrees.end()) { - return entry->second; - } - const auto result = CanSkipSubtreeInternal(op); - skippable_subtrees.emplace(op, result); - return result; - } - -private: - bool CanSkipSubtreeInternal(const LogicalOperator &op); - - void CollectEqualities(const LogicalOperator &op, const shared_ptr &graph) { - switch (op.type) { - case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { - auto &join = op.Cast(); - if (join.join_type != JoinType::INNER) { - return; - } - CollectJoinFilterEqualities(join, *graph); - break; - } - case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: - break; - case LogicalOperatorType::LOGICAL_PROJECTION: { - auto &projection = op.Cast(); - for (idx_t i = 0; i < projection.expressions.size(); i++) { - auto &expr = *projection.expressions[i]; - if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - continue; - } - auto &column = expr.Cast(); - if (column.Depth() == 0) { - AddFilterEquality(*graph, ColumnBinding(projection.table_index, ProjectionIndex(i)), - column.Binding()); - } - } - break; - } - default: - return; - } - equality_graphs.emplace(op, graph); - for (auto &child : op.children) { - CollectEqualities(*child, graph); - } - } - -private: - reference_map_t skippable_subtrees; - reference_map_t> equality_graphs; -}; - -enum class FilterColumnExpansion { REQUIRED, COMPLETE }; - -static void FindFilterTargets(LogicalOperator &op, vector columns, - vector &targets, FilterTargetContext &context, - FilterColumnExpansion expansion = FilterColumnExpansion::REQUIRED); - -static void FindSetOperationFilterTargets(LogicalSetOperation &setop, const vector &columns, - vector &targets, FilterTargetContext &context) { +void FilterTargetFinder::FindSetOperationFilterTargets(LogicalSetOperation &setop, + const vector &columns, + vector &targets) { for (auto &child : setop.children) { vector child_columns; const auto child_bindings = child->GetColumnBindings(); @@ -421,18 +414,18 @@ static void FindSetOperationFilterTargets(LogicalSetOperation &setop, const vect if (filter.probe_column_index.table_index != setop.table_index) { continue; } - auto candidate = filter; + auto candidate = filter.Copy(); candidate.probe_column_index = child_bindings[filter.probe_column_index.column_index]; child_columns.push_back(std::move(candidate)); } - FindFilterTargets(*child, std::move(child_columns), targets, context); + FindTargets(*child, FilterColumns(child_columns), targets); if (setop.type == LogicalOperatorType::LOGICAL_EXCEPT) { break; } } } -static bool FilterTargetPreservesLeftInput(JoinType type) { +bool FilterTargetFinder::FilterTargetPreservesLeftInput(JoinType type) { switch (type) { case JoinType::INNER: case JoinType::LEFT: @@ -447,7 +440,63 @@ static bool FilterTargetPreservesLeftInput(JoinType type) { } } -bool FilterTargetContext::CanSkipSubtreeInternal(const LogicalOperator &op) { +const filter_equality_graph_t &FilterTargetFinder::GetEqualities(const LogicalOperator &op) { + auto entry = equality_graphs.find(op); + if (entry != equality_graphs.end()) { + return *entry->second; + } + auto graph = make_shared_ptr(); + CollectEqualities(op, graph); + return *graph; +} + +bool FilterTargetFinder::CanSkipSubtree(const LogicalOperator &op) { + auto entry = skippable_subtrees.find(op); + if (entry != skippable_subtrees.end()) { + return entry->second; + } + const auto result = CanSkipSubtreeInternal(op); + skippable_subtrees.emplace(op, result); + return result; +} + +void FilterTargetFinder::CollectEqualities(const LogicalOperator &op, + const shared_ptr &graph) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { + auto &join = op.Cast(); + if (join.join_type != JoinType::INNER) { + return; + } + CollectJoinFilterEqualities(join, *graph); + break; + } + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + break; + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &projection = op.Cast(); + for (idx_t i = 0; i < projection.expressions.size(); i++) { + auto &expr = *projection.expressions[i]; + if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + continue; + } + auto &column = expr.Cast(); + if (column.Depth() == 0) { + AddFilterEquality(*graph, ColumnBinding(projection.table_index, ProjectionIndex(i)), column.Binding()); + } + } + break; + } + default: + return; + } + equality_graphs.emplace(op, graph); + for (auto &child : op.children) { + CollectEqualities(*child, graph); + } +} + +bool FilterTargetFinder::CanSkipSubtreeInternal(const LogicalOperator &op) { switch (op.type) { case LogicalOperatorType::LOGICAL_INSERT: case LogicalOperatorType::LOGICAL_UPDATE: @@ -471,37 +520,62 @@ bool FilterTargetContext::CanSkipSubtreeInternal(const LogicalOperator &op) { return true; } -static vector ExpandEquivalentFilterColumns(const filter_equality_graph_t &equalities, - vector columns) { - if (equalities.empty()) { - return columns; - } - vector result; - filter_column_set_t seen; +// The traversal borrows only from its immutable input columns, never from the growing worklist. +// Copies become owned filter columns only after equality expansion has finished. +struct EquivalentFilterColumn { + reference source; + ColumnBinding binding; + + struct Hash { + hash_t operator()(const EquivalentFilterColumn &column) const { + return FilterColumnHash::HashWithBinding(column.source.get(), column.binding); + } + }; + struct Equality { + bool operator()(const EquivalentFilterColumn &a, const EquivalentFilterColumn &b) const { + return a.binding == b.binding && + FilterColumnEquality::EqualsIgnoringBinding(a.source.get(), b.source.get()); + } + }; +}; + +vector +FilterTargetFinder::ExpandEquivalentFilterColumns(const filter_equality_graph_t &equalities, + const vector &columns) { + D_ASSERT(!equalities.empty()); + vector pending; + unordered_set seen; for (auto &column : columns) { - if (seen.insert(column).second) { - result.push_back(std::move(column)); + EquivalentFilterColumn initial {column, column.probe_column_index}; + if (seen.insert(initial).second) { + pending.push_back(initial); } } - for (idx_t i = 0; i < result.size(); i++) { - auto entry = equalities.find(result[i].probe_column_index); + for (idx_t i = 0; i < pending.size(); i++) { + auto entry = equalities.find(pending[i].binding); if (entry == equalities.end()) { continue; } for (auto &binding : entry->second) { - auto inferred = result[i]; - inferred.probe_column_index = binding; + auto inferred = pending[i]; + inferred.binding = binding; if (seen.insert(inferred).second) { - result.push_back(std::move(inferred)); + pending.push_back(inferred); } } } + vector result; + result.reserve(pending.size()); + for (auto &column : pending) { + auto inferred = column.source.get().Copy(); + inferred.probe_column_index = column.binding; + result.push_back(std::move(inferred)); + } return result; } -static void FindJoinFilterTargets(LogicalOperator &op, vector columns, - vector &targets, FilterTargetContext &context, - FilterColumnExpansion expansion) { +void FilterTargetFinder::FindJoinFilterTargets(LogicalOperator &op, const FilterColumns &state, + vector &targets) { if (OperatorHasVolatileExpressions(op)) { return; } @@ -510,28 +584,33 @@ static void FindJoinFilterTargets(LogicalOperator &op, vector().join_type)) { return; } - const auto propagate = inner && context.equality_propagation == EqualityPropagation::ENABLED; - if (propagate && expansion == FilterColumnExpansion::REQUIRED) { - columns = ExpandEquivalentFilterColumns(context.GetEqualities(op), std::move(columns)); + optional_ptr equalities; + if (inner && equality_propagation == EqualityPropagation::ENABLED) { + equalities = GetEqualities(op); } - // Unchanged columns already carry the region's closure; remapping operators expand their new states. - const auto child_expansion = propagate ? FilterColumnExpansion::COMPLETE : FilterColumnExpansion::REQUIRED; - FindFilterTargets(*op.children[0], columns, targets, context, child_expansion); + const auto needs_expansion = equalities && state.expanded_for.get() != equalities.get() && !equalities->empty(); + vector expanded_columns; + if (needs_expansion) { + expanded_columns = ExpandEquivalentFilterColumns(*equalities, state.columns); + } + // Remapping creates fresh state; unchanged columns share their expansion within the same equality region. + const FilterColumns child_state(needs_expansion ? expanded_columns : state.columns, equalities); + FindTargets(*op.children[0], child_state, targets); if (!inner) { return; } vector right_targets; - FindFilterTargets(*op.children[1], std::move(columns), right_targets, context, child_expansion); + FindTargets(*op.children[1], child_state, right_targets); // An empty build can skip the probe input, including expressions outside the filtered branch. - if (!right_targets.empty() && context.CanSkipSubtree(*op.children[0])) { + if (!right_targets.empty() && CanSkipSubtree(*op.children[0])) { for (auto &target : right_targets) { targets.push_back(std::move(target)); } } } -static void FindWindowFilterTargets(LogicalWindow &window, vector columns, - vector &targets, FilterTargetContext &context) { +void FilterTargetFinder::FindWindowFilterTargets(LogicalWindow &window, const vector &columns, + vector &targets) { vector partition_columns; for (auto &filter : columns) { bool shared_partition = filter.probe_column_index.table_index != window.window_index; @@ -547,24 +626,23 @@ static void FindWindowFilterTargets(LogicalWindow &window, vector columns, - vector &targets, FilterTargetContext &context, - FilterColumnExpansion expansion) { +void FilterTargetFinder::FindTargets(LogicalOperator &op, const FilterColumns &state, vector &targets) { + const auto &columns = state.columns; if (columns.empty() || OperatorHasVolatileExpressions(op)) { return; } switch (op.type) { case LogicalOperatorType::LOGICAL_GET: - FindScanFilterTargets(op.Cast(), std::move(columns), targets); + FindScanFilterTargets(op.Cast(), columns, targets); break; case LogicalOperatorType::LOGICAL_CTE_REF: { - if (!context.include_cte_references) { + if (mode != FilterTargetMode::SCANS_AND_CTE_REFERENCES) { break; } auto &ref = op.Cast(); @@ -572,12 +650,13 @@ static void FindFilterTargets(LogicalOperator &op, vector accepted; - for (auto &column : columns) { - if (column.probe_column_index.table_index != ref.table_index || - !column.probe_column_index.column_index.IsValid() || - column.probe_column_index.column_index.GetIndex() >= ref.chunk_types.size()) { + for (auto &input_column : columns) { + if (input_column.probe_column_index.table_index != ref.table_index || + !input_column.probe_column_index.column_index.IsValid() || + input_column.probe_column_index.column_index.GetIndex() >= ref.chunk_types.size()) { continue; } + auto column = input_column.Copy(); column.storage_type = ref.chunk_types[column.probe_column_index.column_index.GetIndex()]; if (column.storage_type.id() == LogicalTypeId::VARIANT && RuntimeFilterCastUtil::GetRuntimeFilterInputType(column, column.storage_type).id() == @@ -595,13 +674,13 @@ static void FindFilterTargets(LogicalOperator &op, vector projected_columns; PushdownProjectionColumns(op.Cast(), columns, projected_columns); - FindFilterTargets(*op.children[0], std::move(projected_columns), targets, context); + FindTargets(*op.children[0], FilterColumns(projected_columns), targets); break; } case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { vector group_columns; PushdownAggregateColumns(op.Cast(), columns, group_columns); - FindFilterTargets(*op.children[0], std::move(group_columns), targets, context); + FindTargets(*op.children[0], FilterColumns(group_columns), targets); break; } case LogicalOperatorType::LOGICAL_ANY_JOIN: { @@ -610,48 +689,48 @@ static void FindFilterTargets(LogicalOperator &op, vectorIsVolatile()) { break; } - FindFilterTargets(*join.children[0], std::move(columns), targets, context); + FindTargets(*join.children[0], state, targets); break; } case LogicalOperatorType::LOGICAL_UNNEST: { vector input_columns; for (auto &filter : columns) { if (filter.probe_column_index.table_index != op.Cast().unnest_index) { - input_columns.push_back(std::move(filter)); + input_columns.push_back(filter.Copy()); } } - FindFilterTargets(*op.children[0], std::move(input_columns), targets, context); + FindTargets(*op.children[0], FilterColumns(input_columns), targets); break; } case LogicalOperatorType::LOGICAL_EXCEPT: case LogicalOperatorType::LOGICAL_INTERSECT: case LogicalOperatorType::LOGICAL_UNION: - FindSetOperationFilterTargets(op.Cast(), columns, targets, context); + FindSetOperationFilterTargets(op.Cast(), columns, targets); break; case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: - FindJoinFilterTargets(op, std::move(columns), targets, context, expansion); + FindJoinFilterTargets(op, state, targets); break; case LogicalOperatorType::LOGICAL_WINDOW: - FindWindowFilterTargets(op.Cast(), std::move(columns), targets, context); + FindWindowFilterTargets(op.Cast(), columns, targets); break; case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: - if (context.CanSkipSubtree(*op.children[0])) { - FindFilterTargets(*op.children[1], std::move(columns), targets, context); + if (CanSkipSubtree(*op.children[0])) { + FindTargets(*op.children[1], state, targets); } break; case LogicalOperatorType::LOGICAL_ORDER_BY: case LogicalOperatorType::LOGICAL_FILTER: - FindFilterTargets(*op.children[0], std::move(columns), targets, context); + FindTargets(*op.children[0], state, targets); break; case LogicalOperatorType::LOGICAL_SECURE_VIEW: - if (!context.cross_secure_views) { + if (!cross_secure_views) { break; } // a join filter enters the view as a pushed WHERE filter would, and needs no barrier: it cannot fail, as a cast // that can fail is a TRY_CAST that keeps the rows it cannot convert for the join // (PreserveRuntimeFilterCastErrors) - FindFilterTargets(*op.children[0], std::move(columns), targets, context); + FindTargets(*op.children[0], state, targets); break; default: break; @@ -659,25 +738,24 @@ static void FindFilterTargets(LogicalOperator &op, vector columns, + const vector &columns, vector &targets, EqualityPropagation equality_propagation, bool cross_secure_views) { - FilterTargetContext context(equality_propagation, cross_secure_views); + FilterTargetFinder finder(FilterTargetMode::SCANS, equality_propagation, cross_secure_views); vector result; - FindFilterTargets(op, std::move(columns), result, context); + finder.Find(op, columns, result); for (auto &target : result) { targets.emplace_back(target.op.Cast(), std::move(target.columns)); } } void JoinFilterPushdownOptimizer::GetCTEFilterTargets( - LogicalOperator &op, vector columns, + LogicalOperator &op, const vector &columns, reference_map_t> &targets) { - FilterTargetContext context(EqualityPropagation::DISABLED); - context.include_cte_references = true; + FilterTargetFinder finder(FilterTargetMode::SCANS_AND_CTE_REFERENCES); vector result; - FindFilterTargets(op, std::move(columns), result, context); + finder.Find(op, columns, result); for (auto &target : result) { if (target.op.type != LogicalOperatorType::LOGICAL_CTE_REF) { continue; @@ -761,10 +839,90 @@ bool JoinFilterPushdownOptimizer::CanGenerateJoinFilters(const LogicalComparison return true; } +static bool CanAdaptScanFilters(const LogicalGet &get) { + return get.children.empty() && !get.has_pushed_projection && !get.ordinality_idx.IsValid() && + !get.table_filters.HasMultiColumnFilters(); +} + +static bool IsScanKeyConstraint(const LogicalGet &get, ProjectionIndex column_index, const TableFilter &filter) { + if (filter.filter_type != TableFilterType::EXPRESSION_FILTER) { + return false; + } + auto &expression = filter.Cast(); + if (!expression.column_indexes.empty()) { + return false; + } + auto &column = get.GetColumnIds()[column_index]; + if (column.IsVirtualColumn() || column.HasChildren() || column.IsPushdownExtract()) { + return false; + } + auto &type = get.GetColumnType(column); + if (!type.EqualValuesAreIdentical()) { + return false; + } + BoundReferenceExpression key(type, idx_t(0)); + return FilterCombiner::CanMatchExpression(*expression.expr) && + FilterCombiner::IsKeyConstraint(*expression.expr, {key}); +} + +static void MakeRedundantProbeFiltersAdaptive(LogicalComparisonJoin &join) { + if (join.join_type != JoinType::INNER || join.children[0]->type != LogicalOperatorType::LOGICAL_GET || + join.children[1]->type != LogicalOperatorType::LOGICAL_GET || !join.expressions.empty()) { + return; + } + auto &probe = join.children[0]->Cast(); + auto &build = join.children[1]->Cast(); + if (!CanAdaptScanFilters(probe) || !CanAdaptScanFilters(build) || !probe.table_filters.HasFilters() || + !build.table_filters.HasFilters()) { + return; + } + // Computed conditions may have been simplified using the probe filter's statistics. + for (auto &condition : join.conditions) { + if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL || + condition.GetLHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + condition.GetRHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + condition.GetLHS().GetReturnType() != condition.GetRHS().GetReturnType()) { + return; + } + } + // Pausing a probe filter must not expose unsafe scan expressions to additional rows. + for (auto &entry : probe.table_filters) { + if (!IsScanKeyConstraint(probe, entry.GetIndex(), entry.Filter())) { + return; + } + } + for (auto &condition : join.conditions) { + auto &probe_key = condition.GetLHS().Cast(); + auto &build_key = condition.GetRHS().Cast(); + if (probe_key.Depth() != 0 || build_key.Depth() != 0 || probe_key.Binding().table_index != probe.table_index || + build_key.Binding().table_index != build.table_index) { + continue; + } + auto probe_column = probe_key.Binding().column_index; + auto build_column = build_key.Binding().column_index; + auto probe_filter = probe.table_filters.TryGetFilterByColumnIndex(probe_column); + auto build_filter = build.table_filters.TryGetFilterByColumnIndex(build_column); + if (!probe_filter || !build_filter || !IsScanKeyConstraint(build, build_column, *build_filter)) { + continue; + } + auto &probe_expression = probe_filter->Cast(); + auto &build_expression = build_filter->Cast(); + if (!probe_expression.Equals(build_expression)) { + continue; + } + // The build predicate and equality still enforce this constraint on every output row. + probe.table_filters.SetFilterByColumnIndex( + probe_column, + ExpressionFilter::CreateSelectivityOptionalFilter(probe_expression.expr->Copy(), probe_key.GetReturnType(), + SelectivityOptionalFilterType::MIN_MAX)); + } +} + void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &join) { if (!CanGenerateJoinFilters(join)) { return; } + MakeRedundantProbeFiltersAdaptive(join); // re-order conditions here - otherwise this will happen later on and invalidate the indexes we generate PhysicalComparisonJoin::ReorderConditions(join.conditions); auto pushdown_info = make_uniq(); @@ -793,7 +951,7 @@ void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &joi } pushdown_col.join_filter_idx = pushdown_info->join_condition.size(); - pushdown_columns.push_back(pushdown_col); + pushdown_columns.push_back(std::move(pushdown_col)); pushdown_info->join_condition.push_back(cond_idx); } if (pushdown_columns.empty()) { diff --git a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp index 2a1f50011..e1de2aaa7 100644 --- a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp +++ b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp @@ -1,11 +1,14 @@ #include "duckdb/optimizer/join_order/cardinality_estimator.hpp" #include "duckdb/common/limits.hpp" +#include "duckdb/common/set.hpp" #include "duckdb/optimizer/join_order/join_order_operator.hpp" #include "duckdb/optimizer/join_order/join_predicate.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" #include +#include namespace duckdb { @@ -14,9 +17,9 @@ struct DomainEstimate { DomainEstimate(); public: - double GetDistinctCount(const JoinPredicate &predicate) const; + CardinalityValue GetDistinctCount(const JoinPredicate &predicate) const; bool HasReliableDistinctCount() const; - idx_t GetReliableDistinctCount() const; + CardinalityValue GetReliableDistinctCount() const; void Update(ColumnBinding binding, const DistinctCount &distinct_count, optional_ptr sources); void AddSource(const JoinColumnSource &source); @@ -29,13 +32,13 @@ struct DomainEstimate { column_binding_set_t sources; idx_t reliable_source_count = 0; idx_t reliable_source_cardinality = NumericLimits::Maximum(); - vector min_max_candidates; + vector min_max_candidates; }; DomainEstimate::DomainEstimate() { } -double DomainEstimate::GetDistinctCount(const JoinPredicate &predicate) const { +CardinalityValue DomainEstimate::GetDistinctCount(const JoinPredicate &predicate) const { auto domain = estimate; for (bool left : {true, false}) { auto entry = local_fallbacks.find(predicate.GetStatsBinding(left)); @@ -44,7 +47,7 @@ double DomainEstimate::GetDistinctCount(const JoinPredicate &predicate) const { } } if (!domain) { - return static_cast(NumericLimits::Maximum()); + return CardinalityValue(static_cast(NumericLimits::Maximum())); } auto result = domain->distinct_count; auto comparison = predicate.GetComparisonType(); @@ -52,28 +55,27 @@ double DomainEstimate::GetDistinctCount(const JoinPredicate &predicate) const { predicate.GetJoinType() == JoinType::INNER && (comparison == ExpressionType::COMPARE_EQUAL || comparison == ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { // Discount scan-backed domains before applying predicate-local bounds. - return MinValue(static_cast(result), - MaxValue(1.0, static_cast(estimate->distinct_count) * - RelationStatisticsHelper::DEFAULT_SELECTIVITY)); + return MinValue(result, MaxValue(CardinalityValue(1), + estimate->distinct_count * RelationStatisticsHelper::DEFAULT_SELECTIVITY)); } if (!HasReliableDistinctCount() || reliable_source_count != 1) { - return static_cast(result); + return result; } - auto key_domain = NumericLimits::Maximum(); + optional key_domain; for (auto candidate : min_max_candidates) { if (candidate > result && candidate <= reliable_source_cardinality) { - key_domain = MinValue(key_domain, candidate); + key_domain = key_domain ? MinValue(*key_domain, candidate) : candidate; } } - return static_cast(key_domain == NumericLimits::Maximum() ? result : key_domain); + return key_domain ? *key_domain : result; } bool DomainEstimate::HasReliableDistinctCount() const { return estimate && (estimate->source == DistinctCountSource::HLL || estimate->source == DistinctCountSource::EXACT); } -idx_t DomainEstimate::GetReliableDistinctCount() const { - if (!estimate || (estimate->source != DistinctCountSource::HLL && estimate->source != DistinctCountSource::EXACT)) { +CardinalityValue DomainEstimate::GetReliableDistinctCount() const { + if (!estimate || !HasReliableDistinctCount()) { throw InternalException("Attempted to access an unreliable distinct count"); } return estimate->distinct_count; @@ -84,7 +86,7 @@ void DomainEstimate::Restrict(idx_t bound) { if (!estimate) { return; } - estimate->distinct_count = MinValue(estimate->distinct_count, bound); + estimate->distinct_count = MinValue(estimate->distinct_count, CardinalityValue(bound)); // the filter bound holds for every column of the class; no candidate overrides it min_max_candidates.clear(); } @@ -136,13 +138,13 @@ struct RelationsSetToStats { struct FilterInfoWithTotalDomains { FilterInfoWithTotalDomains(JoinPredicate &predicate, RelationsSetToStats &relation_set_to_stats) : predicate(predicate), domain_estimate(relation_set_to_stats.domain_estimate), - distinct_count(domain_estimate.get().GetDistinctCount(predicate)) { + distinct_count(domain_estimate.get().GetDistinctCount(predicate)), residual(predicate.IsResidualFilter()) { } public: - double GetDistinctCount() const; + CardinalityValue GetDistinctCount() const; bool HasReliableDistinctCount() const; - idx_t GetReliableDistinctCount() const; + CardinalityValue GetReliableDistinctCount() const; ExpressionType GetComparisonType(); bool IsInnerEquality(); FilterInfo &GetFilter() const; @@ -151,7 +153,8 @@ struct FilterInfoWithTotalDomains { public: reference predicate; reference domain_estimate; - double distinct_count; + CardinalityValue distinct_count; + bool residual; }; struct SelectivitySubgraph { @@ -170,7 +173,7 @@ struct CompositeJoinPairStats { //! as an observed single-column domain. Otherwise broad fact-to-fact joins can look like key lookups. static constexpr double MAX_CARDINALITY_TO_DISTINCT_RATIO = 8; - void RegisterDistinctCount(double distinct_count) { + void RegisterDistinctCount(CardinalityValue distinct_count) { if (!has_distinct_count) { first_distinct_count = distinct_count; has_distinct_count = true; @@ -180,14 +183,14 @@ struct CompositeJoinPairStats { } } - bool CanApplyCap(double cap) const { - return has_distinct_count && max_distinct_count > 0 && + bool CanApplyCap(CardinalityValue cap) const { + return has_distinct_count && cap > 0 && max_distinct_count > 0 && cap <= max_distinct_count * MAX_CARDINALITY_TO_DISTINCT_RATIO; } public: - double first_distinct_count = 0; - double max_distinct_count = 0; + CardinalityValue first_distinct_count = 0; + CardinalityValue max_distinct_count = 0; bool has_distinct_count = false; }; @@ -199,8 +202,24 @@ struct LogicalJoinStats { reference op; reference scope; CardinalityValue selectivity; + vector> equality_keys; + bool has_residual = false; }; +struct RegionEstimate { + CardinalityValue cardinality; + optional_idx maximum; + CardinalityValue row_retention; +}; + +struct ResidualFilterStats { + reference filter; + CardinalityValue selectivity; + bool proven_empty; +}; + +static CardinalityValue GetResidualOnSelectivity(const Expression &expression); + struct CardinalityEstimatorState { void InitializeEdgeIndex(); bool TryGetCandidateEdges(const JoinRelationSet &set, vector &candidates) const; @@ -210,14 +229,15 @@ struct CardinalityEstimatorState { //! 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; + vector leaves; vector> operators; vector boundaries; reference_map_t inner_selectivities; - reference_map_t cardinalities; - vector> residual_filters; + reference_map_t cardinalities; + //! Only requested columns at semantic boundaries; inner subsets do not acquire full column vectors. + reference_map_t> projected_columns; + vector residual_filters; + unordered_set leaf_filters; }; CardinalityEstimator::CardinalityEstimator(JoinRelationSetManager &set_manager, @@ -228,7 +248,7 @@ CardinalityEstimator::CardinalityEstimator(JoinRelationSetManager &set_manager, CardinalityEstimator::~CardinalityEstimator() { } -double FilterInfoWithTotalDomains::GetDistinctCount() const { +CardinalityValue FilterInfoWithTotalDomains::GetDistinctCount() const { return distinct_count; } @@ -236,7 +256,7 @@ bool FilterInfoWithTotalDomains::HasReliableDistinctCount() const { return domain_estimate.get().HasReliableDistinctCount(); } -idx_t FilterInfoWithTotalDomains::GetReliableDistinctCount() const { +CardinalityValue FilterInfoWithTotalDomains::GetReliableDistinctCount() const { return domain_estimate.get().GetReliableDistinctCount(); } @@ -257,7 +277,7 @@ JoinPredicate &FilterInfoWithTotalDomains::GetPredicate() const { } void CardinalityEstimatorState::InitializeEdgeIndex() { - edges_by_relation.resize(leaf_cardinalities.size()); + edges_by_relation.resize(leaves.size()); for (idx_t i = 0; i < edges.size(); i++) { auto &scope = edges[i].GetFilter().set.get(); if (scope.Empty()) { @@ -345,23 +365,19 @@ bool CardinalityEstimator::SingleColumnFilter(const FilterInfo &filter_info) { return true; } -static bool IsResidualFilter(const FilterInfo &filter) { - if (filter.join_type != JoinType::INNER || - (filter.set.get().count < 2 && !filter.source_operator_index.IsValid())) { - return false; - } - return filter.must_remain_filter || filter.from_residual_predicate || - (filter.filter && filter.filter->GetExpressionType() == ExpressionType::CONJUNCTION_OR); -} - void CardinalityEstimator::InitEquivalentRelations() { state->relation_set_stats.clear(); state->residual_filters.clear(); for (auto predicate_ref : predicate_model.GetPredicates()) { auto &filter = predicate_ref.get().GetFilter(); - if (IsResidualFilter(filter)) { - state->residual_filters.push_back(filter); + if (state->leaf_filters.count(filter.filter_index)) { + continue; + } + if (predicate_ref.get().IsResidualFilter()) { + auto selectivity = GetResidualOnSelectivity(*filter.filter); + auto constant = filter.filter->GetExpressionClass() == ExpressionClass::BOUND_CONSTANT; + state->residual_filters.push_back({filter, selectivity, constant && selectivity.IsZero()}); continue; } if (SingleColumnFilter(filter)) { @@ -402,14 +418,16 @@ void CardinalityEstimator::InitEquivalentRelations() { CardinalityValue CardinalityEstimator::GetNumerator(JoinRelationSet &set) { CardinalityValue numerator; for (idx_t i = 0; i < set.count; i++) { - auto cardinality = state->leaf_cardinalities.at(set.relations[i].index); - // Logical output handles exact zero separately from the selectivity model. - numerator *= cardinality.IsZero() ? CardinalityValue(1) : cardinality; + auto cardinality = state->leaves.at(set.relations[i].index).cardinality; + numerator *= cardinality; } return numerator; } bool CardinalityEstimator::IsFilterApplicable(const FilterInfo &filter, JoinRelationSet &set) const { + if ((filter.must_remain_at_root || filter.set.get().Empty()) && set.count != state->leaves.size()) { + return false; + } if (!filter.set.get().Empty() && !JoinRelationSet::IsSubset(set, filter.set)) { return false; } @@ -424,8 +442,7 @@ bool CardinalityEstimator::IsFilterApplicable(const FilterInfo &filter, JoinRela static optional_ptr GetEdgeEndpoint(FilterInfoWithTotalDomains &edge, JoinRelationSetManager &set_manager, bool left) { - auto &filter = edge.GetFilter(); - if (filter.filter && BoundComparisonExpression::IsComparison(*filter.filter)) { + if (edge.GetComparisonType() != ExpressionType::INVALID) { auto &binding = edge.GetPredicate().GetStatsBinding(left); if (binding.table_index.IsValid()) { return &set_manager.GetJoinRelation(RelationIndex(binding.table_index.index)); @@ -450,37 +467,21 @@ bool EdgeConnects(FilterInfoWithTotalDomains &edge, SelectivitySubgraph &subgrap vector SubgraphsConnectedByEdge(FilterInfoWithTotalDomains &edge, vector &subgraphs, JoinRelationSetManager &set_manager) { vector res; - if (subgraphs.empty()) { - return res; - } else { - // check the combinations of subgraphs and see if the edge connects two of them, - // if so, return the indexes of the two subgraphs within the vector - for (idx_t outer = 0; outer != subgraphs.size(); outer++) { - // check if the edge connects two subgraphs. - for (idx_t inner = outer + 1; inner != subgraphs.size(); inner++) { - if (EdgeConnects(edge, subgraphs.at(outer), set_manager) && - EdgeConnects(edge, subgraphs.at(inner), set_manager)) { - // order is important because we will delete the inner subgraph later - res.push_back(outer); - res.push_back(inner); - return res; - } - } - // if the edge does not connect two subgraphs, see if the edge connects with just outer - // merge subgraph.at(outer) with the RelationSet(s) that edge connects - if (EdgeConnects(edge, subgraphs.at(outer), set_manager)) { - res.push_back(outer); - return res; + // Keep the first two matches in order: merging removes the second subgraph. + for (idx_t index = 0; index < subgraphs.size(); index++) { + if (EdgeConnects(edge, subgraphs.at(index), set_manager)) { + res.push_back(index); + if (res.size() == 2) { + break; } } } - // this edge connects only the relations it connects. Return an empty result so a new subgraph is created. return res; } // Apply the selectivity multiplier for a given comparison type and effective distinct count. static CardinalityValue ApplyComparisonRatio(CardinalityValue base_selectivity, ExpressionType comparison_type, - double effective_d) { + CardinalityValue effective_d) { switch (comparison_type) { case ExpressionType::COMPARE_EQUAL: case ExpressionType::COMPARE_NOT_DISTINCT_FROM: @@ -501,8 +502,8 @@ static CardinalityValue ApplyComparisonRatio(CardinalityValue base_selectivity, } } -static double GetEffectiveDistinctCount(double distinct_count) { - return distinct_count <= 0 ? 1 : distinct_count; +static CardinalityValue GetEffectiveDistinctCount(CardinalityValue distinct_count) { + return distinct_count.IsZero() ? CardinalityValue(1) : distinct_count; } CardinalityValue CardinalityEstimator::CalculateInnerJoinSelectivity(CardinalityValue base_selectivity, @@ -541,58 +542,92 @@ static optional_ptr GetEqualityJoinPair(FilterInfoWithTotalDoma return set_manager.Union(left_set, right_set); } -double CardinalityEstimator::GetJoinPairCap(JoinRelationSet &join_pair) { +CardinalityValue CardinalityEstimator::GetJoinPairCap(JoinRelationSet &join_pair) { D_ASSERT(join_pair.count == 2); - double cap = NumericLimits::Maximum(); + auto cap = GetNumerator(set_manager.GetJoinRelation(join_pair.relations[0])); for (idx_t relation_index = 0; relation_index < join_pair.count; relation_index++) { auto &single_relation = set_manager.GetJoinRelation(join_pair.relations[relation_index]); - auto cardinality = GetNumerator(single_relation).GetDouble(); + auto cardinality = GetNumerator(single_relation); if (cardinality <= 0) { return 0; } cap = MinValue(cap, cardinality); } - return cap == NumericLimits::Maximum() ? 0 : cap; + return cap; } -double CardinalityEstimator::GetUniqueJoinPairDomain(JoinRelationSet &join_pair) { +CardinalityValue CardinalityEstimator::GetUniqueJoinPairDomain(JoinRelationSet &join_pair) { D_ASSERT(join_pair.count == 2); auto equality_pair = predicate_model.GetDirectEqualityPair(join_pair); if (!equality_pair) { return 0; } - double domain = 0; + CardinalityValue domain(0); for (idx_t relation_index = 0; relation_index < join_pair.count; relation_index++) { auto relation = join_pair.relations[relation_index]; auto &equality_bindings = relation_index == 0 ? equality_pair->first_relation_bindings : equality_pair->second_relation_bindings; - auto &unique_key = state->unique_keys.at(relation.index); - bool covered = !unique_key.empty(); - for (auto column : unique_key) { - ColumnBinding binding(TableIndex(relation.index), ProjectionIndex(column)); - covered = covered && equality_bindings.find(binding) != equality_bindings.end(); - } - if (covered) { - // Every row of this relation is a different key combination, so the other side matches at most one row. - domain = MaxValue(domain, GetNumerator(set_manager.GetJoinRelation(relation)).GetDouble()); + for (auto &unique_key : state->leaves.at(relation.index).unique_keys) { + bool covered = !unique_key.empty(); + for (auto column : unique_key) { + ColumnBinding binding(TableIndex(relation.index), ProjectionIndex(column)); + covered = covered && equality_bindings.find(binding) != equality_bindings.end(); + } + if (covered) { + // Every row has a different key combination, so the other side matches at most one row. + domain = MaxValue(domain, GetNumerator(set_manager.GetJoinRelation(relation))); + break; + } } } return domain; } -bool CardinalityEstimator::ApplyJoinPairCap(CardinalityValue &target_selectivity, JoinRelationSet &join_pair, - reference_map_t &join_pair_stats, - reference_set_t &capped_join_pairs) { +class CardinalityEstimator::CompositeJoinPairCaps { +public: + explicit CompositeJoinPairCaps(CardinalityEstimator &estimator) : estimator(estimator) { + } + + void Register(FilterInfoWithTotalDomains &edge); + bool ApplyIncrement(CardinalityValue &target_selectivity, FilterInfoWithTotalDomains &edge, JoinRelationSet &scope); + bool ApplyPending(CardinalityValue &target_selectivity, JoinRelationSet &scope); + +private: + bool ApplyPair(CardinalityValue &target_selectivity, JoinRelationSet &join_pair); + +private: + CardinalityEstimator &estimator; + //! Successfully capped pairs cannot be registered again. + reference_map_t pending_join_pairs; + reference_set_t capped_join_pairs; +}; + +void CardinalityEstimator::CompositeJoinPairCaps::Register(FilterInfoWithTotalDomains &edge) { + if (!edge.IsInnerEquality()) { + return; + } + auto join_pair = GetEqualityJoinPair(edge, estimator.set_manager); + if (!join_pair || !estimator.predicate_model.HasDirectCompositeEquality(*join_pair)) { + return; + } + if (capped_join_pairs.find(*join_pair) != capped_join_pairs.end()) { + return; + } + pending_join_pairs[*join_pair].RegisterDistinctCount(edge.GetDistinctCount()); +} + +bool CardinalityEstimator::CompositeJoinPairCaps::ApplyPair(CardinalityValue &target_selectivity, + JoinRelationSet &join_pair) { if (capped_join_pairs.find(join_pair) != capped_join_pairs.end()) { return false; } - const auto it = join_pair_stats.find(join_pair); - if (it == join_pair_stats.end()) { + const auto it = pending_join_pairs.find(join_pair); + if (it == pending_join_pairs.end()) { return false; } auto &stats = it->second; - auto cap = GetJoinPairCap(join_pair); - auto unique_domain = GetUniqueJoinPairDomain(join_pair); + auto cap = estimator.GetJoinPairCap(join_pair); + auto unique_domain = estimator.GetUniqueJoinPairDomain(join_pair); if (unique_domain > 0) { // The equalities cover a key: its row count is the composite NDV, not a proxy for it. cap = unique_domain; @@ -609,58 +644,49 @@ bool CardinalityEstimator::ApplyJoinPairCap(CardinalityValue &target_selectivity if (cap > 0 && first_d < cap && first_d > 0) { // Lower weak same-pair composite evidence to the FK/PK cap. target_selectivity = target_selectivity * CardinalityValue(first_d) / CardinalityValue(cap); - first_d = cap; } capped_join_pairs.insert(join_pair); + pending_join_pairs.erase(it); return true; } -bool CardinalityEstimator::ApplyJoinIncrement(CardinalityValue &target_selectivity, FilterInfoWithTotalDomains &edge, - reference_map_t &join_pair_stats, - reference_set_t &capped_join_pairs, - JoinRelationSet &scope, optional_ptr join_pair) { +bool CardinalityEstimator::CompositeJoinPairCaps::ApplyIncrement(CardinalityValue &target_selectivity, + FilterInfoWithTotalDomains &edge, + JoinRelationSet &scope) { if (edge.IsInnerEquality()) { - auto target_pair = join_pair; - if (!target_pair) { - target_pair = GetEqualityJoinPair(edge, set_manager); - } + auto target_pair = GetEqualityJoinPair(edge, estimator.set_manager); if (!target_pair) { return false; } if (!JoinRelationSet::IsSubset(scope, *target_pair) || - !predicate_model.HasDirectCompositeEquality(*target_pair)) { + !estimator.predicate_model.HasDirectCompositeEquality(*target_pair)) { return false; } if (capped_join_pairs.find(*target_pair) != capped_join_pairs.end()) { // The composite-key cap already accounts for same-pair equality predicates. return true; } - return ApplyJoinPairCap(target_selectivity, *target_pair, join_pair_stats, capped_join_pairs); + return ApplyPair(target_selectivity, *target_pair); } return false; } -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()) { +bool CardinalityEstimator::CompositeJoinPairCaps::ApplyPending(CardinalityValue &target_selectivity, + JoinRelationSet &scope) { + if (pending_join_pairs.empty()) { return false; } bool applied = false; - for (auto &entry : join_pair_stats) { - auto &join_pair = entry.first.get(); - if (capped_join_pairs.find(join_pair) != capped_join_pairs.end()) { - continue; - } + for (auto it = pending_join_pairs.begin(); it != pending_join_pairs.end();) { + // Applying the cap erases this entry. + auto &join_pair = (it++)->first.get(); + D_ASSERT(capped_join_pairs.find(join_pair) == capped_join_pairs.end()); if (!JoinRelationSet::IsSubset(scope, join_pair)) { continue; } - if (!predicate_model.HasDirectCompositeEquality(join_pair)) { - continue; - } - applied = ApplyJoinPairCap(target_selectivity, join_pair, join_pair_stats, capped_join_pairs) || applied; + D_ASSERT(estimator.predicate_model.HasDirectCompositeEquality(join_pair)); + applied = ApplyPair(target_selectivity, join_pair) || applied; } return applied; } @@ -696,44 +722,32 @@ static bool CanIncrementExistingJoin(SelectivityEdgeKind kind) { return kind == SelectivityEdgeKind::INNER_EQUIVALENCE; } -static void RegisterEqualityJoinPair(FilterInfoWithTotalDomains &edge, JoinRelationSetManager &set_manager, - reference_map_t &join_pair_stats) { - if (!edge.IsInnerEquality()) { - return; +struct CardinalityEstimator::SelectivityState { + explicit SelectivityState(CardinalityEstimator &estimator) : composite_caps(estimator) { } - auto join_pair = GetEqualityJoinPair(edge, set_manager); - if (!join_pair) { - return; + + bool IsComplete(JoinRelationSet &set) const { + return subgraphs.size() == 1 && subgraphs.at(0).relations && + RefersToSameObject(*subgraphs.at(0).relations, set); } - join_pair_stats[*join_pair].RegisterDistinctCount(edge.GetDistinctCount()); -} -struct SelectivityState { vector subgraphs; unordered_set applied_equivalence_groups; - reference_map_t join_pair_stats; - reference_set_t capped_join_pairs; - unordered_set unused_edge_tdoms; + CompositeJoinPairCaps composite_caps; + set unused_edge_tdoms; }; -static bool SelectivitySubgraphComplete(SelectivityState &state, JoinRelationSet &set) { - return state.subgraphs.size() == 1 && state.subgraphs.at(0).relations && - RefersToSameObject(*state.subgraphs.at(0).relations, set); -} - void CardinalityEstimator::ProcessSelectivityEdge(FilterInfoWithTotalDomains &edge, JoinRelationSet &requested_set, SelectivityState &state) { auto edge_kind = ClassifySelectivityEdge(edge, state.applied_equivalence_groups); - if (SelectivitySubgraphComplete(state, requested_set)) { + if (state.IsComplete(requested_set)) { auto &complete_subgraph = state.subgraphs.at(0); - ApplyCompositeJoinPairCaps(complete_subgraph.selectivity, *complete_subgraph.relations, state.join_pair_stats, - state.capped_join_pairs); + state.composite_caps.ApplyPending(complete_subgraph.selectivity, *complete_subgraph.relations); if (edge_kind == SelectivityEdgeKind::REDUNDANT_TRANSITIVE_EQUALITY) { return; } if (CanIncrementExistingJoin(edge_kind) && - ApplyJoinIncrement(complete_subgraph.selectivity, edge, state.join_pair_stats, state.capped_join_pairs, - *complete_subgraph.relations)) { + state.composite_caps.ApplyIncrement(complete_subgraph.selectivity, edge, *complete_subgraph.relations)) { return; } if (edge.HasReliableDistinctCount()) { @@ -746,7 +760,7 @@ void CardinalityEstimator::ProcessSelectivityEdge(FilterInfoWithTotalDomains &ed if (equality_class_index.IsValid()) { state.applied_equivalence_groups.insert(equality_class_index.GetIndex()); } - RegisterEqualityJoinPair(edge, set_manager, state.join_pair_stats); + state.composite_caps.Register(edge); auto edge_left_set = GetEdgeEndpoint(edge, set_manager, true); auto edge_right_set = GetEdgeEndpoint(edge, set_manager, false); @@ -771,8 +785,7 @@ void CardinalityEstimator::CreateSelectivitySubgraph(FilterInfoWithTotalDomains auto selectivity = CalculateInnerJoinSelectivity(CardinalityValue(1), edge); left_subgraph.relations = &set_manager.Union(edge_left_set, edge_right_set); left_subgraph.selectivity = selectivity; - ApplyCompositeJoinPairCaps(left_subgraph.selectivity, *left_subgraph.relations, state.join_pair_stats, - state.capped_join_pairs); + state.composite_caps.ApplyPending(left_subgraph.selectivity, *left_subgraph.relations); state.subgraphs.push_back(left_subgraph); } @@ -789,19 +802,16 @@ void CardinalityEstimator::ExtendSelectivitySubgraph(idx_t subgraph_index, Filte if (JoinRelationSet::IsSubset(*left_subgraph->relations, edge_left_set) && JoinRelationSet::IsSubset(*left_subgraph->relations, edge_right_set)) { if (can_increment_existing_join) { - ApplyJoinIncrement(left_subgraph->selectivity, edge, state.join_pair_stats, state.capped_join_pairs, - *left_subgraph->relations); + state.composite_caps.ApplyIncrement(left_subgraph->selectivity, edge, *left_subgraph->relations); } - ApplyCompositeJoinPairCaps(left_subgraph->selectivity, *left_subgraph->relations, state.join_pair_stats, - state.capped_join_pairs); + state.composite_caps.ApplyPending(left_subgraph->selectivity, *left_subgraph->relations); return; } auto selectivity = CalculateInnerJoinSelectivity(left_subgraph->selectivity, edge); left_subgraph->relations = &set_manager.Union(*left_subgraph->relations, *right_subgraph.relations); left_subgraph->selectivity = selectivity; - ApplyCompositeJoinPairCaps(left_subgraph->selectivity, *left_subgraph->relations, state.join_pair_stats, - state.capped_join_pairs); + state.composite_caps.ApplyPending(left_subgraph->selectivity, *left_subgraph->relations); } void CardinalityEstimator::MergeSelectivitySubgraphs(const vector &subgraph_connections, @@ -815,8 +825,7 @@ void CardinalityEstimator::MergeSelectivitySubgraphs(const vector &subgra subgraph_to_merge_into->relations = &set_manager.Union(*subgraph_to_merge_into->relations, *subgraph_to_delete->relations); subgraph_to_merge_into->selectivity = selectivity; - ApplyCompositeJoinPairCaps(subgraph_to_merge_into->selectivity, *subgraph_to_merge_into->relations, - state.join_pair_stats, state.capped_join_pairs); + state.composite_caps.ApplyPending(subgraph_to_merge_into->selectivity, *subgraph_to_merge_into->relations); subgraph_to_delete->relations = nullptr; auto remove_start = std::remove_if(state.subgraphs.begin(), state.subgraphs.end(), [](SelectivitySubgraph &s) { return !s.relations; }); @@ -838,11 +847,11 @@ void CardinalityEstimator::MergeDisconnectedSelectivitySubgraphs(SelectivityStat } CardinalityValue CardinalityEstimator::GetSelectivity(JoinRelationSet &set) { - SelectivityState selectivity_state; + SelectivityState selectivity_state(*this); 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)) { + IsFilterApplicable(filter, set) && !edge.residual) { ProcessSelectivityEdge(edge, set, selectivity_state); } }; @@ -869,8 +878,8 @@ CardinalityValue CardinalityEstimator::GetInnerSelectivity(JoinRelationSet &set) } auto result = GetSelectivity(set); for (auto &filter : state->residual_filters) { - if (IsFilterApplicable(filter, set)) { - result *= CardinalityValue(RelationStatisticsHelper::DEFAULT_SELECTIVITY); + if (IsFilterApplicable(filter.filter, set)) { + result *= filter.selectivity; } } state->inner_selectivities.emplace(set, result); @@ -883,18 +892,17 @@ CardinalityValue CardinalityEstimator::GetJoinSelectivity(JoinRelationSet &set, auto combined = GetInnerSelectivity(set); auto left_domains = GetInnerSelectivity(left); auto right_domains = GetInnerSelectivity(right); - D_ASSERT(!left_domains.IsZero() && !right_domains.IsZero()); - return MinValue(CardinalityValue(1), combined / left_domains / right_domains); + if (left_domains.IsZero() || right_domains.IsZero()) { + // Conditioning on a statistical zero has no defined ratio. Retain the + // already selected input rows; this supplies no emptiness or coverage proof. + return CardinalityValue(1); + } + return combined / left_domains / right_domains; } -CardinalityValue CardinalityEstimator::EstimateCardinality(JoinRelationSet &set) { - D_ASSERT(!state->leaf_cardinalities.empty() && !set.Empty()); - auto entry = state->cardinalities.find(set); - if (entry != state->cardinalities.end()) { - return entry->second; - } +optional_ptr CardinalityEstimator::FindBoundary(JoinRelationSet &set, + optional_ptr ®ion) { optional_ptr boundary; - optional_ptr region; for (auto &candidate : state->boundaries) { if (!JoinOrderConflictDetector::IsCompletedBy(candidate.op, set)) { continue; @@ -907,19 +915,70 @@ CardinalityValue CardinalityEstimator::EstimateCardinality(JoinRelationSet &set) region = projected; } } + return boundary; +} + +static bool ContainsBinding(const JoinRelationSet &set, ColumnBinding binding) { + if (!binding.table_index.IsValid()) { + return false; + } + return set.Contains(RelationIndex(binding.table_index.index)); +} + +SemiAntiJoinCardinalityEstimate CardinalityEstimator::EstimateMembership(const LogicalJoinStats &boundary, + JoinRelationSet &left, JoinRelationSet &right, + vector &domains) { + auto has_residual = boundary.has_residual; + for (auto &key : boundary.equality_keys) { + auto lhs = ProjectColumn(left, key.first); + auto rhs = ProjectColumn(right, key.second); + if (!lhs || !rhs) { + has_residual = true; + continue; + } + auto supported = rhs->GetSupportedSemiAntiDomainSize(); + auto total = RelationStatisticsHelper::SelectTotalDomain({lhs->total_domain, rhs->total_domain}); + if (!supported || !total || total->distinct_count.IsZero()) { + has_residual = true; + continue; + } + // Row-count fallbacks bound domains but do not estimate membership coverage. + if (total->source == DistinctCountSource::CARDINALITY) { + has_residual = true; + } + domains.push_back({total->distinct_count, *supported, key.first, key.second}); + } + auto type = boundary.op.get().type == JoinOrderOperatorType::SEMI ? JoinType::SEMI : JoinType::ANTI; + auto &left_stats = state->cardinalities.at(left); + auto &right_stats = state->cardinalities.at(right); + return RelationStatisticsHelper::EstimateSemiAntiJoinCardinality( + left_stats.cardinality, right_stats.cardinality, right_stats.row_retention, type, domains, has_residual); +} + +CardinalityValue CardinalityEstimator::EstimateCardinality(JoinRelationSet &set) { + D_ASSERT(!state->leaves.empty() && !set.Empty()); + auto entry = state->cardinalities.find(set); + if (entry != state->cardinalities.end()) { + return entry->second.cardinality; + } + optional_ptr region; + auto boundary = FindBoundary(set, region); CardinalityValue result; + CardinalityValue retention(1); + optional_idx maximum; if (!boundary) { result = GetNumerator(set) * GetInnerSelectivity(set); + maximum = optional_idx(1); for (idx_t i = 0; i < set.count; i++) { - if (state->leaf_cardinalities.at(set.relations[i].index).IsZero()) { - result = CardinalityValue(0); - break; - } + maximum = RelationStatisticsHelper::MultiplyCardinalityBounds( + maximum, state->leaves.at(set.relations[i].index).max_cardinality); } } else if (region->count < set.count) { auto &remaining = set_manager.Difference(set, *region); result = EstimateCardinality(*region) * EstimateCardinality(remaining) * GetJoinSelectivity(set, *region, remaining); + maximum = RelationStatisticsHelper::MultiplyCardinalityBounds(state->cardinalities.at(*region).maximum, + state->cardinalities.at(remaining).maximum); } else { auto &op = boundary->op.get(); auto &left = set_manager.Intersection(set, op.left_relations); @@ -929,20 +988,257 @@ 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); + maximum = RelationStatisticsHelper::JoinCardinalityBound( + JoinType::LEFT, state->cardinalities.at(left).maximum, state->cardinalities.at(right).maximum); } else if (op.type == JoinOrderOperatorType::MARK) { result = left_rows; + maximum = state->cardinalities.at(left).maximum; + retention = state->cardinalities.at(left).row_retention; } else { auto type = op.type == JoinOrderOperatorType::SEMI ? JoinType::SEMI : JoinType::ANTI; - result = RelationStatisticsHelper::EstimateSemiAntiJoinFallbackCardinality( - left_rows, right_rows.IsZero() ? 0 : 1, type); + vector domains; + result = EstimateMembership(*boundary, left, right, domains).cardinality; + maximum = RelationStatisticsHelper::JoinCardinalityBound(type, state->cardinalities.at(left).maximum, + state->cardinalities.at(right).maximum); + retention = left_rows.IsZero() ? CardinalityValue(0) + : state->cardinalities.at(left).row_retention * + MinValue(CardinalityValue(1), result / left_rows); } // Filters above the boundary see its output, including NULL-extended LEFT rows. - result *= GetJoinSelectivity(set, left, right); + auto post_selectivity = GetJoinSelectivity(set, left, right); + result *= post_selectivity; + retention *= MinValue(CardinalityValue(1), post_selectivity); } - state->cardinalities.emplace(set, result); + for (auto &filter : state->residual_filters) { + if (filter.proven_empty && IsFilterApplicable(filter.filter, set)) { + maximum = optional_idx(0); + } + } + RelationStats output; + output.cardinality = result; + output.max_cardinality = maximum; + result = output.GetCardinality(); + state->cardinalities.emplace(set, RegionEstimate {result, maximum, retention}); return result; } +CardinalityValue CardinalityEstimator::EstimateCardinalityForCost(JoinRelationSet &set) { + RelationStats rows; + rows.cardinality = EstimateCardinality(set); + rows.max_cardinality = state->cardinalities.at(set).maximum; + return rows.GetCardinalityForCost(); +} + +//! One projection scope owns both boundary resolution and equality-domain reuse for its relation set. +class CardinalityEstimator::ColumnProjection { +public: + ColumnProjection(CardinalityEstimator &estimator, JoinRelationSet &set) : estimator(estimator), set(set) { + } + + optional ProjectColumn(ColumnBinding binding); + optional ProjectStats(const vector &bindings); + +private: + void ResolveBoundary(); + optional ProjectInputColumn(ColumnBinding binding); + void ApplyEqualityClass(const JoinEqualityClass &component, DistinctCount &domain); + +private: + CardinalityEstimator &estimator; + JoinRelationSet &set; + bool boundary_resolved = false; + optional_ptr boundary; + optional_ptr region; + bool reuse_domains = false; + //! An empty entry means the class is incomplete in this set. Entries never escape this projection. + reference_map_t> equality_domains; +}; + +void CardinalityEstimator::ColumnProjection::ResolveBoundary() { + if (!boundary_resolved) { + boundary = estimator.FindBoundary(set, region); + boundary_resolved = true; + } +} + +optional CardinalityEstimator::ColumnProjection::ProjectInputColumn(ColumnBinding binding) { + if (!boundary) { + if (binding.table_index.index >= estimator.state->leaves.size()) { + return {}; + } + auto &columns = estimator.state->leaves[binding.table_index.index].columns; + if (binding.column_index.GetIndex() >= columns.size()) { + return {}; + } + auto result = columns[binding.column_index.GetIndex()]; + if (set.count > 1) { + result.semi_anti_join_domain_evidence.Invalidate(); + } + return result; + } + if (region->count < set.count) { + auto &input = ContainsBinding(*region, binding) ? *region : estimator.set_manager.Difference(set, *region); + auto result = estimator.ProjectColumn(input, binding); + if (result) { + result->semi_anti_join_domain_evidence.Invalidate(); + } + return result; + } + auto &op = boundary->op.get(); + auto &left = estimator.set_manager.Intersection(set, op.left_relations); + auto &right = estimator.set_manager.Intersection(set, op.right_relations); + bool on_left = ContainsBinding(left, binding); + if (!on_left && op.type == JoinOrderOperatorType::MARK) { + auto rhs = op.right_relations.get().relations[0]; + if (binding.table_index.index == rhs.index && + binding.column_index.GetIndex() == estimator.state->leaves[rhs.index].columns.size()) { + return RelationColumnStats(binding, DistinctCount(3, DistinctCountSource::CARDINALITY), Identifier("mark")); + } + return {}; + } + if (!on_left && op.type != JoinOrderOperatorType::LEFT) { + return {}; + } + auto result = estimator.ProjectColumn(on_left ? left : right, binding); + if (!result) { + return {}; + } + auto left_rows = estimator.state->cardinalities.at(left).cardinality; + CardinalityValue join_rows; + if (op.type == JoinOrderOperatorType::LEFT) { + join_rows = MaxValue(left_rows, + left_rows * estimator.state->cardinalities.at(right).cardinality * boundary->selectivity); + result->semi_anti_join_domain_evidence.Invalidate(); + } else if (op.type == JoinOrderOperatorType::MARK) { + join_rows = left_rows; + } else { + vector domains; + auto estimate = estimator.EstimateMembership(*boundary, left, right, domains); + join_rows = estimate.cardinality; + result->current_domain = + RelationStatisticsHelper::EstimateCurrentDomain(result->current_domain, left_rows, join_rows); + if (op.type == JoinOrderOperatorType::SEMI) { + for (auto &domain : domains) { + if (domain.preserved_binding == binding) { + result->current_domain.distinct_count = + MinValue(result->current_domain.distinct_count, domain.rhs_current_domain); + } + } + } + } + auto post_selectivity = estimator.GetJoinSelectivity(set, left, right); + result->current_domain = RelationStatisticsHelper::EstimateCurrentDomain(result->current_domain, join_rows, + join_rows * post_selectivity); + return result; +} + +void CardinalityEstimator::ColumnProjection::ApplyEqualityClass(const JoinEqualityClass &component, + DistinctCount &domain) { + auto current = domain.distinct_count; + auto cached = reuse_domains ? equality_domains.find(component) : equality_domains.end(); + if (cached != equality_domains.end()) { + if (cached->second.empty()) { + return; + } + // Preserve the original seed and member order; rounded cardinality comparisons cannot be reassociated. + for (auto &input : cached->second) { + current = MinValue(current, input); + } + } else { + bool complete = true; + vector domains; + for (auto &other : component.columns) { + if (!ContainsBinding(set, other)) { + complete = false; + break; + } + auto input = ProjectInputColumn(other); + if (!input) { + complete = false; + break; + } + current = MinValue(current, input->current_domain.distinct_count); + // Repeating the same operand is idempotent; retain the order of all distinct representations. + if (reuse_domains && + (domains.empty() || !domains.back().HasSameRepresentation(input->current_domain.distinct_count))) { + domains.push_back(input->current_domain.distinct_count); + } + } + for (auto &edge : component.edges) { + if (!complete || !estimator.IsFilterApplicable(edge.predicate.get().GetFilter(), set)) { + complete = false; + break; + } + } + if (reuse_domains) { + equality_domains.emplace(component, complete ? std::move(domains) : vector()); + } + if (!complete) { + return; + } + } + domain = DistinctCount(current, DistinctCountSource::CARDINALITY); +} + +optional CardinalityEstimator::ColumnProjection::ProjectColumn(ColumnBinding binding) { + if (!ContainsBinding(set, binding)) { + return {}; + } + auto rows = estimator.EstimateCardinality(set); + auto cached = estimator.state->projected_columns.find(set); + if (cached != estimator.state->projected_columns.end()) { + auto column = cached->second.find(binding); + if (column != cached->second.end()) { + return column->second; + } + } + ResolveBoundary(); + auto result = ProjectInputColumn(binding); + if (!result) { + return {}; + } + for (auto &component : estimator.predicate_model.GetEqualityClasses()) { + if (component.columns.count(binding)) { + ApplyEqualityClass(component, result->current_domain); + } + } + result->current_domain.distinct_count = + MinValue(MinValue(result->current_domain.distinct_count, result->total_domain.distinct_count), rows); + if (boundary) { + estimator.state->projected_columns[set].emplace(binding, *result); + } + return result; +} + +optional CardinalityEstimator::ColumnProjection::ProjectStats(const vector &bindings) { + RelationStats result; + result.cardinality = estimator.EstimateCardinality(set); + auto &estimate = estimator.state->cardinalities.at(set); + result.max_cardinality = estimate.maximum; + result.row_retention = estimate.row_retention; + // Scalar requests keep the direct, allocation-free reduction. + reuse_domains = bindings.size() > 1; + for (auto &binding : bindings) { + auto column = ProjectColumn(binding); + if (!column) { + return {}; + } + result.columns.push_back(*column); + } + result.stats_initialized = true; + result.Verify(bindings); + return result; +} + +optional CardinalityEstimator::ProjectColumn(JoinRelationSet &set, ColumnBinding binding) { + return ColumnProjection(*this, set).ProjectColumn(binding); +} + +optional CardinalityEstimator::ProjectStats(JoinRelationSet &set, + const vector &bindings) { + return ColumnProjection(*this, set).ProjectStats(bindings); +} + static CardinalityValue GetResidualOnSelectivity(const Expression &expression) { if (expression.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { auto &value = expression.Cast().GetValue(); @@ -1021,18 +1317,40 @@ static bool SortEdges(const FilterInfoWithTotalDomains &a, const FilterInfoWithT return a.GetDistinctCount() > b.GetDistinctCount(); } -void CardinalityEstimator::Initialize(const vector &relations, +void CardinalityEstimator::Initialize(vector relations, const vector> &operators, const join_column_sources_t &sources) { - D_ASSERT(state->leaf_cardinalities.empty()); + D_ASSERT(state->leaves.empty()); + state->leaves = std::move(relations); + // Region-local single-input filters commute to that input. Capture their effect once, + // while expressions and column bindings still describe the original input. + std::map>> leaf_expressions; + for (auto predicate : predicate_model.GetPredicates()) { + auto &filter = predicate.get().GetFilter(); + if (filter.from_logical_filter && filter.set.get().count == 1 && !filter.must_remain_at_root) { + leaf_expressions[filter.set.get().relations[0].index].push_back(filter.filter->Copy()); + state->leaf_filters.insert(filter.filter_index); + } + } + for (auto &entry : leaf_expressions) { + auto &leaf = state->leaves[entry.first]; + vector bindings; + for (auto &column : leaf.columns) { + bindings.push_back(column.binding); + } + leaf = RelationStatisticsHelper::ConditionFilterStats(leaf, entry.second, bindings); + } InitEquivalentRelations(); - for (idx_t i = 0; i < relations.size(); i++) { - auto &stats = relations[i]; + for (idx_t i = 0; i < state->leaves.size(); i++) { + auto &stats = state->leaves[i]; D_ASSERT(stats.stats_initialized); - auto cardinality = CardinalityValue(static_cast(stats.cardinality)); - state->leaf_cardinalities.push_back(cardinality); - state->unique_keys.push_back(stats.unique_key); - state->cardinalities.emplace(set_manager.GetJoinRelation(RelationIndex(i)), cardinality); + auto cardinality = stats.GetCardinality(); + stats.cardinality = cardinality; + for (idx_t column = 0; column < stats.columns.size(); column++) { + stats.columns[column].binding = ColumnBinding(TableIndex(i), ProjectionIndex(column)); + } + state->cardinalities.emplace(set_manager.GetJoinRelation(RelationIndex(i)), + RegionEstimate {cardinality, stats.max_cardinality, stats.row_retention}); UpdateTotalDomains(RelationIndex(i), stats, sources); } for (auto &op : operators) { @@ -1042,14 +1360,14 @@ void CardinalityEstimator::Initialize(const vector &relations, 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())); + auto key = ColumnBinding(TableIndex(rhs.index), ProjectionIndex(state->leaves[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); + RestrictFilterDomains(state->leaves); for (auto &domain : state->relation_set_stats) { for (auto &predicate : domain.predicates) { state->edges.emplace_back(predicate, domain); @@ -1065,6 +1383,42 @@ void CardinalityEstimator::Initialize(const vector &relations, } auto selectivity = op->type == JoinOrderOperatorType::LEFT ? GetLeftJoinSelectivity(*op) : CardinalityValue(1); state->boundaries.emplace_back(*op, set_manager.Union(op->left_relations, op->right_relations), selectivity); + auto &boundary = state->boundaries.back(); + for (auto &condition : op->conditions) { + boundary.has_residual |= !condition.IsComparison() || + (condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL && + condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM); + } + idx_t predicate_count = 0; + for (auto &predicate_ref : predicate_model.GetPredicates()) { + auto &predicate = predicate_ref.get(); + auto source = predicate.GetFilter().source_operator_index; + if (!source.IsValid() || source.GetIndex() != op->index) { + continue; + } + predicate_count++; + auto type = predicate.GetComparisonType(); + if ((type != ExpressionType::COMPARE_EQUAL && type != ExpressionType::COMPARE_NOT_DISTINCT_FROM) || + !predicate.HasValidEqualityBindings()) { + boundary.has_residual = true; + continue; + } + auto left = predicate.GetEqualityBinding(true); + auto right = predicate.GetEqualityBinding(false); + if (ContainsBinding(op->right_relations, left) && ContainsBinding(op->left_relations, right)) { + std::swap(left, right); + } + if (!ContainsBinding(op->left_relations, left) || !ContainsBinding(op->right_relations, right)) { + boundary.has_residual = true; + continue; + } + auto key = make_pair(left, right); + if (std::find(boundary.equality_keys.begin(), boundary.equality_keys.end(), key) == + boundary.equality_keys.end()) { + boundary.equality_keys.push_back(key); + } + } + boundary.has_residual |= predicate_count < op->conditions.size(); } } diff --git a/src/duckdb/src/optimizer/join_order/cost_model.cpp b/src/duckdb/src/optimizer/join_order/cost_model.cpp index dccbc0d53..6c302bded 100644 --- a/src/duckdb/src/optimizer/join_order/cost_model.cpp +++ b/src/duckdb/src/optimizer/join_order/cost_model.cpp @@ -16,14 +16,19 @@ CardinalityEstimator &CostModel::GetCardinalityEstimator() { } double CostModel::ComputeCost(const DPJoinNode &left, const DPJoinNode &right, - optional_ptr join_operator, double output_rows) { - auto input_cost = - join_operator && join_operator->type == JoinOrderOperatorType::LEFT ? right.cardinality.GetDouble() : 0; + optional_ptr join_operator, JoinRelationSet &output) { + auto input_cost = join_operator && join_operator->type == JoinOrderOperatorType::LEFT + ? cardinality_estimator.EstimateCardinalityForCost(right.set).GetDouble() + : 0; + // Keep fractional INNER estimates distinct when comparing join orders. + auto output_rows = !join_operator || join_operator->type == JoinOrderOperatorType::INNER + ? cardinality_estimator.EstimateCardinality(output).GetDouble() + : cardinality_estimator.EstimateCardinalityForCost(output).GetDouble(); 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); + return left.cost + right.cost + output_rows; } void CostModel::InitializeRecursiveMemory(ClientContext &context, RelationManager &relations) { @@ -82,7 +87,7 @@ void CostModel::UpdateBuildMemory(DPJoinNode &result, const DPJoinNode &left, co left_properties.build.correlation_sensitive || right_properties.build.correlation_sensitive; properties.build.repeatable = left_properties.build.repeatable && right_properties.build.repeatable; for (auto &predicate : result.predicates) { - properties.build.repeatable &= !predicate.get().GetFilter().filter->IsVolatile(); + properties.build.repeatable &= !predicate.get().IsVolatile(); } if (!recursive_relations) { return; 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 e0ae79957..7ff571060 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_candidate.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_candidate.cpp @@ -112,7 +112,7 @@ JoinOrderCandidateEvaluator::CreateJoinTree(JoinRelationSet &set, return nullptr; } } - auto cost = cost_model.ComputeCost(left, right, best_candidate->join_operator, cardinality.GetDouble()); + auto cost = cost_model.ComputeCost(left, right, best_candidate->join_operator, set); auto result = make_uniq(set, best_candidate->join_operator, std::move(best_candidate->predicates), best_candidate->generated_cross_product, left.set, right.set, cost); result->cardinality = cardinality; @@ -202,11 +202,11 @@ bool JoinOrderCandidateEvaluator::CanImprovePair(const JoinOrderPlanMap &plans, right.cardinality > incumbent_right->second->cardinality; } -void JoinOrderCandidateEvaluator::InitLeafPlans(JoinOrderPlanMap &plans, const vector &relation_stats) { +void JoinOrderCandidateEvaluator::InitLeafPlans(JoinOrderPlanMap &plans, vector relation_stats) { auto &estimator = cost_model.GetCardinalityEstimator(); - estimator.Initialize(relation_stats, query_graph_manager.GetJoinOperators(), + estimator.Initialize(std::move(relation_stats), query_graph_manager.GetJoinOperators(), query_graph_manager.relation_manager.GetColumnSources()); - for (idx_t i = 0; i < relation_stats.size(); i++) { + for (idx_t i = 0; i < query_graph_manager.relation_manager.NumRelations(); i++) { auto &relation_set = query_graph_manager.set_manager.GetJoinRelation(RelationIndex(i)); auto join_node = make_uniq(relation_set); join_node->cost = 0; diff --git a/src/duckdb/src/optimizer/join_order/join_order_linearizer.cpp b/src/duckdb/src/optimizer/join_order/join_order_linearizer.cpp index 97dff0e52..717c97472 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_linearizer.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_linearizer.cpp @@ -20,10 +20,13 @@ bool JoinOrderLinearizer::BuildTree() { } } auto count = graph.relation_manager.NumRelations(); + vector input_cardinalities; + input_cardinalities.reserve(count); 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()); + input_cardinalities.push_back(estimator.EstimateCardinality(set)); + cardinalities.push_back(input_cardinalities.back().GetLog()); } vector edges; bool edges_complete = true; @@ -39,7 +42,9 @@ bool JoinOrderLinearizer::BuildTree() { 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]; + // Divide before taking logs: subtracting large logs can reorder equal-selectivity edges. + auto input_rows = input_cardinalities[lhs] * input_cardinalities[rhs]; + selectivity = (estimator.EstimateCardinality(set) / input_rows).GetLog(); } edges.push_back({MinValue(lhs, rhs), MaxValue(lhs, rhs), selectivity}); return false; diff --git a/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp b/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp index 81c384d83..724f2157b 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp @@ -48,53 +48,72 @@ unique_ptr JoinOrderOptimizer::Optimize(unique_ptr new_logical_plan = nullptr; RelationStats output_stats; - if (reorderable) { - // query graph now has filters and relations + auto &relation_manager = query_graph_manager.relation_manager; + if (reorderable || (relation_manager.NumRelations() > 1 && relation_manager.HasCompleteStats())) { + // A retained join order still has an estimable region when all inputs were captured. auto cardinality_estimator = CardinalityEstimator(query_graph_manager.set_manager, query_graph_manager.GetPredicateModel()); - auto cost_model = CostModel(cardinality_estimator); - bool inner_region = true; - for (auto &join : query_graph_manager.GetJoinOperators()) { - inner_region &= - join->type == JoinOrderOperatorType::INNER || join->type == JoinOrderOperatorType::CROSS_PRODUCT; - } - if (inner_region) { - cost_model.InitializeRecursiveMemory(context, query_graph_manager.relation_manager); - } + if (reorderable) { + auto cost_model = CostModel(cardinality_estimator); + bool inner_region = true; + for (auto &join : query_graph_manager.GetJoinOperators()) { + inner_region &= + join->type == JoinOrderOperatorType::INNER || join->type == JoinOrderOperatorType::CROSS_PRODUCT; + } + if (inner_region) { + cost_model.InitializeRecursiveMemory(context, relation_manager); + } - // Initialize a plan enumerator. - auto plan_enumerator = - PlanEnumerator(query_graph_manager, cost_model, query_graph_manager.GetQueryGraphEdges()); - - // Initialize the leaf/single node plans - plan_enumerator.InitLeafPlans(); - if (plan_enumerator.SolveJoinOrder()) { - // now reconstruct a logical plan from the query graph plan - query_graph_manager.plans = plan_enumerator.GetPlans(); - auto reconstructed = query_graph_manager.Reconstruct(std::move(plan), relation_stats); - new_logical_plan = std::move(reconstructed.op); - output_stats = std::move(reconstructed.stats); + // Initialize a plan enumerator. + auto plan_enumerator = + PlanEnumerator(query_graph_manager, cost_model, query_graph_manager.GetQueryGraphEdges()); + + // Initialize the leaf/single node plans + plan_enumerator.InitLeafPlans(); + if (plan_enumerator.SolveJoinOrder()) { + // now reconstruct a logical plan from the query graph plan + query_graph_manager.plans = plan_enumerator.GetPlans(); + auto reconstructed = query_graph_manager.Reconstruct(std::move(plan), cardinality_estimator); + new_logical_plan = std::move(reconstructed.op); + output_stats = std::move(reconstructed.stats); + } + } else { + cardinality_estimator.Initialize(relation_manager.GetRelationStats(), + query_graph_manager.GetJoinOperators(), + relation_manager.GetColumnSources()); + } + if (!new_logical_plan) { + unordered_set relations; + for (idx_t i = 0; i < relation_manager.NumRelations(); i++) { + relations.insert(RelationIndex(i)); + } + auto &set = query_graph_manager.set_manager.GetJoinRelation(relations); + auto projected = + query_graph_manager.ProjectRetainedStats(cardinality_estimator, set, op, PlanEstimateUpdate::UPDATE); + if (projected) { + output_stats = std::move(*projected); + } } } if (!new_logical_plan) { // Keep the original tree when there is nothing to reorder or enumeration cannot complete. new_logical_plan = std::move(plan); // NOLINT: plan is only moved when reconstruction succeeded - if (!reorderable && relation_stats.size() == 1) { - new_logical_plan->estimated_cardinality = relation_stats.at(0).cardinality; - new_logical_plan->has_estimated_cardinality = true; - } - if (stats && query_graph_manager.relation_manager.HasCompleteStats()) { - auto combined = query_graph_manager.CombineRelationStats( - new_logical_plan->GetColumnBindings(), relation_stats, new_logical_plan->EstimateCardinality(context)); - if (combined) { - output_stats = std::move(*combined); + if (!reorderable && relation_manager.NumRelations() == 1) { + auto &relation_stats = relation_manager.GetRelation(RelationIndex(0)).stats; + new_logical_plan->SetEstimatedCardinality(relation_stats.GetCardinalityForPlan()); + if (relation_manager.HasCompleteStats()) { + auto combined = RelationStatisticsHelper::ProjectOutputStats(relation_stats, *new_logical_plan); + if (combined) { + output_stats = std::move(*combined); + } } } + if (output_stats.stats_initialized) { + new_logical_plan->SetEstimatedCardinality(output_stats.GetCardinalityForPlan()); + } } // Propagate up a stats object from the top of the new_logical_plan if stats exist. diff --git a/src/duckdb/src/optimizer/join_order/join_order_plan.cpp b/src/duckdb/src/optimizer/join_order/join_order_plan.cpp index 0acb6741c..93aab0776 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_plan.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_plan.cpp @@ -36,7 +36,7 @@ unique_ptr CapturedJoinOrderPlan::Capture(const JoinOrder 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()); + node->cost = cost_model.ComputeCost(left, right, node->join_operator, node->set); cost_model.UpdateBuildMemory(*node, left, right); } result.emplace(node->set, std::move(node)); diff --git a/src/duckdb/src/optimizer/join_order/join_order_source_stats.cpp b/src/duckdb/src/optimizer/join_order/join_order_source_stats.cpp index 13e0b5ea0..f2c5430ac 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_source_stats.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_source_stats.cpp @@ -9,6 +9,7 @@ #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_projection.hpp" #include "duckdb/planner/operator/logical_secure_view.hpp" +#include "duckdb/storage/statistics/node_statistics.hpp" namespace duckdb { @@ -25,9 +26,9 @@ void JoinOrderSourceStats::AddPlan(ClientContext &context, LogicalOperator &root if (op.type == LogicalOperatorType::LOGICAL_GET && op.children.empty()) { auto &get = op.Cast(); if (scans.find(get.table_index) == scans.end()) { - auto cardinality = get.EstimateSourceCardinality(context); - auto stats = RelationStatisticsHelper::ExtractGetStats(get, context, cardinality); - scans.emplace(get.table_index, ScanStats {cardinality, std::move(stats)}); + auto source = get.EstimateSourceStatistics(context); + auto stats = RelationStatisticsHelper::ExtractGetStats(get, context, source); + scans.emplace(get.table_index, ScanStats {source.estimated_cardinality, std::move(stats)}); } } if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { diff --git a/src/duckdb/src/optimizer/join_order/join_predicate.cpp b/src/duckdb/src/optimizer/join_order/join_predicate.cpp index 318d052bc..ca3caf4ff 100644 --- a/src/duckdb/src/optimizer/join_order/join_predicate.cpp +++ b/src/duckdb/src/optimizer/join_order/join_predicate.cpp @@ -87,7 +87,8 @@ JoinPredicate::JoinPredicate(idx_t index, FilterInfo &filter, JoinPredicateClass ColumnBinding left_equality_binding, ColumnBinding right_equality_binding) : index(index), filter(filter), predicate_class(predicate_class), comparison_type(JoinOrderUtil::GetJoinPredicateComparisonType(filter)), - left_equality_binding(left_equality_binding), right_equality_binding(right_equality_binding) { + is_volatile(filter.filter && filter.filter->IsVolatile()), left_equality_binding(left_equality_binding), + right_equality_binding(right_equality_binding) { } idx_t JoinPredicate::GetIndex() const { @@ -110,6 +111,10 @@ ExpressionType JoinPredicate::GetComparisonType() const { return comparison_type; } +bool JoinPredicate::IsVolatile() const { + return is_volatile; +} + JoinRelationSet &JoinPredicate::GetSet() const { return filter.get().set; } @@ -180,6 +185,23 @@ bool JoinPredicate::IsEquivalencePredicate() const { return CanBuildEqualityClosure(); } +bool JoinPredicate::IsResidualFilter() const { + auto &info = filter.get(); + if (info.join_type != JoinType::INNER) { + return false; + } + // FILTERs collected from inside this join region are not included in leaf statistics. + // An unsupported expression still has one fallback estimate and one runtime owner. + if (info.from_logical_filter && !CanBuildEqualityClosure() && !CanBuildSelectivityDomain()) { + return true; + } + if (info.set.get().count < 2 && !info.source_operator_index.IsValid()) { + return false; + } + return info.must_remain_filter || info.from_residual_predicate || + (info.filter && info.filter->GetExpressionType() == ExpressionType::CONJUNCTION_OR); +} + void JoinPredicate::SetEqualityClassIndex(optional_idx equality_class_index) { this->equality_class_index = equality_class_index; filter.get().edge_equivalence_index = equality_class_index; 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 63ccb9b7c..70f8ba9cc 100644 --- a/src/duckdb/src/optimizer/join_order/join_relation_set.cpp +++ b/src/duckdb/src/optimizer/join_order/join_relation_set.cpp @@ -1,7 +1,6 @@ #include "duckdb/optimizer/join_order/join_relation_set.hpp" #include "duckdb/common/printer.hpp" #include "duckdb/common/string_util.hpp" -#include "duckdb/common/to_string.hpp" #include "duckdb/common/types/hash.hpp" #include @@ -26,8 +25,9 @@ JoinRelationSet::JoinRelationSet(unsafe_unique_array relations, i // LCOV_EXCL_START string JoinRelationSet::ToString() const { string result = "["; - result += StringUtil::Join(relations, count, ", ", - [](const RelationIndex &relation) { return to_string(relation.index); }); + result += StringUtil::Join(relations, count, ", ", [](const RelationIndex &relation) { + return StringUtil::Format("%llu", relation.index); + }); result += "]"; return result; } @@ -37,6 +37,11 @@ bool JoinRelationSet::Empty() const { return count == 0; } +bool JoinRelationSet::Contains(RelationIndex relation) const { + auto word = relation.index / BITMASK_WORD_SIZE; + return word < bitmask.size() && (bitmask[word] & (idx_t(1) << (relation.index % BITMASK_WORD_SIZE))) != 0; +} + //! Returns true if sub is a subset of super bool JoinRelationSet::IsSubset(const JoinRelationSet &super, const JoinRelationSet &sub) { D_ASSERT(sub.count > 0); @@ -82,6 +87,13 @@ JoinRelationSet &JoinRelationSetManager::GetJoinRelation(unsafe_unique_arraysecond; + if (set.count == 1 && set.relations[0] == index) { + return set; + } + } // create a sorted vector of the relations auto relations = make_unsafe_uniq_array(1); relations[0] = index; diff --git a/src/duckdb/src/optimizer/join_order/query_graph.cpp b/src/duckdb/src/optimizer/join_order/query_graph.cpp index 93b71fffe..ddef03b7c 100644 --- a/src/duckdb/src/optimizer/join_order/query_graph.cpp +++ b/src/duckdb/src/optimizer/join_order/query_graph.cpp @@ -18,7 +18,7 @@ static string QueryEdgeToString(const QueryEdge *info, vector pre string result = ""; string source = "["; for (idx_t i = 0; i < prefix.size(); i++) { - source += to_string(prefix[i].index) + (i < prefix.size() - 1 ? ", " : ""); + source += StringUtil::Format("%llu%s", prefix[i].index, i < prefix.size() - 1 ? ", " : ""); } source += "]"; for (auto &entry : info->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 d7fad5332..1a9bb336b 100644 --- a/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp @@ -1,5 +1,6 @@ #include "duckdb/optimizer/join_order/query_graph_manager.hpp" #include "duckdb/optimizer/join_order/join_order_optimizer.hpp" +#include "duckdb/optimizer/join_order/cardinality_estimator.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" #include "duckdb/common/assert.hpp" @@ -255,11 +256,14 @@ bool QueryGraphManager::Build(JoinOrderOptimizer &optimizer, LogicalOperator &op // filter operators. auto can_reorder = relation_manager.ExtractJoinRelations(optimizer, op, filter_operators); auto num_relations = relation_manager.NumRelations(); - if (num_relations <= 1 || !can_reorder) { - // nothing to optimize/reorder + if (num_relations <= 1 || !relation_manager.HasCompleteStats()) { return false; } PreparePredicateModel(op); + if (!can_reorder) { + // Keep the complete model available for statistics without enumerating a different join order. + return false; + } BuildInnerCompanionSets(); CreateHyperGraphEdges(); return true; @@ -284,6 +288,11 @@ bool QueryGraphManager::BuildForEstimation(RelationStatsExtractor &extractor, Lo } }); for (auto expr_class : {ExpressionClass::BOUND_REF, ExpressionClass::BOUND_SUBQUERY}) { + if (expr_class == ExpressionClass::BOUND_REF && + filter.get().type == LogicalOperatorType::LOGICAL_FILTER) { + // Positional root filters stay with the generic operator statistics owner. + continue; + } ExpressionIterator::VisitExpressionClass(**expr, expr_class, [&](const Expression &) { valid_bindings = false; }); } @@ -293,12 +302,6 @@ bool QueryGraphManager::BuildForEstimation(RelationStatsExtractor &extractor, Lo } } PreparePredicateModel(op); - for (auto &filter : filters_and_bindings) { - // Single-relation root filters need to be estimated outside the join region. - if (filter->from_logical_filter && filter->set.get().count < 2) { - return false; - } - } return true; } @@ -307,6 +310,7 @@ void QueryGraphManager::PreparePredicateModel(LogicalOperator &op) { auto extraction = relation_manager.ExtractEdges(op, filter_operators, set_manager); filters_and_bindings = std::move(extraction.filters); join_operators = std::move(extraction.join_operators); + extracted_filter_expressions = std::move(extraction.extracted_filter_expressions); JoinOrderConflictDetector::Build(join_operators, set_manager, relation_manager.relation_mapping); candidate_constraints.clear(); for (auto &join_operator : join_operators) { @@ -337,111 +341,25 @@ void QueryGraphManager::PreparePredicateModel(LogicalOperator &op) { BuildPredicateModel(); } -optional QueryGraphManager::CombineRelationStats(const vector &bindings, - const vector &relation_stats, - idx_t root_cardinality) const { - vector> inputs; - for (auto &stats : relation_stats) { - inputs.push_back(stats); - } - return CombineRelationStats(bindings, inputs, root_cardinality); -} - -static column_binding_map_t -GetEqualityDomainBounds(const vector &equality_classes, - const column_binding_map_t> &source_columns) { - column_binding_map_t equality_bounds; - for (auto &equality_class : equality_classes) { - idx_t current_domain = NumericLimits::Maximum(); - bool complete = !equality_class.columns.empty(); - for (auto &binding : equality_class.columns) { - auto column = source_columns.find(binding); - if (column == source_columns.end()) { - complete = false; - break; - } - current_domain = MinValue(current_domain, column->second.get().current_domain.distinct_count); - } - if (!complete) { - continue; - } - for (auto &binding : equality_class.columns) { - auto entry = equality_bounds.find(binding); - if (entry == equality_bounds.end()) { - equality_bounds.emplace(binding, current_domain); - } else { - entry->second = MinValue(entry->second, current_domain); - } - } - } - return equality_bounds; -} - -static RelationColumnStats CombineColumnStats(const ColumnBinding &binding, const ColumnBinding &normalized, - const RelationColumnStats &source, - const column_binding_map_t &equality_bounds, - bool preserve_semi_anti_evidence) { - SemiAntiJoinDomainEvidence semi_anti_evidence; - if (preserve_semi_anti_evidence) { - semi_anti_evidence = source.semi_anti_join_domain_evidence; - } - RelationColumnStats column(binding, source.total_domain, source.current_domain, source.name, semi_anti_evidence); - auto equality_entry = equality_bounds.find(normalized); - if (equality_entry != equality_bounds.end()) { - column.current_domain = DistinctCount(MinValue(column.current_domain.distinct_count, equality_entry->second), - DistinctCountSource::CARDINALITY); - } - column.current_domain.distinct_count = - MinValue(column.current_domain.distinct_count, column.total_domain.distinct_count); - return column; -} - -optional QueryGraphManager::CombineRelationStats(const vector &bindings, - const vector> &inputs, - idx_t root_cardinality) const { - RelationStats result; - result.cardinality = root_cardinality; - if (inputs.size() == 1) { - result.row_retention = inputs[0].get().row_retention; - } - result.stats_initialized = true; - column_binding_map_t> source_columns; - for (auto &input : inputs) { - auto &stats = input.get(); - if (!stats.stats_initialized) { - return {}; - } -#ifdef DEBUG - if (!result.table_name.empty()) { - result.table_name = Identifier(result.table_name + " joined with "); - } - result.table_name = Identifier(result.table_name + stats.table_name); -#endif - for (auto &column : stats.columns) { - ColumnBinding normalized; - if (!relation_manager.TryNormalizeBinding(column.binding, normalized)) { - return {}; - } - source_columns.emplace(normalized, column); - } - } - - auto equality_bounds = GetEqualityDomainBounds(predicate_model.GetEqualityClasses(), source_columns); +optional QueryGraphManager::ProjectStats(CardinalityEstimator &estimator, JoinRelationSet &set, + const vector &bindings) const { + vector normalized; + normalized.reserve(bindings.size()); for (auto &binding : bindings) { - ColumnBinding normalized; - if (!relation_manager.TryNormalizeBinding(binding, normalized)) { + ColumnBinding result; + if (!relation_manager.TryNormalizeBinding(binding, result)) { return {}; } - auto source_entry = source_columns.find(normalized); - if (source_entry == source_columns.end()) { - return {}; + normalized.push_back(result); + } + auto stats = estimator.ProjectStats(set, normalized); + if (stats) { + for (idx_t i = 0; i < bindings.size(); i++) { + stats->columns[i].binding = bindings[i]; } - result.columns.push_back( - CombineColumnStats(binding, normalized, source_entry->second.get(), equality_bounds, inputs.size() == 1)); + stats->Verify(bindings); } - result.CapCurrentDomainsToCardinality(); - result.Verify(bindings); - return result; + return stats; } const JoinPredicateModel &QueryGraphManager::GetPredicateModel() const { @@ -649,6 +567,7 @@ static unique_ptr ExtractJoinRelation(unique_ptr> retired_expressions; for (auto &operator_ref : filter_operators) { auto &op = operator_ref.get(); if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN || @@ -658,13 +577,17 @@ void QueryGraphManager::ClearExtractedExpressions() { } vector> remaining_expressions; for (auto &expression : op.expressions) { - unordered_set bindings; - if (!relation_manager.ExtractFilterBindings(*expression, bindings)) { + if (!extracted_filter_expressions.count(*expression)) { remaining_expressions.push_back(std::move(expression)); + } else { + // Set entries borrow the originals until every operator has been inspected. + retired_expressions.push_back(std::move(expression)); } } op.expressions = std::move(remaining_expressions); } + // Clear borrowed references before destroying the retired originals. Reconstruction owns their normalized copies. + extracted_filter_expressions.clear(); } vector> QueryGraphManager::GetPendingFilters(JoinRelationSet &root) const { @@ -696,25 +619,70 @@ vector> QueryGraphManager::GetPendingFilters(JoinRelationS return result; } -GenerateJoinRelation QueryGraphManager::Reconstruct(unique_ptr plan, - const vector &relation_stats) { - // now we have to rewrite the plan - bool root_is_join = plan->children.size() > 1; - // find the operator whose child is replaced by the new join tree - optional_ptr> parent; - vector old_child_bindings; +static LogicalOperator &FindJoinRoot(LogicalOperator &plan, vector> &ancestors) { + optional_ptr root = plan; + while (root->children.size() == 1) { + ancestors.push_back(*root); + root = *root->children[0]; + } + D_ASSERT(root->children.size() == 2); + return *root; +} + +RelationStats QueryGraphManager::ApplyAncestorStats(const vector> &ancestors, + RelationStats stats, PlanEstimateUpdate update_estimates) { + for (auto ancestor = ancestors.rbegin(); ancestor != ancestors.rend(); ++ancestor) { + auto &op = ancestor->get(); + optional output_stats; + if (!extracted_filter_expressions.empty() && op.type == LogicalOperatorType::LOGICAL_FILTER) { + // Only expressions outside this extracted region remain owned by the ancestor FILTER. + vector> remaining; + for (auto &expression : op.expressions) { + if (!extracted_filter_expressions.count(*expression)) { + remaining.push_back(expression->Copy()); + } + } + output_stats = RelationStatisticsHelper::ExtractFilterStats(op.Cast(), stats, remaining); + } else { + vector> input {stats}; + output_stats = RelationStatisticsHelper::ExtractOperatorStats(op, context, input); + } + if (!output_stats) { + return RelationStats(); + } + stats = std::move(*output_stats); + if (update_estimates == PlanEstimateUpdate::UPDATE) { + op.SetEstimatedCardinality(stats.GetCardinalityForPlan()); + } + } + return stats; +} + +optional QueryGraphManager::ProjectRetainedStats(CardinalityEstimator &estimator, JoinRelationSet &set, + LogicalOperator &plan, + PlanEstimateUpdate update_estimates) { vector> ancestors; - if (!root_is_join) { - D_ASSERT(plan->children.size() == 1); + auto &join = FindJoinRoot(plan, ancestors); + auto stats = ProjectStats(estimator, set, join.GetColumnBindings()); + if (!stats) { + return {}; + } + auto result = ApplyAncestorStats(ancestors, std::move(*stats), update_estimates); + return result.stats_initialized ? optional(std::move(result)) : optional(); +} + +GenerateJoinRelation QueryGraphManager::Reconstruct(unique_ptr plan, CardinalityEstimator &estimator) { + vector> ancestors; + FindJoinRoot(*plan, ancestors); + optional_ptr> parent; + if (!ancestors.empty()) { parent = &plan; - ancestors.push_back(**parent); - while ((*parent)->children[0]->type != LogicalOperatorType::LOGICAL_CROSS_PRODUCT && - (*parent)->children[0]->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN && - (*parent)->children[0]->type != LogicalOperatorType::LOGICAL_ASOF_JOIN) { - D_ASSERT((*parent)->children[0]->children.size() == 1); + for (idx_t i = 1; i < ancestors.size(); i++) { parent = &(*parent)->children[0]; - ancestors.push_back(**parent); } + } + vector old_child_bindings; + if (parent) { old_child_bindings = (*parent)->children[0]->GetColumnBindings(); } ClearExtractedExpressions(); @@ -734,7 +702,7 @@ GenerateJoinRelation QueryGraphManager::Reconstruct(unique_ptr // now we generate the actual joins auto pending_filters = GetPendingFilters(total_relation); - auto join_tree = GenerateJoins(extracted_relations, total_relation, relation_stats, pending_filters); + auto join_tree = GenerateJoins(extracted_relations, total_relation, estimator, pending_filters); for (auto &join_operator : join_operators) { if (JoinOrderConflictDetector::MustApplyAsOperator(*join_operator) && !reconstructed_operators.count(join_operator->index)) { @@ -757,10 +725,10 @@ GenerateJoinRelation QueryGraphManager::Reconstruct(unique_ptr join_tree.op = PushFilter(std::move(join_tree.op), std::move(filter->filter)); } } - join_tree.op->SetEstimatedCardinality(join_tree.stats.cardinality); + join_tree.op->SetEstimatedCardinality(join_tree.stats.GetCardinalityForPlan()); // find the first join in the relation to know where to place this node - if (root_is_join) { + if (!parent) { // first node is the join, return it immediately return join_tree; } @@ -768,16 +736,7 @@ GenerateJoinRelation QueryGraphManager::Reconstruct(unique_ptr (*parent)->children[0] = std::move(join_tree.op); // the new join tree can emit its columns in a different order: preserve the parent's output layout ColumnBindingRewrite::ApplyToChild(*parent, 0, std::move(old_child_bindings), BindingReplacementGraph()); - for (auto ancestor = ancestors.rbegin(); ancestor != ancestors.rend(); ++ancestor) { - vector> input {join_tree.stats}; - auto output_stats = RelationStatisticsHelper::ExtractOperatorStats(ancestor->get(), context, input); - if (!output_stats) { - join_tree.stats = RelationStats(); - break; - } - join_tree.stats = std::move(*output_stats); - ancestor->get().SetEstimatedCardinality(join_tree.stats.cardinality); - } + join_tree.stats = ApplyAncestorStats(ancestors, std::move(join_tree.stats), PlanEstimateUpdate::UPDATE); join_tree.op = std::move(plan); return join_tree; } @@ -857,7 +816,7 @@ static void OrientInnerConditions(RelationManager &relation_manager, JoinRelatio } GenerateJoinRelation QueryGraphManager::GenerateJoins(vector> &extracted_relations, - JoinRelationSet &set, const vector &relation_stats, + JoinRelationSet &set, CardinalityEstimator &estimator, const vector> &pending_filters) { optional_ptr left_node; optional_ptr right_node; @@ -870,11 +829,10 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorsecond; - auto result_cardinality = node->cardinality.GetIndex(); if (!dp_entry->second->is_leaf) { // generate the left and right children - 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 left = GenerateJoins(extracted_relations, node->left_set, estimator, pending_filters); + auto right = GenerateJoins(extracted_relations, node->right_set, estimator, pending_filters); auto descriptor = node->join_operator; if (descriptor) { D_ASSERT(descriptor->type == JoinOrderOperatorType::CROSS_PRODUCT || @@ -979,37 +937,13 @@ 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) { - 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); - } } else { // base node, get the entry from the list of extracted relations D_ASSERT(node->set.count == 1); D_ASSERT(extracted_relations[node->set.relations[0].index]); result_relation = &node->set; result_operator = std::move(extracted_relations[result_relation->relations[0].index]); - vector> inputs {relation_stats[result_relation->relations[0].index]}; - result_stats = CombineRelationStats(result_operator->GetColumnBindings(), inputs, result_cardinality); } - // TODO: this is where estimated properties start coming into play. - // when creating the result operator, we should ask the cost model and cardinality estimator what - // the cost and cardinality are - result_operator->estimated_cardinality = result_cardinality; - result_operator->has_estimated_cardinality = true; // Collect unused residual predicates that belong to this join. Semantic non-inner joins own their complete // condition directly, so only ordinary (notably INNER) residual predicates reach this path. Predicates that @@ -1139,13 +1073,16 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorSetEstimatedCardinality(result_cardinality); + result_stats = ProjectStats(estimator, set, result_operator->GetColumnBindings()); RelationStats output_stats; if (result_stats) { output_stats = std::move(*result_stats); output_stats.Verify(result_operator->GetColumnBindings()); + } else { + output_stats.cardinality = node->cardinality; } - output_stats.cardinality = result_cardinality; + D_ASSERT(output_stats.GetCardinality() == node->cardinality); + result_operator->SetEstimatedCardinality(output_stats.GetCardinalityForPlan()); return GenerateJoinRelation(result_relation, std::move(result_operator), std::move(output_stats)); } diff --git a/src/duckdb/src/optimizer/join_order/relation_manager.cpp b/src/duckdb/src/optimizer/join_order/relation_manager.cpp index cdec24fa5..2a90dee47 100644 --- a/src/duckdb/src/optimizer/join_order/relation_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/relation_manager.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/enums/join_type.hpp" #include "duckdb/common/enums/logical_operator_type.hpp" #include "duckdb/common/string_util.hpp" +#include "duckdb/optimizer/distinctness.hpp" #include "duckdb/optimizer/join_order/join_order_optimizer.hpp" #include "duckdb/optimizer/join_order/join_relation_set.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" @@ -42,6 +43,18 @@ const join_column_sources_t &RelationManager::GetColumnSources() const { static bool OperatorNeedsRelation(LogicalOperatorType op_type); static bool OperatorIsNonReorderable(const LogicalOperator &op); +static RelationStats RecursiveReferenceStats(const RelationStats &input, CardinalityValue rows) { + // The seed and one term do not constrain values, keys or NULLs in later iterations. + RelationStats result; + result.cardinality = rows; + result.stats_initialized = input.stats_initialized; + result.table_name = input.table_name; + for (auto &column : input.columns) { + result.columns.emplace_back(column.binding, DistinctCount(rows, DistinctCountSource::CARDINALITY), column.name); + } + return result; +} + static bool CanReuseAlignedStats(const LogicalOperator &op) { if (OperatorNeedsRelation(op.type) || OperatorIsNonReorderable(op)) { return true; @@ -81,7 +94,7 @@ bool RelationManager::AddRelation(LogicalOperator &op, optional_ptrstats.cardinality); + op.SetEstimatedCardinality(relations.back()->stats.GetCardinalityForPlan()); return true; } @@ -93,58 +106,6 @@ const SingleJoinRelation &RelationManager::GetRelation(RelationIndex index) cons return *relations.at(index.index); } -//! The output columns of an operator that together identify a row: the groups of an aggregate, seen through the -//! filters and projections above it. Empty when the operator has no such key. -static vector FindUniqueKey(LogicalOperator &op) { - switch (op.type) { - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { - auto &aggregate = op.Cast(); - // An absent grouping-set list denotes the single set containing all groups. - if (aggregate.groups.empty() || aggregate.grouping_sets.size() > 1 || - (aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() != aggregate.groups.size())) { - return {}; - } - vector key; - for (idx_t group_idx = 0; group_idx < aggregate.groups.size(); group_idx++) { - key.emplace_back(aggregate.group_index, ProjectionIndex(group_idx)); - } - return key; - } - case LogicalOperatorType::LOGICAL_FILTER: { - auto key = FindUniqueKey(*op.children[0]); - // A projection map can remove key columns. - auto bindings = op.GetColumnBindings(); - for (auto &binding : key) { - if (std::find(bindings.begin(), bindings.end(), binding) == bindings.end()) { - return {}; - } - } - return key; - } - case LogicalOperatorType::LOGICAL_PROJECTION: { - auto &projection = op.Cast(); - vector key; - for (auto &binding : FindUniqueKey(*op.children[0])) { - optional_idx projected; - for (idx_t i = 0; i < projection.expressions.size() && !projected.IsValid(); i++) { - auto &expression = *projection.expressions[i]; - if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && - expression.Cast().Binding() == binding) { - projected = i; - } - } - if (!projected.IsValid()) { - return {}; - } - key.emplace_back(projection.table_index, ProjectionIndex(projected.GetIndex())); - } - return key; - } - default: - return {}; - } -} - bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptr parent, RelationStats stats) { D_ASSERT(!parent || parent->children.size() >= 2); if (!stats.stats_initialized || !stats.MatchesBindings(op.GetColumnBindings())) { @@ -157,14 +118,28 @@ bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptrrecursive_properties.depends_on_recursive_input; } RelationIndex relation_id(relations.size()); - relation->stats.unique_key.clear(); - for (auto &binding : FindUniqueKey(op)) { - auto column = relation->stats.FindColumn(binding); - if (!column.IsValid()) { - relation->stats.unique_key.clear(); - break; + Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS, context); + auto &unique_sets = distinctness.GetUniqueSets(op); + auto &unique_keys = relation->stats.unique_keys; + unique_keys.clear(); + unique_keys.reserve(MinValue(unique_sets.size(), Distinctness::MAX_UNIQUE_SETS)); + for (auto &bindings : unique_sets) { + vector key; + key.reserve(bindings.size()); + for (auto &binding : bindings) { + auto column = relation->stats.FindColumn(binding); + if (!column.IsValid()) { + key.clear(); + break; + } + key.push_back(column.GetIndex()); + } + if (!key.empty()) { + unique_keys.push_back(std::move(key)); + if (unique_keys.size() == Distinctness::MAX_UNIQUE_SETS) { + break; + } } - relation->stats.unique_key.push_back(column.GetIndex()); } unordered_set relation_bindings; @@ -202,6 +177,8 @@ bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptr input_bindings; for (idx_t child_idx = 0; child_idx < op.children.size(); child_idx++) { @@ -226,9 +203,34 @@ static bool HasVisibleEstimationInputs(LogicalOperator &op) { } }); }); - // Conflict preparation needs both INNER inputs; the join's output maps do not hide its predicate inputs. - return valid_bindings && - (op.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN || referenced_children.size() == 2); + if (!valid_bindings || + (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && referenced_children.size() != 2)) { + return false; + } + if (op.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN || + op.Cast().join_type != JoinType::LEFT) { + return true; + } + // LEFT costing needs a comparison between the semantic inputs. Conditions that normalize to + // residuals alone cannot prepare that boundary. Output maps do not hide predicate inputs. + auto operand_inputs = [&](const Expression &expression) { + idx_t mask = 0; + ExpressionIterator::VisitExpression( + expression, + [&](const BoundColumnRefExpression &column) { mask |= idx_t(1) << input_bindings.at(column.Binding()); }); + return mask; + }; + for (auto &condition : op.Cast().conditions) { + if (!condition.IsComparison()) { + continue; + } + auto left = operand_inputs(condition.GetLHS()); + auto right = operand_inputs(condition.GetRHS()); + if ((left == 1 && right == 2) || (left == 2 && right == 1)) { + return true; + } + } + return false; } bool RelationManager::ExtractJoinRelationsForEstimation(RelationStatsExtractor &extractor, LogicalOperator &op, @@ -244,15 +246,28 @@ bool RelationManager::ExtractJoinRelationsForEstimation(RelationStatsExtractor & } auto is_inner = op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && op.Cast().join_type == JoinType::INNER; - if (is_inner || op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + auto is_left = op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + op.Cast().join_type == JoinType::LEFT; + if (is_inner || is_left || op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { if (!HasVisibleEstimationInputs(op)) { return false; } - if (is_inner) { + if (is_left && !HasStableJoinInputs(op.Cast())) { + return false; + } + if (is_inner || is_left) { filter_operators.push_back(op); } - return ExtractJoinRelationsForEstimation(extractor, *op.children[0], filter_operators, op) && - ExtractJoinRelationsForEstimation(extractor, *op.children[1], filter_operators, op); + if (!ExtractJoinRelationsForEstimation(extractor, *op.children[0], filter_operators, op)) { + return false; + } + if (is_left) { + // A non-inner boundary owns its entire RHS, including any joins within that subtree. + auto &right = *op.children[1]; + auto stats = extractor.Extract(right); + return stats && RegisterRelation(right, op, *stats); + } + return ExtractJoinRelationsForEstimation(extractor, *op.children[1], filter_operators, op); } auto stats = extractor.Extract(op); return stats && RegisterRelation(op, parent, *stats); @@ -396,6 +411,19 @@ static bool ContainsRecurringCTERef(const LogicalOperator &op) { return false; } +static bool HasStableJoinInputs(LogicalComparisonJoin &join) { + // Preserve the input rows on which volatile condition operands are evaluated. + for (auto &cond : join.conditions) { + bool is_volatile = cond.IsComparison() ? cond.GetLHS().IsVolatile() || cond.GetRHS().IsVolatile() + : cond.GetJoinExpression().IsVolatile(); + if (is_volatile) { + return false; + } + } + return (join.join_type != JoinType::LEFT && join.join_type != JoinType::SEMI && join.join_type != JoinType::ANTI) || + !ContainsRecurringCTERef(*join.children[1]); +} + static bool JoinIsReorderable(LogicalOperator &op, bool has_throwing_predicate) { if (op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { return true; @@ -430,17 +458,7 @@ static bool JoinIsReorderable(LogicalOperator &op, bool has_throwing_predicate) return false; } } - // Preserve the input rows on which volatile condition operands are evaluated. - for (auto &cond : join.conditions) { - bool is_volatile = cond.IsComparison() ? cond.GetLHS().IsVolatile() || cond.GetRHS().IsVolatile() - : cond.GetJoinExpression().IsVolatile(); - if (is_volatile) { - return false; - } - } - if ((join.join_type == JoinType::LEFT || join.join_type == JoinType::SEMI || - join.join_type == JoinType::ANTI) && - ContainsRecurringCTERef(*join.children[1])) { + if (!HasStableJoinInputs(join)) { return false; } switch (join.join_type) { @@ -585,17 +603,16 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending vector> &filter_operators, vector &pending_relations) { if (relation.optimize_as_leaf) { - // This job follows the left subtree, preserving relation numbering and the RHS boundary. + // The semantic RHS is optimized once, retaining the upstream relation numbering. auto &join = *relation.parent; RelationStats child_stats; auto child_optimizer = optimizer.CreateChildOptimizer(); OptimizeChild(child_optimizer, join, 1, &child_stats); - if (!AddRelation(*join.children[1], join, child_stats)) { + // child_stats already describes the optimized root, including its FILTERs. + if (!RegisterRelation(*join.children[1], join, std::move(child_stats))) { return false; } - for (auto &binding : join.children[1]->GetColumnBindings()) { - relation_mapping[binding.table_index] = RelationIndex(relations.size() - 1); - } + join.children[1]->SetEstimatedCardinality(relations.back()->stats.GetCardinalityForPlan()); return true; } auto &input_op = relation.op; @@ -607,6 +624,19 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending // 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) { + // Bind positions before optimizing children can change their output layout. + // Read-only extraction binds its copies in ExtractEdges instead. + vector bindings; + for (auto &expression : op->expressions) { + ExpressionIterator::VisitExpressionMutable( + expression, [&](BoundReferenceExpression &ref, unique_ptr &child) { + if (bindings.empty()) { + bindings = op->children[0]->GetColumnBindings(); + } + child = make_uniq(ref.GetAlias(), ref.GetReturnType(), + bindings.at(ref.Index())); + }); + } unary_filters.push_back(*op); for (auto &expression : op->expressions) { has_throwing_predicate |= expression->CanThrow(); @@ -652,7 +682,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending stats_complete = false; return false; } - op->SetEstimatedCardinality(combined_stats->cardinality); + op->SetEstimatedCardinality(combined_stats->GetCardinalityForPlan()); return AddRelation(input_op, parent, *combined_stats); } @@ -664,13 +694,13 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending OptimizeChild(child_optimizer, *op, 0, &child_stats); auto &aggr = op->Cast(); RelationStatsExtractor extractor(context, optimizer.GetSourceStats()); - auto operator_stats = RelationStatisticsHelper::ExtractAggregationStats(aggr, child_stats, extractor, true); + auto operator_stats = RelationStatisticsHelper::ExtractAggregationStats(aggr, child_stats, extractor); if (!operator_stats) { stats_complete = false; return false; } // the extracted cardinality should be set for aggregate - aggr.SetEstimatedCardinality(operator_stats->cardinality); + aggr.SetEstimatedCardinality(operator_stats->GetCardinalityForPlan()); return AddRelation(input_op, parent, *operator_stats); } case LogicalOperatorType::LOGICAL_WINDOW: { @@ -685,7 +715,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending return false; } // the extracted cardinality should be set for window - window.SetEstimatedCardinality(operator_stats->cardinality); + window.SetEstimatedCardinality(operator_stats->GetCardinalityForPlan()); return AddRelation(input_op, parent, *operator_stats); } case LogicalOperatorType::LOGICAL_SECURE_VIEW: { @@ -697,12 +727,14 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending auto &secure_view = op->Cast(); RelationStats stats; stats.cardinality = secure_view.EstimateCardinality(context); - secure_view.SetEstimatedCardinality(stats.cardinality); stats.table_name = Identifier(secure_view.view_name); stats.stats_initialized = true; if (secure_view.propagate_statistics) { + stats.cardinality = child_stats.cardinality; + stats.max_cardinality = child_stats.max_cardinality; stats.row_retention = child_stats.row_retention; } + secure_view.SetEstimatedCardinality(stats.GetCardinalityForPlan()); RelationColumnStatsLookup child_columns(child_stats); for (auto &binding : secure_view.GetColumnBindings()) { auto child_column = child_columns.Find(binding); @@ -711,7 +743,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending stats.columns.emplace_back(binding, child_column->total_domain, child_column->current_domain, std::move(name), child_column->semi_anti_join_domain_evidence); } else { - DistinctCount domain(MaxValue(stats.cardinality, 1), DistinctCountSource::CARDINALITY); + DistinctCount domain(stats.GetCardinality(), DistinctCountSource::CARDINALITY); stats.columns.emplace_back(binding, domain, std::move(name)); } } @@ -773,7 +805,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending auto stats = captured ? *captured : RelationStatisticsHelper::ExtractGetStats(get, context); // if there is another logical filter that could not be pushed down into the // table scan, apply another selectivity. - get.SetEstimatedCardinality(stats.cardinality); + get.SetEstimatedCardinality(stats.GetCardinalityForPlan()); return AddRelation(input_op, parent, stats); } case LogicalOperatorType::LOGICAL_PROJECTION: { @@ -788,7 +820,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending stats_complete = false; return false; } - proj.SetEstimatedCardinality(proj_stats->cardinality); + proj.SetEstimatedCardinality(proj_stats->GetCardinalityForPlan()); if (!AddRelation(input_op, parent, *proj_stats)) { return false; } @@ -803,7 +835,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending auto &empty_result = op->Cast(); // Projection can create columns so we need to add them here auto stats = RelationStatisticsHelper::ExtractEmptyResultStats(empty_result); - empty_result.SetEstimatedCardinality(stats.cardinality); + empty_result.SetEstimatedCardinality(stats.GetCardinalityForPlan()); return AddRelation(input_op, parent, stats); } case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: @@ -817,6 +849,9 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending auto table_index = op->Cast().table_index; auto child_1_card = lhs_stats.stats_initialized ? lhs_stats.cardinality : 0; + if (op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + lhs_stats = RecursiveReferenceStats(lhs_stats, child_1_card); + } rhs_optimizer.AddMaterializedCTEStats(table_index, std::move(lhs_stats)); if (op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { rhs_optimizer.recursive_cte_indexes.insert(op->Cast().table_index); @@ -826,7 +861,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending // create the stats for the CTE auto child_2_card = rhs_stats.stats_initialized ? rhs_stats.cardinality : 0; - idx_t cte_cardinality; + CardinalityValue cte_cardinality; if (op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { // we cannot really estimate the cardinality of a recursive CTE @@ -839,22 +874,14 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending } else { throw InternalException("Unexpected CTE type in join order optimizer"); } - op->SetEstimatedCardinality(cte_cardinality); auto output_stats = RelationStatisticsHelper::ProjectOutputStats(rhs_stats, input_op); if (!output_stats) { output_stats = RelationStatisticsHelper::RebindOutputStats(rhs_stats, input_op); } if (output_stats && op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { - output_stats->cardinality = cte_cardinality; - output_stats->row_retention = 1; - // Statistics from one recursive term do not describe the complete fixpoint. Keep the output layout, but - // represent each fixpoint domain using the standard cardinality-based fallback. - for (auto &column : output_stats->columns) { - column.total_domain = DistinctCount(cte_cardinality, DistinctCountSource::CARDINALITY); - column.current_domain = column.total_domain; - column.semi_anti_join_domain_evidence.Invalidate(); - } + output_stats = RecursiveReferenceStats(*output_stats, cte_cardinality); } + op->SetEstimatedCardinality(output_stats ? output_stats->GetCardinalityForPlan() : cte_cardinality.GetIndex()); if (!output_stats || !AddRelation(input_op, parent, *output_stats)) { stats_complete = false; } @@ -869,7 +896,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending stats_complete = false; return false; } - cte_ref.SetEstimatedCardinality(cte_stats.cardinality); + cte_ref.SetEstimatedCardinality(cte_stats.GetCardinalityForPlan()); if (!AddRelation(input_op, parent, *rebound_stats)) { return false; } @@ -901,8 +928,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending dummy_aggr->groups.push_back(delim_col->Copy()); } RelationStatsExtractor extractor(context, optimizer.GetSourceStats()); - auto lhs_delim_stats = - RelationStatisticsHelper::ExtractAggregationStats(*dummy_aggr, lhs_stats, extractor, true); + auto lhs_delim_stats = RelationStatisticsHelper::ExtractAggregationStats(*dummy_aggr, lhs_stats, extractor); if (!lhs_delim_stats) { stats_complete = false; return false; @@ -959,10 +985,11 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending stats_complete = false; return false; } - op->SetEstimatedCardinality(delim_scan_stats.cardinality); + op->SetEstimatedCardinality(delim_scan_stats.GetCardinalityForPlan()); return AddRelation(input_op, parent, *rebound_stats); } default: + stats_complete = false; return false; } } @@ -1062,11 +1089,14 @@ bool RelationManager::ExtractBindings(const Expression &expression, unordered_se bool RelationManager::ExtractFilterBindings(const Expression &expression, unordered_set &bindings) { const auto can_reorder = ExtractBindings(expression, bindings); + if (!can_reorder) { + return false; + } if (!bindings.empty()) { return true; } // without bindings the filter can only move if it references no columns at all - return can_reorder && !ExpressionContainsColumnRef(expression); + return !ExpressionContainsColumnRef(expression); } JoinOrderExtraction RelationManager::ExtractEdges(LogicalOperator &op, @@ -1289,16 +1319,28 @@ JoinOrderExtraction RelationManager::ExtractEdges(LogicalOperator &op, } else { // handle filters from logical filters + vector input_bindings; for (auto &expression : f_op.expressions) { + auto copy = expression->Copy(); + ExpressionIterator::VisitExpressionMutable( + copy, [&](BoundReferenceExpression &ref, unique_ptr &child) { + if (input_bindings.empty()) { + input_bindings = f_op.children[0]->GetColumnBindings(); + } + child = make_uniq(ref.GetAlias(), ref.GetReturnType(), + input_bindings.at(ref.Index())); + }); unordered_set bindings; - if (!ExtractFilterBindings(*expression, bindings)) { + if (!ExtractFilterBindings(*copy, bindings)) { // the filter is on a column that is not in our relational map. (example: limit_rownum) // in this case we do not create a FilterInfo for it. (duckdb-internal/#1493) continue; } - if (is_new_filter(*expression)) { + // Keep original ownership separate from normalized, deduplicated statistics predicates. + result.extracted_filter_expressions.insert(*expression); + if (is_new_filter(*copy)) { auto &set = set_manager.GetJoinRelation(bindings); - auto filter_info = make_uniq(expression->Copy(), set, filters_and_bindings.size()); + auto filter_info = make_uniq(std::move(copy), set, filters_and_bindings.size()); filter_info->from_logical_filter = true; if (ExpressionBarrier::Contains(*expression)) { // the barrier must not end up below one of the joins we are reordering @@ -1413,13 +1455,13 @@ void RelationManager::PrintRelationStats() { auto &relation = relations.at(i); auto &stats = relation->stats; for (auto &column : stats.columns) { - to_print = column.name + " has estimated current/total domains " + - to_string(column.current_domain.distinct_count) + "/" + - to_string(column.total_domain.distinct_count); + to_print = StringUtil::Format("%s has estimated current/total domains %g/%g", column.name, + column.current_domain.distinct_count.GetDouble(), + column.total_domain.distinct_count.GetDouble()); Printer::Print(to_print); } - to_print = stats.table_name + " has estimated cardinality " + to_string(stats.cardinality); - to_print += " and relation id " + to_string(i) + "\n"; + to_print = StringUtil::Format("%s has estimated cardinality %g and relation id %llu\n", stats.table_name, + stats.cardinality.GetDouble(), i); Printer::Print(to_print); } #endif diff --git a/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp b/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp index c17d407ed..70ff51264 100644 --- a/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp +++ b/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp @@ -745,9 +745,8 @@ static bool DEEstimateCollapse(RelationStatsExtractor &extractor, LogicalCompari return false; } const auto cardinality = stats->cardinality; - const auto join_retains_rows = - static_cast(join.estimated_cardinality) >= - PartialAggregatePushdownHeuristics::MIN_JOIN_RETENTION * static_cast(cardinality); + const auto join_retains_rows = static_cast(join.estimated_cardinality) >= + PartialAggregatePushdownHeuristics::MIN_JOIN_RETENTION * cardinality.GetDouble(); if (!join_retains_rows || cardinality == 0) { return false; } @@ -759,16 +758,17 @@ static bool DEEstimateCollapse(RelationStatsExtractor &extractor, LogicalCompari } groups.push_back(column.GetIndex()); } - lower_cardinalities[side] = RelationStatisticsHelper::EstimateGroupCardinality(*join.children[side], *stats, - std::move(groups), extractor); + const auto lower_cardinality = RelationStatisticsHelper::EstimateGroupCardinality(*join.children[side], *stats, + std::move(groups), extractor); + lower_cardinalities[side] = lower_cardinality.GetIndex(); const auto min_collapse = DERequiredCollapse(lower_cardinalities[side]); const auto input_collapses = cardinality / min_collapse >= lower_cardinalities[side]; both_inputs_collapse &= input_collapses; if (input_collapses) { work_margin = MinValue(work_margin, min_collapse); } - input_cardinality += static_cast(cardinality); - retained_fraction *= static_cast(lower_cardinalities[side]) / static_cast(cardinality); + input_cardinality += cardinality.GetDouble(); + retained_fraction *= (lower_cardinality / cardinality).GetDouble(); } // Scale the join estimate by grouping reduction without interpreting its selectivity as an NDV. const auto cross_product = @@ -1150,12 +1150,12 @@ bool PartialAggregatePushdown::TryOwnerOuterCountPushdown(unique_ptrcardinality; const auto key_count = MinValue(key_stats->total_domain.distinct_count, aggregate_cardinality); if (aggregate_cardinality == 0 || key_count == 0 || - static_cast(aggregate_cardinality) < + aggregate_cardinality.GetDouble() < static_cast(PartialAggregatePushdownHeuristics::MIN_AGGREGATE_TO_DIMENSION_RATIO) * - static_cast(key_count) || + key_count.GetDouble() || !join.children[info.dimension_side]->has_estimated_cardinality || !join.has_estimated_cardinality || static_cast(join.estimated_cardinality) < - PartialAggregatePushdownHeuristics::MIN_JOIN_RETENTION * static_cast(aggregate_cardinality)) { + PartialAggregatePushdownHeuristics::MIN_JOIN_RETENTION * aggregate_cardinality.GetDouble()) { return false; } @@ -1167,7 +1167,7 @@ bool PartialAggregatePushdown::TryOwnerOuterCountPushdown(unique_ptrgroups.push_back((*aggregate_key_expr)->Copy()); lower->children.push_back(std::move(join.children[info.aggregate_side])); lower->ResolveOperatorTypes(); - lower->SetEstimatedCardinality(key_count); + lower->SetEstimatedCardinality(key_count.GetIndex()); auto aggregate_key_type = (*aggregate_key_expr)->GetReturnType(); *aggregate_key_expr = diff --git a/src/duckdb/src/optimizer/pullup/pullup_constraints.cpp b/src/duckdb/src/optimizer/pullup/pullup_constraints.cpp new file mode 100644 index 000000000..73e9f8e86 --- /dev/null +++ b/src/duckdb/src/optimizer/pullup/pullup_constraints.cpp @@ -0,0 +1,136 @@ +#include "duckdb/optimizer/filter_pullup.hpp" +#include "duckdb/optimizer/filter_combiner.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_window_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_window.hpp" + +namespace duckdb { + +unique_ptr FilterPullup::ReturnConstraints(unique_ptr op, + vector> constraints) { + FilterCombiner::DeduplicateFilters(constraints); + if (!can_pullup) { + return GeneratePullupFilter(std::move(op), constraints); + } + for (auto &constraint : constraints) { + filters_expr_pullup.push_back(std::move(constraint)); + } + return op; +} + +unique_ptr FilterPullup::PullupWindow(unique_ptr op) { + if (!can_pullup || op->expressions.empty()) { + return FinishPullup(std::move(op)); + } + vector> keys; + for (idx_t i = 0; i < op->expressions.size(); i++) { + auto &expr = *op->expressions[i]; + if (expr.GetExpressionClass() != ExpressionClass::BOUND_WINDOW || expr.IsVolatile()) { + return FinishPullup(std::move(op)); + } + auto &partitions = expr.Cast().Partitions(); + if (i == 0) { + for (auto &partition : partitions) { + if (FilterCombiner::CanMatchExpression(*partition)) { + keys.push_back(*partition); + } + } + } else { + for (idx_t k = 0; k < keys.size(); k++) { + bool found = false; + for (auto &partition : partitions) { + found |= FilterCombiner::CanMatchExpression(*partition) && keys[k].get().Equals(*partition); + } + if (!found) { + keys.erase_at(k--); + } + } + } + } + if (keys.empty()) { + return FinishPullup(std::move(op)); + } + FilterPullup child_pullup(context, true, false); + op->children[0] = child_pullup.Rewrite(std::move(op->children[0])); + vector> constraints; + for (auto &filter : child_pullup.filters_expr_pullup) { + if (FilterCombiner::IsKeyConstraint(*filter, keys)) { + constraints.push_back(filter->Copy()); + } + } + // Keep partition membership and the rows evaluated by window arguments and frames unchanged. + op->children[0] = GeneratePullupFilter(std::move(op->children[0]), child_pullup.filters_expr_pullup); + return ReturnConstraints(std::move(op), std::move(constraints)); +} + +static void RewriteGroupConstraint(Expression &filter, TableIndex group_index, + const expression_map_t &outputs) { + const auto type = filter.GetExpressionType(); + const bool conjunction = type == ExpressionType::CONJUNCTION_AND || type == ExpressionType::CONJUNCTION_OR || + type == ExpressionType::OPERATOR_NOT; + ExpressionIterator::EnumerateChildren(filter, [&](unique_ptr &child) { + if (conjunction) { + RewriteGroupConstraint(*child, group_index, outputs); + return; + } + child = ExpressionIterator::PreorderReplace( + std::move(child), [&](const Expression &expr) -> unique_ptr { + auto entry = outputs.find(expr); + if (entry == outputs.end()) { + return nullptr; + } + return make_uniq(expr.GetReturnType(), + ColumnBinding(group_index, entry->second)); + }); + }); +} + +unique_ptr FilterPullup::PullupAggregate(unique_ptr op) { + auto &aggregate = op->Cast(); + if (!can_pullup || aggregate.groups.empty()) { + return FinishPullup(std::move(op)); + } + for (auto &expr : aggregate.expressions) { + if (expr->IsVolatile()) { + return FinishPullup(std::move(op)); + } + } + vector> keys; + expression_map_t outputs; + for (idx_t i = 0; i < aggregate.groups.size(); i++) { + auto &group = *aggregate.groups[i]; + if (group.IsFoldable() || group.IsVolatile() || group.CanThrow() || + !FilterCombiner::CanMatchExpression(group)) { + continue; + } + bool common = true; + for (auto &set : aggregate.grouping_sets) { + common &= set.count(ProjectionIndex(i)) != 0; + } + if (common) { + keys.push_back(group); + outputs.emplace(group, ProjectionIndex(i)); + } + } + if (keys.empty()) { + return FinishPullup(std::move(op)); + } + FilterPullup child_pullup(context, true, false); + op->children[0] = child_pullup.Rewrite(std::move(op->children[0])); + vector> constraints; + for (auto &filter : child_pullup.filters_expr_pullup) { + if (!FilterCombiner::IsKeyConstraint(*filter, keys)) { + continue; + } + auto copy = filter->Copy(); + // Keep comparison roots and constants available to the filter combiner. + RewriteGroupConstraint(*copy, aggregate.group_index, outputs); + constraints.push_back(std::move(copy)); + } + op->children[0] = GeneratePullupFilter(std::move(op->children[0]), child_pullup.filters_expr_pullup); + return ReturnConstraints(std::move(op), std::move(constraints)); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp b/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp index 1e93c0903..41c308c85 100644 --- a/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp +++ b/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp @@ -1,4 +1,5 @@ #include "duckdb/optimizer/filter_pullup.hpp" +#include "duckdb/optimizer/filter_combiner.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_join.hpp" @@ -16,11 +17,14 @@ unique_ptr FilterPullup::PullupFromLeft(unique_ptrchildren[0] = left_pullup.Rewrite(std::move(op->children[0])); op->children[1] = right_pullup.Rewrite(std::move(op->children[1])); - // check only for filters from the LHS - if (!left_pullup.filters_expr_pullup.empty() && right_pullup.filters_expr_pullup.empty()) { - return GeneratePullupFilter(std::move(op), left_pullup.filters_expr_pullup); + vector> constraints; + for (auto &filter : left_pullup.filters_expr_pullup) { + if (FilterCombiner::CanCopyFilter(*filter)) { + constraints.push_back(filter->Copy()); + } } - return op; + op->children[0] = GeneratePullupFilter(std::move(op->children[0]), left_pullup.filters_expr_pullup); + return ReturnConstraints(std::move(op), std::move(constraints)); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/pullup/pullup_projection.cpp b/src/duckdb/src/optimizer/pullup/pullup_projection.cpp index 64d14c85d..7a6a8bcb8 100644 --- a/src/duckdb/src/optimizer/pullup/pullup_projection.cpp +++ b/src/duckdb/src/optimizer/pullup/pullup_projection.cpp @@ -1,91 +1,136 @@ #include "duckdb/optimizer/filter_pullup.hpp" +#include "duckdb/optimizer/filter_combiner.hpp" +#include "duckdb/parser/expression_map.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" -#include "duckdb/planner/operator/logical_empty_result.hpp" #include "duckdb/planner/operator/logical_projection.hpp" -#include "duckdb/planner/expression/bound_comparison_expression.hpp" namespace duckdb { -static void RevertFilterPullup(LogicalProjection &proj, vector> &expressions) { - unique_ptr filter = make_uniq(); - for (idx_t i = 0; i < expressions.size(); ++i) { - filter->expressions.push_back(std::move(expressions[i])); +static bool CanRewrite(const Expression &expr, const expression_map_t &projections, + bool match_computed) { + if (expr.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { + return projections.find(expr) != projections.end(); } - expressions.clear(); - filter->children.push_back(std::move(proj.children[0])); - proj.children[0] = std::move(filter); + if (match_computed && projections.find(expr) != projections.end()) { + return true; + } + bool can_rewrite = true; + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { + can_rewrite = can_rewrite && CanRewrite(child, projections, match_computed); + }); + return can_rewrite; } -static void ReplaceExpressionBinding(vector> &proj_expressions, unique_ptr &expr, - TableIndex proj_table_idx) { - expr = ExpressionIterator::PreorderReplace( - std::move(expr), [&](const BoundColumnRefExpression &colref) { - // find the corresponding column index in the projection expressions - for (idx_t proj_idx = 0; proj_idx < proj_expressions.size(); proj_idx++) { - auto &proj_expr = *proj_expressions[proj_idx]; - if (proj_expr.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF && colref.Equals(proj_expr)) { - return colref.WithBinding(ColumnBinding(proj_table_idx, ProjectionIndex(proj_idx))); - } - } - // Project a new column - auto column_index = ColumnBinding::PushExpression(proj_expressions, colref.Copy()); - return colref.WithBinding(ColumnBinding(proj_table_idx, column_index)); - }); +static unique_ptr RewritePredicate(unique_ptr expr, LogicalProjection &proj, + expression_map_t &projections, bool match_computed) { + return ExpressionIterator::PreorderReplace(std::move(expr), [&](const Expression &child) -> unique_ptr { + if (!match_computed && child.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + return nullptr; + } + auto entry = projections.find(child); + if (entry != projections.end()) { + if (child.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { + return child.Cast().WithBinding( + ColumnBinding(proj.table_index, entry->second)); + } + return make_uniq(child.GetAlias(), child.GetReturnType(), + ColumnBinding(proj.table_index, entry->second)); + } + if (child.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + return nullptr; + } + D_ASSERT(!match_computed); + auto column_index = ColumnBinding::PushExpression(proj.expressions, child.Copy()); + projections.emplace(*proj.expressions.back(), column_index); + return child.Cast().WithBinding(ColumnBinding(proj.table_index, column_index)); + }); } -void FilterPullup::ProjectSetOperation(LogicalProjection &proj) { - vector> copy_proj_expressions; - // copying the project expressions, it's useful whether we should revert the filter pullup - for (idx_t i = 0; i < proj.expressions.size(); ++i) { - copy_proj_expressions.push_back(proj.expressions[i]->Copy()); +unique_ptr FilterPullup::PullupProjection(unique_ptr op) { + D_ASSERT(op->type == LogicalOperatorType::LOGICAL_PROJECTION); + auto &proj = op->Cast(); + // Pulling filters above a projection can evaluate its expressions on additional rows. + for (auto &expr : proj.expressions) { + if (expr->CanThrow() || expr->IsVolatile()) { + return FinishPullup(std::move(op)); + } } - // Replace filter expression bindings, when need we add new columns into the copied projection expression - vector> changed_filter_expressions; - for (idx_t i = 0; i < filters_expr_pullup.size(); ++i) { - auto copy_filter_expr = filters_expr_pullup[i]->Copy(); - ReplaceExpressionBinding(copy_proj_expressions, copy_filter_expr, proj.table_index); - changed_filter_expressions.push_back(std::move(copy_filter_expr)); + op->children[0] = Rewrite(std::move(op->children[0])); + if (filters_expr_pullup.empty()) { + return op; } - - /// Case new columns were added into the projection - // we must skip filter pullup because adding new columns to these operators will change the result - if (copy_proj_expressions.size() > proj.expressions.size()) { - RevertFilterPullup(proj, filters_expr_pullup); - return; + for (auto &expr : filters_expr_pullup) { + if (expr->CanThrow() || expr->IsVolatile()) { + // Keep fallible or volatile predicates and their guards below the projection. + proj.children[0] = GeneratePullupFilter(std::move(proj.children[0]), filters_expr_pullup); + return op; + } } - // now we must replace the filter bindings - D_ASSERT(filters_expr_pullup.size() == changed_filter_expressions.size()); - for (idx_t i = 0; i < filters_expr_pullup.size(); ++i) { - filters_expr_pullup[i] = std::move(changed_filter_expressions[i]); + expression_map_t projections; + for (idx_t i = 0; i < proj.expressions.size(); i++) { + // Keep constants in predicates available for constant-filter inference. + if (!proj.expressions[i]->IsFoldable() && FilterCombiner::CanMatchExpression(*proj.expressions[i])) { + projections.emplace(*proj.expressions[i], ProjectionIndex(i)); + } } -} - -unique_ptr FilterPullup::PullupProjection(unique_ptr op) { - D_ASSERT(op->type == LogicalOperatorType::LOGICAL_PROJECTION); - op->children[0] = Rewrite(std::move(op->children[0])); - if (!filters_expr_pullup.empty()) { - auto &proj = op->Cast(); + bool can_move = can_add_column; + if (!can_move) { + can_move = true; for (auto &expr : filters_expr_pullup) { - if (expr->CanThrow()) { - // Keep fallible predicates and their guards below the projection. - RevertFilterPullup(proj, filters_expr_pullup); - return op; - } + can_move = can_move && CanRewrite(*expr, projections, false); } - // INTERSECT, EXCEPT, and DISTINCT - if (!can_add_column) { - // special treatment for operators that cannot add columns, e.g., INTERSECT, EXCEPT, and DISTINCT - ProjectSetOperation(proj); - return op; + } + if (can_move) { + // Preserve the original predicate shape and its visibility at enclosing projections. + for (auto &expr : filters_expr_pullup) { + expr = RewritePredicate(std::move(expr), proj, projections, false); } + return op; + } - for (idx_t i = 0; i < filters_expr_pullup.size(); ++i) { - ReplaceExpressionBinding(proj.expressions, filters_expr_pullup[i], proj.table_index); + vector> exported; + auto export_filter = [&](const Expression &expr) { + if (!FilterCombiner::CanCopyFilter(expr)) { + return; } + auto compared = FilterCombiner::GetComparedExpression(expr); + auto &operand = compared ? *compared : expr; + const bool match_computed = !CanRewrite(operand, projections, false); + if (!match_computed || CanRewrite(operand, projections, true)) { + auto copy = expr.Copy(); + bool rewrite_children = compared; + if (!rewrite_children && BoundComparisonExpression::IsComparison(expr)) { + rewrite_children = true; + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { + rewrite_children &= CanRewrite(child, projections, match_computed); + }); + } + // Keep the comparison available for inference, even when it is also a Boolean output. + if (rewrite_children) { + ExpressionIterator::EnumerateChildren(*copy, [&](unique_ptr &child) { + child = RewritePredicate(std::move(child), proj, projections, match_computed); + }); + } else { + copy = RewritePredicate(std::move(copy), proj, projections, match_computed); + } + exported.push_back(std::move(copy)); + } + }; + for (auto &expr : filters_expr_pullup) { + export_filter(*expr); + } + if (context) { + FilterCombiner::GenerateProjectionFilters( + *context, filters_expr_pullup, [&](const Expression &key) { return CanRewrite(key, projections, true); }, + [&](unique_ptr derived) { export_filter(*derived); }); } + // Retain the full batch: its predicates can guard fallible operators above this projection. + proj.children[0] = GeneratePullupFilter(std::move(proj.children[0]), filters_expr_pullup); + filters_expr_pullup = std::move(exported); return op; } diff --git a/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp b/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp index d3d7d80a2..46e03a2fe 100644 --- a/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp +++ b/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp @@ -3,23 +3,22 @@ #include "duckdb/planner/operator/logical_set_operation.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/expression_binder.hpp" namespace duckdb { -//! Whether the filter compares what a column of that child is compared as with constants: it keeps or removes all the -//! rows that the set operation treats as equal -static bool ComparesSetOperationColumn(const Expression &filter, const vector &comparisons, - bool left_child) { - auto compared = FilterCombiner::GetComparedExpression(filter); - if (!compared) { - return false; - } - for (auto &comparison : comparisons) { - if ((left_child ? comparison.GetLHS() : comparison.GetRHS()).Equals(*compared)) { - return true; - } - } - return false; +static unique_ptr BindSetConstraint(unique_ptr filter, LogicalSetOperation &setop, + const vector &bindings) { + return ExpressionIterator::PreorderReplace( + std::move(filter), [&](const BoundColumnRefExpression &colref) { + D_ASSERT(colref.Depth() == 0); + for (idx_t i = 0; i < bindings.size(); i++) { + if (bindings[i] == colref.Binding()) { + return colref.WithBinding(ColumnBinding(setop.table_index, ProjectionIndex(i))); + } + } + throw InternalException("Filter of a set operation refers to a column that is not one of its child"); + }); } unique_ptr FilterPullup::PullupSetOperation(unique_ptr op) { @@ -28,63 +27,94 @@ unique_ptr FilterPullup::PullupSetOperation(unique_ptrCast(); - // the children cannot get more columns to carry a filter FilterPullup left_pullup(context, true, false); FilterPullup right_pullup(context, op->type == LogicalOperatorType::LOGICAL_INTERSECT, false); op->children[0] = left_pullup.Rewrite(std::move(op->children[0])); op->children[1] = right_pullup.Rewrite(std::move(op->children[1])); auto comparisons = setop.GetComparisons(*context); - - // EXCEPT and INTERSECT return some of the rows of the left child that they treat as equal. A filter of the left - // child may run above them if it keeps or removes all equal rows: one that compares a column with constants. - // A filter that stays below and can throw keeps the filters that guard it there - auto &left_filters = left_pullup.filters_expr_pullup; - bool keep_all = false; - for (auto &filter : left_filters) { - keep_all = keep_all || (filter->CanThrow() && !ComparesSetOperationColumn(*filter, comparisons, true)); + vector> left_keys, right_keys; + for (auto &comparison : comparisons) { + left_keys.push_back(comparison.GetLHS()); + right_keys.push_back(comparison.GetRHS()); } - vector> kept_filters; - vector> pulled_filters; - for (auto &filter : left_filters) { - if (keep_all || !ComparesSetOperationColumn(*filter, comparisons, true)) { - kept_filters.push_back(std::move(filter)); - } else { - pulled_filters.push_back(std::move(filter)); + vector> constraints; + for (auto &filter : left_pullup.filters_expr_pullup) { + if (FilterCombiner::IsKeyConstraint(*filter, left_keys)) { + constraints.push_back(filter->Copy()); } } - left_filters.clear(); - if (!kept_filters.empty()) { - op->children[0] = GeneratePullupFilter(std::move(op->children[0]), kept_filters); - } - if (!right_pullup.filters_expr_pullup.empty()) { - // INTERSECT: a left row with an equal right row passes what the filters of the right child imply for it - vector> right_filters; - for (auto &filter : right_pullup.filters_expr_pullup) { - right_filters.push_back(*filter); + for (auto &filter : right_pullup.filters_expr_pullup) { + if (!FilterCombiner::IsKeyConstraint(*filter, right_keys)) { + continue; } - FilterCombiner::GenerateJoinFilters( - comparisons, right_filters, JoinSide::LEFT, - [&](unique_ptr left_filter) { pulled_filters.push_back(std::move(left_filter)); }); - op->children[1] = GeneratePullupFilter(std::move(op->children[1]), right_pullup.filters_expr_pullup); - } - if (pulled_filters.empty()) { - return op; - } - // the filters refer to the columns of the left child: above the set operation these are its columns - auto left_bindings = op->children[0]->GetColumnBindings(); - for (auto &filter : pulled_filters) { - filter = ExpressionIterator::PreorderReplace( - std::move(filter), [&](const BoundColumnRefExpression &colref) { - D_ASSERT(colref.Depth() == 0); - for (idx_t i = 0; i < left_bindings.size(); i++) { - if (left_bindings[i] == colref.Binding()) { - return colref.WithBinding(ColumnBinding(setop.table_index, ProjectionIndex(i))); + auto copy = + ExpressionIterator::PreorderReplace(filter->Copy(), [&](const Expression &expr) -> unique_ptr { + for (auto &comparison : comparisons) { + if (comparison.GetRHS().Equals(expr)) { + return comparison.GetLHS().Copy(); } } - throw InternalException("Filter of a set operation refers to a column that is not one of its child"); + return nullptr; }); + if (FilterCombiner::IsKeyConstraint(*copy, left_keys)) { + constraints.push_back(std::move(copy)); + } + } + op->children[0] = GeneratePullupFilter(std::move(op->children[0]), left_pullup.filters_expr_pullup); + op->children[1] = GeneratePullupFilter(std::move(op->children[1]), right_pullup.filters_expr_pullup); + auto bindings = op->children[0]->GetColumnBindings(); + for (auto &filter : constraints) { + filter = BindSetConstraint(std::move(filter), setop, bindings); + } + return ReturnConstraints(std::move(op), std::move(constraints)); +} + +unique_ptr FilterPullup::PullupUnion(unique_ptr op) { + if (!can_pullup) { + return FinishPullup(std::move(op)); + } + auto &setop = op->Cast(); + vector> common; + for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { + auto &child = op->children[child_idx]; + FilterPullup child_pullup(context, true, false); + child = child_pullup.Rewrite(std::move(child)); + auto bindings = child->GetColumnBindings(); + child->ResolveOperatorTypes(); + vector> key_expressions; + vector> keys; + for (idx_t i = 0; i < bindings.size(); i++) { + auto key = make_uniq(child->types[i], bindings[i]); + key_expressions.push_back(std::move(key)); + if (!setop.setop_all && context) { + ExpressionBinder::PushCollation(*context, key_expressions.back(), child->types[i]); + } + keys.push_back(*key_expressions.back()); + } + vector> constraints; + // The binder has already coerced each branch to the UNION's output types. + for (auto &filter : child_pullup.filters_expr_pullup) { + if (FilterCombiner::IsKeyConstraint(*filter, keys) && FilterCombiner::CanMatchExpression(*filter)) { + constraints.push_back(BindSetConstraint(filter->Copy(), setop, bindings)); + } + } + child = GeneratePullupFilter(std::move(child), child_pullup.filters_expr_pullup); + if (child_idx == 0) { + FilterCombiner::DeduplicateFilters(constraints); + common = std::move(constraints); + continue; + } + expression_set_t branch_constraints; + for (auto &filter : constraints) { + branch_constraints.insert(*filter); + } + for (idx_t i = 0; i < common.size(); i++) { + if (!branch_constraints.count(*common[i])) { + common.erase_at(i--); + } + } } - return GeneratePullupFilter(std::move(op), pulled_filters); + return ReturnConstraints(std::move(op), std::move(common)); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_filter.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_filter.cpp index fdf6fbe6e..c3f6b261f 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_filter.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_filter.cpp @@ -10,7 +10,20 @@ unique_ptr FilterPushdown::PushdownFilter(unique_ptrtype == LogicalOperatorType::LOGICAL_FILTER); auto &filter = op->Cast(); if (filter.HasProjectionMap()) { - return FinishPushdown(std::move(op)); + if (!filter.expressions.empty()) { + return FinishPushdown(std::move(op)); + } + vector> remain_expressions; + for (idx_t i = 0; i < filters.size(); i++) { + if (!filters[i]->filter->CanThrow() && !filters[i]->filter->IsVolatile()) { + continue; + } + remain_expressions.push_back(std::move(filters[i]->filter)); + filters.erase_at(i--); + } + // Preserve the output layout and the evaluation boundary of unsafe predicates. + RewriteChild(*op, 0); + return AddLogicalFilter(std::move(op), std::move(remain_expressions)); } // filter: gather the filters and remove the filter from the set of operations for (auto &expression : filter.expressions) { diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_get.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_get.cpp index e9ef36ae6..72974da57 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_get.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_get.cpp @@ -154,20 +154,21 @@ unique_ptr FilterPushdown::PushdownGet(unique_ptr(std::move(op)); } auto &column_ids = get.GetColumnIds(); + const bool has_existing_filters = get.table_filters.HasFilters(); //! We generate the table filters that will be executed during the table scan vector pushdown_results; - get.table_filters = combiner.GenerateTableScanFilters(column_ids, pushdown_results); + combiner.GenerateTableScanFilters(get.table_filters, column_ids, pushdown_results); GenerateFilters(); @@ -194,8 +195,8 @@ unique_ptr FilterPushdown::PushdownGet(unique_ptr 1) { + // An existing scan filter may guard a throwing expression that arrived in this later pass. + if (expr.CanThrow() && (filters.size() > 1 || has_existing_filters)) { continue; } pushdown_result = combiner.TryPushdownGenericExpression(get, expr); @@ -209,6 +210,10 @@ unique_ptr FilterPushdown::PushdownGet(unique_ptr(std::move(op)); + } + //! Now we try to pushdown the remaining filters to perform zonemap checking return FinishPushdown(std::move(op)); } diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics.cpp index c8733e6db..4b11f669b 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics.cpp @@ -2,7 +2,7 @@ namespace duckdb { -DistinctCount::DistinctCount(idx_t distinct_count, DistinctCountSource source) +DistinctCount::DistinctCount(CardinalityValue distinct_count, DistinctCountSource source) : distinct_count(distinct_count), source(source) { } @@ -25,14 +25,14 @@ optional_idx SemiAntiJoinDomainEvidence::GetDomainBound() const { return domain_bound; } -optional_idx SemiAntiJoinDomainEvidence::GetSupportedDomainSize(idx_t current_domain) const { - optional_idx result; +optional SemiAntiJoinDomainEvidence::GetSupportedDomainSize(CardinalityValue current_domain) const { + optional result; if (is_unique) { - result = optional_idx(current_domain); + result = current_domain; } if (domain_bound.IsValid()) { - result = optional_idx(result.IsValid() ? MinValue(result.GetIndex(), domain_bound.GetIndex()) - : domain_bound.GetIndex()); + auto bound = CardinalityValue(domain_bound.GetIndex()); + result = result ? MinValue(*result, bound) : bound; } return result; } @@ -48,13 +48,31 @@ RelationColumnStats::RelationColumnStats(ColumnBinding binding, DistinctCount to semi_anti_join_domain_evidence(semi_anti_join_domain_evidence), name(std::move(name)) { } -optional_idx RelationColumnStats::GetSupportedSemiAntiDomainSize() const { +optional RelationColumnStats::GetSupportedSemiAntiDomainSize() const { return semi_anti_join_domain_evidence.GetSupportedDomainSize(current_domain.distinct_count); } RelationStats::RelationStats() : cardinality(1), row_retention(1), stats_initialized(false) { } +bool RelationStats::IsEmpty() const { + return max_cardinality.IsValid() && max_cardinality.GetIndex() == 0; +} + +CardinalityValue RelationStats::GetCardinality() const { + return max_cardinality.IsValid() ? MinValue(cardinality, CardinalityValue(max_cardinality.GetIndex())) + : cardinality; +} + +CardinalityValue RelationStats::GetCardinalityForCost() const { + return IsEmpty() ? CardinalityValue(0) : MaxValue(CardinalityValue(1), GetCardinality()); +} + +idx_t RelationStats::GetCardinalityForPlan() const { + auto result = GetCardinalityForCost().GetIndex(); + return max_cardinality.IsValid() ? MinValue(result, max_cardinality.GetIndex()) : result; +} + optional_idx RelationStats::FindColumn(ColumnBinding binding) const { for (idx_t column_idx = 0; column_idx < columns.size(); column_idx++) { if (columns[column_idx].binding == binding) { @@ -85,6 +103,7 @@ bool RelationStats::MatchesBindings(const vector &bindings) const } void RelationStats::CapCurrentDomainsToCardinality() { + cardinality = GetCardinality(); for (auto &column : columns) { column.current_domain.distinct_count = MinValue(column.current_domain.distinct_count, cardinality); } @@ -113,6 +132,7 @@ void RelationStats::Verify(const vector &bindings) const { if (!stats_initialized) { return; } + D_ASSERT(cardinality == GetCardinality()); D_ASSERT(row_retention >= 0 && row_retention <= 1); for (auto &column : columns) { (void)column; diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp index f8f7a1eda..ce743f35b 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp @@ -60,14 +60,19 @@ idx_t RelationStatsExtractor::ExtractedOperatorCount() const { return extracted_operator_count; } -static bool IsInnerJoinRegion(LogicalOperator &op) { +static bool IsJoinEstimationRegion(LogicalOperator &op) { optional_ptr root = op; while (root->type == LogicalOperatorType::LOGICAL_FILTER) { root = *root->children[0]; } - return root->type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT || - (root->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && - root->Cast().join_type == JoinType::INNER); + if (root->type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + return true; + } + if (root->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return false; + } + auto type = root->Cast().join_type; + return type == JoinType::INNER || type == JoinType::LEFT; } optional RelationStatsExtractor::ExtractInternal(LogicalOperator &op) { @@ -104,7 +109,7 @@ optional RelationStatsExtractor::ExtractInternal(LogicalOperator return RelationStatisticsHelper::ExtractExplainStats(op); } - if (IsInnerJoinRegion(op)) { + if (IsJoinEstimationRegion(op)) { auto stats = ExtractJoinStats(op); if (stats) { return stats; @@ -131,19 +136,15 @@ optional RelationStatsExtractor::ExtractJoinStats(LogicalOperator if (!graph.BuildForEstimation(*this, op)) { return {}; } - auto relation_stats = graph.relation_manager.GetRelationStats(); CardinalityEstimator estimator(graph.set_manager, graph.GetPredicateModel()); - estimator.Initialize(relation_stats, graph.GetJoinOperators(), graph.relation_manager.GetColumnSources()); + estimator.Initialize(graph.relation_manager.GetRelationStats(), graph.GetJoinOperators(), + graph.relation_manager.GetColumnSources()); unordered_set relations; - for (idx_t i = 0; i < relation_stats.size(); i++) { + for (idx_t i = 0; i < graph.relation_manager.NumRelations(); i++) { relations.insert(RelationIndex(i)); } auto &set = graph.set_manager.GetJoinRelation(relations); - auto estimate = estimator.EstimateCardinality(set); - if (estimate.GetDouble() >= static_cast(NumericLimits::Maximum())) { - return {}; - } - return graph.CombineRelationStats(op.GetColumnBindings(), relation_stats, estimate.GetIndex()); + return graph.ProjectRetainedStats(estimator, set, op); } optional_ptr RelationStatsExtractor::GetCTEDefinition(const LogicalCTERef &cte_ref) const { diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp index 4bb143589..3ee732cc5 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp @@ -3,6 +3,8 @@ #include "duckdb/common/types/value_map.hpp" #include "duckdb/function/aggregate/distributive_function_utils.hpp" +#include "duckdb/common/operator/add.hpp" +#include "duckdb/common/operator/multiply.hpp" #include "duckdb/optimizer/distinctness.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" @@ -184,6 +186,7 @@ optional RelationStatisticsHelper::ExtractProjectionStats(Logical const RelationStats &child_stats) { RelationStats result; result.cardinality = child_stats.cardinality; + result.max_cardinality = child_stats.max_cardinality; result.row_retention = child_stats.row_retention; result.table_name = Identifier(projection.GetName()); result.stats_initialized = true; @@ -197,7 +200,8 @@ optional RelationStatisticsHelper::ExtractProjectionStats(Logical SemiAntiJoinDomainEvidence semi_anti_join_domain_evidence; optional_ptr child_column; if (expression_binding.expression_is_constant) { - distinct_count = DistinctCount(MinValue(result.cardinality, 1), DistinctCountSource::EXACT); + distinct_count = + DistinctCount(MinValue(result.cardinality, CardinalityValue(1)), DistinctCountSource::EXACT); } else if (expression_binding.FoundColumnRef()) { child_column = child_columns.Find(expression_binding.child_binding); if (!child_column) { @@ -220,33 +224,38 @@ optional RelationStatisticsHelper::ExtractProjectionStats(Logical return result; } -idx_t RelationStatisticsHelper::EstimateDistinctCardinality(const vector &distinct_counts, - idx_t input_cardinality) { +CardinalityValue RelationStatisticsHelper::EstimateDistinctCardinality(const vector &distinct_counts, + CardinalityValue input_cardinality) { if (distinct_counts.empty()) { return input_cardinality / 2; } if (distinct_counts.size() == 1) { return MinValue(distinct_counts[0].distinct_count, input_cardinality); } - double product = 1; - idx_t largest_domain = 1; + CardinalityValue product(1); + CardinalityValue largest_domain(0); idx_t varying_groups = 0; for (auto &distinct_count : distinct_counts) { - product *= static_cast(MaxValue(distinct_count.distinct_count, 1)); + auto domain = distinct_count.distinct_count.IsZero() ? CardinalityValue(1) : distinct_count.distinct_count; + product *= domain; largest_domain = MaxValue(largest_domain, distinct_count.distinct_count); - varying_groups += distinct_count.distinct_count > 1; + if (domain != 1 && varying_groups++ > 0) { + product *= CardinalityValue(0.95); + } } if (varying_groups <= 1) { return MinValue(largest_domain, input_cardinality); } - product *= pow(0.95, static_cast(varying_groups - 1)); - const auto multiplier = 1.0 - exp(-static_cast(input_cardinality) / product); - const auto estimate = multiplier == 0 ? static_cast(input_cardinality) : product * multiplier; - return MinValue(MaxValue(CardinalityFromDouble(estimate), largest_domain), input_cardinality); + const auto load = (input_cardinality / product).GetDouble(); + const auto multiplier = -expm1(-load); + // The small-load limit retains input rows even below double's exponent range. + const auto estimate = multiplier == 0 ? input_cardinality : product * CardinalityValue(multiplier); + return MinValue(MaxValue(estimate, largest_domain), input_cardinality); } DistinctCount RelationStatisticsHelper::EstimateCurrentDomain(const DistinctCount ¤t_domain, - idx_t input_cardinality, idx_t output_cardinality) { + CardinalityValue input_cardinality, + CardinalityValue output_cardinality) { auto count = MinValue(current_domain.distinct_count, input_cardinality); if (count == 0 || output_cardinality == 0 || input_cardinality == 0) { return DistinctCount(0, DistinctCountSource::CARDINALITY); @@ -254,17 +263,30 @@ DistinctCount RelationStatisticsHelper::EstimateCurrentDomain(const DistinctCoun if (output_cardinality >= input_cardinality) { return DistinctCount(count, current_domain.source); } + if (count == input_cardinality) { + // The uniform model has multiplicity one, so its retained-domain point equals the retained rows. + // Avoid a logarithm/exponential round trip; this estimate does not establish uniqueness. + return DistinctCount(output_cardinality, DistinctCountSource::CARDINALITY); + } - const auto row_survival = static_cast(output_cardinality) / static_cast(input_cardinality); - const auto multiplicity = static_cast(input_cardinality) / static_cast(count); - const auto retained_fraction = -expm1(multiplicity * log1p(-row_survival)); - const auto estimate = round(static_cast(count) * retained_fraction); - auto result = MinValue(CardinalityFromDouble(estimate), output_cardinality); - result = MinValue(result, count); - return DistinctCount(MaxValue(result, 1), DistinctCountSource::CARDINALITY); + const auto row_survival = (output_cardinality / input_cardinality).GetDouble(); + // Rearrange multiplicity * -log1p(-survival) to avoid infinity * zero. + const auto correction = row_survival == 0 ? 1.0 : -log1p(-row_survival) / row_survival; + CardinalityValue estimate; + if (!std::isfinite(correction)) { + estimate = count; + } else { + auto load = (output_cardinality / count * CardinalityValue(correction)).GetDouble(); + auto fraction = -expm1(-load); + estimate = fraction == 0 ? output_cardinality : count * CardinalityValue(fraction); + } + return DistinctCount(MinValue(MinValue(estimate, output_cardinality), count), DistinctCountSource::CARDINALITY); } -void RelationStatisticsHelper::ApplyCardinality(RelationStats &stats, idx_t output_cardinality) { +void RelationStatisticsHelper::ApplyCardinality(RelationStats &stats, CardinalityValue output_cardinality) { + if (stats.max_cardinality.IsValid()) { + output_cardinality = MinValue(output_cardinality, CardinalityValue(stats.max_cardinality.GetIndex())); + } const auto input_cardinality = stats.cardinality; for (auto &column : stats.columns) { column.current_domain = EstimateCurrentDomain(column.current_domain, input_cardinality, output_cardinality); @@ -272,49 +294,92 @@ void RelationStatisticsHelper::ApplyCardinality(RelationStats &stats, idx_t outp MinValue(column.current_domain.distinct_count, column.total_domain.distinct_count); } if (input_cardinality > 0 && output_cardinality < input_cardinality) { - stats.row_retention *= double(output_cardinality) / double(input_cardinality); + stats.row_retention *= output_cardinality / input_cardinality; } stats.cardinality = output_cardinality; } -static double RoundSemiAntiCardinality(double preserved_cardinality, double selectivity) { - if (preserved_cardinality <= 0) { - return 0; +optional_idx RelationStatisticsHelper::AddCardinalityBounds(optional_idx left, optional_idx right) { + idx_t result; + if (!left.IsValid() || !right.IsValid() || !TryAddOperator::Operation(left.GetIndex(), right.GetIndex(), result)) { + return {}; } - auto estimate = round(preserved_cardinality * MaxValue(0.0, MinValue(selectivity, 1.0))); - if (estimate <= 0) { - estimate = 1; + return optional_idx(result); +} + +optional_idx RelationStatisticsHelper::MultiplyCardinalityBounds(optional_idx left, optional_idx right) { + if ((left.IsValid() && left.GetIndex() == 0) || (right.IsValid() && right.GetIndex() == 0)) { + return optional_idx(0); + } + idx_t result; + if (!left.IsValid() || !right.IsValid() || + !TryMultiplyOperator::Operation(left.GetIndex(), right.GetIndex(), result)) { + return {}; + } + return optional_idx(result); +} + +optional_idx RelationStatisticsHelper::JoinCardinalityBound(JoinType type, optional_idx left, optional_idx right) { + switch (type) { + case JoinType::RIGHT: + return JoinCardinalityBound(JoinType::LEFT, right, left); + case JoinType::RIGHT_SEMI: + return JoinCardinalityBound(JoinType::SEMI, right, left); + case JoinType::RIGHT_ANTI: + return right; + case JoinType::SEMI: + return right.IsValid() && right.GetIndex() == 0 ? optional_idx(0) : left; + case JoinType::ANTI: + case JoinType::MARK: + case JoinType::SINGLE: + return left; + case JoinType::INNER: + return MultiplyCardinalityBounds(left, right); + case JoinType::LEFT: + if (right.IsValid() && right.GetIndex() == 0) { + return left; + } + return AddCardinalityBounds(MultiplyCardinalityBounds(left, right), left); + case JoinType::OUTER: + if (left.IsValid() && left.GetIndex() == 0) { + return right; + } + if (right.IsValid() && right.GetIndex() == 0) { + return left; + } + return AddCardinalityBounds(AddCardinalityBounds(MultiplyCardinalityBounds(left, right), left), right); + default: + return {}; } - return MinValue(estimate, preserved_cardinality); } -SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinFallback(double preserved_cardinality, - idx_t rhs_cardinality, - JoinType join_type) { +SemiAntiJoinCardinalityEstimate +RelationStatisticsHelper::EstimateSemiAntiJoinFallback(CardinalityValue preserved_cardinality, + CardinalityValue rhs_cardinality, JoinType join_type) { return {EstimateSemiAntiJoinFallbackCardinality(preserved_cardinality, rhs_cardinality, join_type), false}; } static constexpr double MAX_BASE_CARDINALITY_TO_DOMAIN_RATIO = 8; SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinCardinality( - double preserved_cardinality, idx_t rhs_cardinality, double rhs_row_retention, JoinType join_type, - const vector &domains, bool has_residual) { + CardinalityValue preserved_cardinality, CardinalityValue rhs_cardinality, CardinalityValue rhs_row_retention, + JoinType join_type, const vector &domains, bool has_residual) { auto fallback = EstimateSemiAntiJoinFallback(preserved_cardinality, rhs_cardinality, join_type); if (preserved_cardinality <= 0 || rhs_cardinality == 0 || has_residual || domains.empty()) { return fallback; } - double match_fraction = 1; - double strongest_fraction = 1; - idx_t strongest_total_domain = 0; - idx_t maximum_total_domain = 0; + CardinalityValue match_fraction(1); + CardinalityValue strongest_fraction(1); + CardinalityValue strongest_total_domain(0); + CardinalityValue maximum_total_domain(0); column_binding_set_t preserved_bindings; column_binding_set_t rhs_bindings; for (auto &domain : domains) { if (domain.total_domain == 0) { return fallback; } - double fraction = MinValue(1.0, double(domain.rhs_current_domain) / double(domain.total_domain)); + auto fraction = MinValue(CardinalityValue(1), domain.rhs_current_domain / domain.total_domain); match_fraction *= fraction; if (fraction < strongest_fraction) { strongest_fraction = fraction; @@ -325,17 +390,17 @@ SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinCa rhs_bindings.insert(domain.rhs_binding); } if (domains.size() >= 2 && preserved_bindings.size() >= 2 && rhs_bindings.size() >= 2 && maximum_total_domain > 0) { - auto retention = MaxValue(0.0, MinValue(rhs_row_retention, 1.0)); - auto rhs_base_cardinality = retention > 0 ? double(rhs_cardinality) / retention : double(rhs_cardinality); - if (rhs_base_cardinality <= double(maximum_total_domain) * MAX_BASE_CARDINALITY_TO_DOMAIN_RATIO && - (strongest_total_domain == 0 || double(strongest_total_domain) <= rhs_base_cardinality)) { + auto retention = MinValue(rhs_row_retention, CardinalityValue(1)); + auto rhs_base_cardinality = retention > 0 ? rhs_cardinality / retention : rhs_cardinality; + if (rhs_base_cardinality <= maximum_total_domain * CardinalityValue(MAX_BASE_CARDINALITY_TO_DOMAIN_RATIO) && + (strongest_total_domain == 0 || strongest_total_domain <= rhs_base_cardinality)) { match_fraction = MaxValue(match_fraction, MinValue(strongest_fraction, retention)); } } - match_fraction = MaxValue(0.0, MinValue(match_fraction, 1.0)); + match_fraction = MinValue(match_fraction, CardinalityValue(1)); auto is_anti = join_type == JoinType::ANTI || join_type == JoinType::RIGHT_ANTI; - auto selectivity = is_anti ? 1 - match_fraction : match_fraction; - return {RoundSemiAntiCardinality(preserved_cardinality, selectivity), true}; + auto selectivity = is_anti ? CardinalityValue(1) - match_fraction : match_fraction; + return {preserved_cardinality * selectivity, true}; } optional @@ -351,7 +416,7 @@ RelationStatisticsHelper::EstimateTupleDomainRestriction(LogicalComparisonJoin & vector input_columns; vector key_columns; vector total_domains; - double marginal_fraction = 1; + CardinalityValue marginal_fraction(1); for (auto &condition : restriction.conditions) { D_ASSERT(condition.IsComparison()); auto input_index = input.FindColumn(condition.GetLHS().Cast().Binding()); @@ -366,9 +431,8 @@ RelationStatisticsHelper::EstimateTupleDomainRestriction(LogicalComparisonJoin & return {}; } auto supported = key_column.GetSupportedSemiAntiDomainSize(); - if (supported.IsValid()) { - marginal_fraction = MinValue(marginal_fraction, static_cast(supported.GetIndex()) / - static_cast(total->distinct_count)); + if (supported) { + marginal_fraction = MinValue(marginal_fraction, *supported / total->distinct_count); } input_columns.push_back(input_index.GetIndex()); key_columns.push_back(key_index.GetIndex()); @@ -377,18 +441,16 @@ RelationStatisticsHelper::EstimateTupleDomainRestriction(LogicalComparisonJoin & auto input_groups = EstimateGroupCardinality(*restriction.children[0], input, std::move(input_columns), extractor); auto key_groups = EstimateGroupCardinality(*restriction.children[1], keys, std::move(key_columns), extractor); // The total tuple domain predates filters; only current tuple counts are capped by current rows. - auto source_rows = MaxValue(static_cast(input.cardinality) / input.row_retention, - static_cast(keys.cardinality) / keys.row_retention); - auto total_groups = EstimateDistinctCardinality(total_domains, CardinalityFromDouble(source_rows)); + auto source_rows = MaxValue(input.cardinality / input.row_retention, keys.cardinality / keys.row_retention); + auto total_groups = EstimateDistinctCardinality(total_domains, source_rows); if (total_groups == 0) { return {}; } - auto fraction = MinValue(marginal_fraction, static_cast(key_groups) / static_cast(total_groups)); - auto rows = MinValue(static_cast(input.cardinality), - MaxValue(1.0, round(static_cast(input.cardinality) * fraction))); + auto fraction = MinValue(marginal_fraction, key_groups / total_groups); + auto rows = input.cardinality * fraction; // Full marginal domains need not cover every tuple, e.g. a diagonal against a Cartesian input. - auto groups = MinValue(rows, static_cast(MinValue(input_groups, key_groups))); - return TupleDomainRestrictionEstimate {rows, groups}; + auto groups = MinValue(rows, MinValue(input_groups, key_groups)); + return TupleDomainRestrictionEstimate {rows.GetDouble(), groups.GetDouble()}; } static bool TryMapProjectionGroups(LogicalOperator &op, vector &groups) { @@ -413,13 +475,13 @@ static bool TryMapProjectionGroups(LogicalOperator &op, vector &groups) { return true; } -static optional_idx EstimateUnionGroups(LogicalOperator &input, vector groups, idx_t maximum, - RelationStatsExtractor &extractor, bool use_operator_cardinality) { +static optional EstimateUnionGroups(LogicalOperator &input, vector groups, + CardinalityValue maximum, RelationStatsExtractor &extractor) { static constexpr idx_t MAX_VISITED_OPERATORS = 1024; vector, vector>> pending; pending.emplace_back(input, std::move(groups)); idx_t visited = 0; - idx_t result = 0; + CardinalityValue result(0); bool found_union = false; while (!pending.empty()) { if (visited++ == MAX_VISITED_OPERATORS) { @@ -467,14 +529,16 @@ static optional_idx EstimateUnionGroups(LogicalOperator &input, vector gr if (!stats) { return {}; } - auto cardinality = - use_operator_cardinality && op.has_estimated_cardinality ? op.estimated_cardinality : stats->cardinality; - auto estimate = MinValue(cardinality, 1); + auto cardinality = stats->cardinality; + auto estimate = MinValue(cardinality, CardinalityValue(1)); for (auto index : entry.second) { if (index >= stats->columns.size()) { return {}; } - auto domain = MaxValue(stats->columns[index].current_domain.distinct_count, 1); + auto domain = stats->columns[index].current_domain.distinct_count; + if (domain.IsZero()) { + domain = CardinalityValue(1); + } if (estimate > cardinality / domain) { estimate = cardinality; break; @@ -486,21 +550,23 @@ static optional_idx EstimateUnionGroups(LogicalOperator &input, vector gr return result; } -idx_t RelationStatisticsHelper::EstimateGroupCardinality(LogicalOperator &input, const RelationStats &input_stats, - vector groups, RelationStatsExtractor &extractor, - bool use_operator_cardinality) { +CardinalityValue RelationStatisticsHelper::EstimateGroupCardinality(LogicalOperator &input, + const RelationStats &input_stats, + vector groups, + RelationStatsExtractor &extractor) { vector counts; for (auto index : groups) { auto count = input_stats.columns[index].current_domain; - count.distinct_count = MaxValue(count.distinct_count, 1); + if (count.distinct_count.IsZero()) { + count.distinct_count = CardinalityValue(1); + } counts.push_back(count); } auto estimate = EstimateDistinctCardinality(counts, input_stats.cardinality); - auto union_groups = - EstimateUnionGroups(input, std::move(groups), input_stats.cardinality, extractor, use_operator_cardinality); - if (union_groups.IsValid()) { + auto union_groups = EstimateUnionGroups(input, std::move(groups), input_stats.cardinality, extractor); + if (union_groups) { // Per-arm domain products avoid inventing cross-arm combinations of grouping keys. - estimate = MinValue(estimate, union_groups.GetIndex()); + estimate = MinValue(estimate, *union_groups); } return estimate; } @@ -526,8 +592,7 @@ static optional_ptr GetSelectedValueStats(const Expre static optional ExtractAggregationStatsInternal(LogicalAggregate &aggregate, const RelationStats &child_stats, - RelationStatsExtractor &extractor, - bool use_operator_cardinality) { + RelationStatsExtractor &extractor) { RelationColumnStatsLookup child_columns(child_stats); vector cardinality_counts; auto add_group = [&](const Expression &group, vector &counts) { @@ -539,7 +604,9 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate return false; } auto count = column->current_domain; - count.distinct_count = MaxValue(count.distinct_count, 1); + if (count.distinct_count.IsZero()) { + count.distinct_count = CardinalityValue(1); + } counts.push_back(count); return true; }; @@ -566,6 +633,15 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate RelationStats result; result.table_name = Identifier(aggregate.GetName()); result.stats_initialized = true; + if (aggregate.grouping_sets.empty()) { + result.max_cardinality = aggregate.groups.empty() ? optional_idx(1) : child_stats.max_cardinality; + } else { + result.max_cardinality = optional_idx(0); + for (auto &grouping_set : aggregate.grouping_sets) { + result.max_cardinality = RelationStatisticsHelper::AddCardinalityBounds( + result.max_cardinality, grouping_set.empty() ? optional_idx(1) : child_stats.max_cardinality); + } + } auto bindings = aggregate.GetColumnBindings(); auto preserves_group_evidence = aggregate.grouping_sets.empty() || @@ -576,8 +652,8 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate for (auto &group : aggregate.groups) { groups.push_back(child_stats.FindColumn(group->Cast().Binding()).GetIndex()); } - result.cardinality = RelationStatisticsHelper::EstimateGroupCardinality( - *aggregate.children[0], child_stats, std::move(groups), extractor, use_operator_cardinality); + result.cardinality = RelationStatisticsHelper::EstimateGroupCardinality(*aggregate.children[0], child_stats, + std::move(groups), extractor); } else { result.cardinality = aggregate.groups.empty() @@ -646,7 +722,8 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate result.columns.emplace_back(bindings[result.columns.size()], total_domain, current_domain, Identifier()); } for (idx_t grouping_idx = 0; grouping_idx < aggregate.grouping_functions.size(); grouping_idx++) { - auto grouping_count = MinValue(result.cardinality, MaxValue(aggregate.grouping_sets.size(), 1)); + auto grouping_count = + MinValue(result.cardinality, CardinalityValue(MaxValue(aggregate.grouping_sets.size(), 1))); result.columns.emplace_back(bindings[result.columns.size()], DistinctCount(grouping_count, DistinctCountSource::CARDINALITY), Identifier("grouping")); @@ -659,22 +736,21 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate optional RelationStatisticsHelper::ExtractAggregationStats(LogicalAggregate &aggregate, const RelationStats &child_stats, ClientContext &context) { - // Join reconstruction has already published the selected input cardinalities. RelationStatsExtractor extractor(context); - return ExtractAggregationStatsInternal(aggregate, child_stats, extractor, true); + return ExtractAggregationStatsInternal(aggregate, child_stats, extractor); } optional RelationStatisticsHelper::ExtractAggregationStats(LogicalAggregate &aggregate, const RelationStats &child_stats, - RelationStatsExtractor &extractor, - bool use_operator_cardinality) { - return ExtractAggregationStatsInternal(aggregate, child_stats, extractor, use_operator_cardinality); + RelationStatsExtractor &extractor) { + return ExtractAggregationStatsInternal(aggregate, child_stats, extractor); } optional RelationStatisticsHelper::ExtractWindowStats(LogicalWindow &window, const RelationStats &child_stats) { RelationStats result; result.cardinality = child_stats.cardinality; + result.max_cardinality = child_stats.max_cardinality; result.row_retention = child_stats.row_retention; result.table_name = Identifier(window.GetName()); result.stats_initialized = true; @@ -704,18 +780,29 @@ optional RelationStatisticsHelper::ExtractLimitStats(LogicalLimit auto available_cardinality = child_stats.cardinality; if (limit.offset_val.Type() == LimitNodeType::CONSTANT_VALUE) { auto offset = limit.offset_val.GetConstantValue(); - available_cardinality = offset >= available_cardinality ? 0 : available_cardinality - offset; + available_cardinality = available_cardinality - CardinalityValue(offset); + if (result->max_cardinality.IsValid()) { + auto maximum = result->max_cardinality.GetIndex(); + result->max_cardinality = optional_idx(offset >= maximum ? 0 : maximum - offset); + } } auto cardinality = available_cardinality; switch (limit.limit_val.Type()) { case LimitNodeType::CONSTANT_VALUE: - cardinality = MinValue(cardinality, limit.limit_val.GetConstantValue()); + cardinality = MinValue(cardinality, CardinalityValue(limit.limit_val.GetConstantValue())); + result->max_cardinality = + optional_idx(result->max_cardinality.IsValid() + ? MinValue(result->max_cardinality.GetIndex(), limit.limit_val.GetConstantValue()) + : limit.limit_val.GetConstantValue()); break; case LimitNodeType::CONSTANT_PERCENTAGE: { auto percentage = limit.limit_val.GetConstantPercentage(); auto percentage_cardinality = child_stats.cardinality; if (percentage < 100) { - percentage_cardinality = LossyNumericCast(double(child_stats.cardinality) * percentage / 100.0); + percentage_cardinality = child_stats.cardinality * CardinalityValue(percentage / 100.0); + if (percentage == 0) { + result->max_cardinality = optional_idx(0); + } } cardinality = MinValue(cardinality, percentage_cardinality); break; @@ -730,6 +817,7 @@ optional RelationStatisticsHelper::ExtractLimitStats(LogicalLimit RelationStats RelationStatisticsHelper::ExtractEmptyResultStats(LogicalEmptyResult &empty) { RelationStats result; result.cardinality = 0; + result.max_cardinality = optional_idx(0); result.table_name = Identifier(empty.GetName()); result.stats_initialized = true; for (auto &binding : empty.GetColumnBindings()) { @@ -746,6 +834,7 @@ optional RelationStatisticsHelper::ProjectOutputStats(const Relat } RelationStats result; result.cardinality = stats.cardinality; + result.max_cardinality = stats.max_cardinality; result.row_retention = stats.row_retention; result.stats_initialized = true; result.table_name = stats.table_name; diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp index 4022af375..6b312282e 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp @@ -7,10 +7,12 @@ namespace duckdb { -static optional -ProjectChildStats(LogicalOperator &op, const vector> &children, idx_t cardinality) { +static optional ProjectChildStats(LogicalOperator &op, + const vector> &children, + CardinalityValue cardinality, optional_idx maximum = {}) { RelationStats result; result.cardinality = cardinality; + result.max_cardinality = maximum; result.stats_initialized = true; result.table_name = Identifier(op.GetName()); RelationColumnStatsLookup child_columns; @@ -29,18 +31,19 @@ ProjectChildStats(LogicalOperator &op, const vector ExtractSemiAntiJoinDomains(LogicalComparisonJo continue; } auto rhs_current_domain = rhs_column->GetSupportedSemiAntiDomainSize(); - if (!rhs_current_domain.IsValid()) { + if (!rhs_current_domain) { has_residual = true; continue; } @@ -96,7 +99,7 @@ static vector ExtractSemiAntiJoinDomains(LogicalComparisonJo has_residual = true; } domains.push_back( - {total_domain->distinct_count, rhs_current_domain.GetIndex(), lhs_preserved->binding, rhs_column->binding}); + {total_domain->distinct_count, *rhs_current_domain, lhs_preserved->binding, rhs_column->binding}); } return domains; } @@ -106,8 +109,7 @@ static SemiAntiJoinCardinalityEstimate EstimateSemiAntiJoin(LogicalComparisonJoi const vector &domains, bool has_residual) { auto estimate = RelationStatisticsHelper::EstimateSemiAntiJoinCardinality( - static_cast(preserved.cardinality), rhs.cardinality, rhs.row_retention, join.join_type, domains, - has_residual); + preserved.GetCardinality(), rhs.GetCardinality(), rhs.row_retention, join.join_type, domains, has_residual); auto is_semi = join.join_type == JoinType::SEMI || join.join_type == JoinType::RIGHT_SEMI; if (!is_semi || join.children.size() != 2) { return estimate; @@ -119,8 +121,8 @@ static SemiAntiJoinCardinalityEstimate EstimateSemiAntiJoin(LogicalComparisonJoi } if (rhs_op->type == LogicalOperatorType::LOGICAL_CHUNK_GET) { // Constant-list domains do not describe the frequency of matching values. - auto fallback = RelationStatisticsHelper::EstimateSemiAntiJoinFallback( - static_cast(preserved.cardinality), rhs.cardinality, join.join_type); + auto fallback = RelationStatisticsHelper::EstimateSemiAntiJoinFallback(preserved.GetCardinality(), + rhs.GetCardinality(), join.join_type); if (estimate.cardinality < fallback.cardinality) { return fallback; } @@ -146,17 +148,19 @@ void RelationStatisticsHelper::ApplySemiAntiJoinStats(LogicalComparisonJoin &joi auto &rhs = preserve_right ? left : right; D_ASSERT(join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI || join.join_type == JoinType::RIGHT_SEMI || join.join_type == JoinType::RIGHT_ANTI); - D_ASSERT(result.cardinality == preserved.cardinality); bool has_residual; auto domains = ExtractSemiAntiJoinDomains(join, preserved, rhs, has_residual); auto estimate = EstimateSemiAntiJoin(join, preserved, rhs, domains, has_residual); result.row_retention = preserved.row_retention; - // Keep exact empty-input results and the original integer upper limit across double conversion. - auto cardinality = MinValue(preserved.cardinality, CardinalityFromDouble(estimate.cardinality)); - if (rhs.cardinality == 0 && (join.join_type == JoinType::ANTI || join.join_type == JoinType::RIGHT_ANTI)) { - cardinality = preserved.cardinality; + result.cardinality = preserved.GetCardinality(); + result.max_cardinality = JoinCardinalityBound(join.join_type, left.max_cardinality, right.max_cardinality); + for (auto &column : result.columns) { + auto source = preserved.GetColumnStats(column.binding); + if (source) { + column.semi_anti_join_domain_evidence = source->semi_anti_join_domain_evidence; + } } - ApplyCardinality(result, cardinality); + ApplyCardinality(result, estimate.cardinality); if (join.join_type == JoinType::SEMI || join.join_type == JoinType::RIGHT_SEMI) { for (auto &domain : domains) { auto column_index = result.FindColumn(domain.preserved_binding); @@ -175,6 +179,8 @@ static optional ExtractGetWithChildStats(LogicalGet &get, ClientC const RelationStats &child_stats) { auto result = RelationStatisticsHelper::ExtractGetStats(get, context); result.cardinality = child_stats.cardinality; + // A table-in/table-out function can expand its input. + result.max_cardinality = optional_idx(); RelationColumnStatsLookup child_columns(child_stats); for (auto &binding : get.GetColumnBindings()) { if (binding.table_index == get.table_index) { @@ -233,28 +239,31 @@ static optional ExtractComparisonJoinStats(LogicalComparisonJoin return result; } auto cardinality = JoinCardinality(join, child_stats[0], child_stats[1]); - auto result = ProjectChildStats(join, child_stats, cardinality); - if (result || join.join_type != JoinType::MARK) { - return result; + auto maximum = RelationStatisticsHelper::JoinCardinalityBound(join.join_type, child_stats[0].get().max_cardinality, + child_stats[1].get().max_cardinality); + if (join.join_type != JoinType::MARK) { + return ProjectChildStats(join, child_stats, cardinality, maximum); } RelationStats mark_result; mark_result.cardinality = cardinality; + mark_result.max_cardinality = maximum; + mark_result.row_retention = child_stats[0].get().row_retention; mark_result.stats_initialized = true; mark_result.table_name = Identifier(join.GetName()); RelationColumnStatsLookup left_columns(child_stats[0].get()); for (auto &binding : join.GetColumnBindings()) { auto column = left_columns.Find(binding); if (column) { - mark_result.columns.emplace_back(binding, column->total_domain, column->current_domain, column->name); + mark_result.columns.push_back(*column); } else if (binding.table_index == join.mark_index) { - mark_result.columns.emplace_back( - binding, DistinctCount(MinValue(cardinality, 3), DistinctCountSource::CARDINALITY), - Identifier("mark")); + mark_result.columns.emplace_back(binding, DistinctCount(3, DistinctCountSource::CARDINALITY), + Identifier("mark")); } else { return {}; } } + mark_result.CapCurrentDomainsToCardinality(); mark_result.Verify(join.GetColumnBindings()); return mark_result; } @@ -264,20 +273,11 @@ static optional ExtractCrossProductStats(LogicalOperator &op, if (child_stats.size() != 2) { return {}; } - idx_t cardinality; - if (!TryMultiplyOperator::Operation(child_stats[0].get().cardinality, child_stats[1].get().cardinality, - cardinality)) { - cardinality = NumericLimits::Maximum(); - } - return ProjectChildStats(op, child_stats, cardinality); -} - -static idx_t AddDistinctCounts(idx_t left, idx_t right) { - idx_t result; - if (!TryAddOperator::Operation(left, right, result)) { - return NumericLimits::Maximum(); - } - return result; + auto &left = child_stats[0].get(); + auto &right = child_stats[1].get(); + auto cardinality = left.GetCardinality() * right.GetCardinality(); + auto maximum = RelationStatisticsHelper::MultiplyCardinalityBounds(left.max_cardinality, right.max_cardinality); + return ProjectChildStats(op, child_stats, cardinality, maximum); } static optional ExtractSetOperationStats(LogicalSetOperation &setop, @@ -292,18 +292,28 @@ static optional ExtractSetOperationStats(LogicalSetOperation &set switch (setop.type) { case LogicalOperatorType::LOGICAL_UNION: result.cardinality = 0; + result.max_cardinality = optional_idx(0); for (auto &child : child_stats) { - result.cardinality = AddDistinctCounts(result.cardinality, child.get().cardinality); + result.cardinality += child.get().cardinality; + result.max_cardinality = + RelationStatisticsHelper::AddCardinalityBounds(result.max_cardinality, child.get().max_cardinality); } break; case LogicalOperatorType::LOGICAL_INTERSECT: result.cardinality = child_stats[0].get().cardinality; - for (idx_t child_idx = 1; child_idx < child_stats.size(); child_idx++) { - result.cardinality = MinValue(result.cardinality, child_stats[child_idx].get().cardinality); + for (auto &child : child_stats) { + result.cardinality = MinValue(result.cardinality, child.get().cardinality); + auto maximum = child.get().max_cardinality; + if (maximum.IsValid()) { + result.max_cardinality = optional_idx( + result.max_cardinality.IsValid() ? MinValue(result.max_cardinality.GetIndex(), maximum.GetIndex()) + : maximum.GetIndex()); + } } break; case LogicalOperatorType::LOGICAL_EXCEPT: result.cardinality = child_stats[0].get().cardinality; + result.max_cardinality = child_stats[0].get().max_cardinality; break; default: return {}; @@ -324,10 +334,8 @@ static optional ExtractSetOperationStats(LogicalSetOperation &set auto &child_column = child_stats[child_idx].get().columns[column_idx]; switch (setop.type) { case LogicalOperatorType::LOGICAL_UNION: - total_domain.distinct_count = - AddDistinctCounts(total_domain.distinct_count, child_column.total_domain.distinct_count); - current_domain.distinct_count = - AddDistinctCounts(current_domain.distinct_count, child_column.current_domain.distinct_count); + total_domain.distinct_count += child_column.total_domain.distinct_count; + current_domain.distinct_count += child_column.current_domain.distinct_count; total_domain.source = DistinctCountSource::CARDINALITY; current_domain.source = DistinctCountSource::CARDINALITY; break; @@ -356,6 +364,7 @@ static optional ExtractSetOperationStats(LogicalSetOperation &set RelationStats RelationStatisticsHelper::ExtractExplainStats(LogicalOperator &op) { RelationStats result; result.cardinality = 3; + result.max_cardinality = optional_idx(3); result.stats_initialized = true; result.table_name = Identifier(op.GetName()); for (auto &binding : op.GetColumnBindings()) { diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp index b738f0f21..27ea0c190 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp @@ -4,6 +4,7 @@ #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/subtract.hpp" +#include "duckdb/common/string_util.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/function/partition_stats.hpp" #include "duckdb/function/table/table_scan.hpp" @@ -21,6 +22,9 @@ #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/storage/data_table.hpp" #include "duckdb/storage/statistics/numeric_stats.hpp" +#include "duckdb/storage/statistics/node_statistics.hpp" + +#include namespace duckdb { @@ -119,21 +123,19 @@ static DistinctCount GetDistinctCountFromStats(BaseStatistics &base_stats, idx_t } struct FilterEstimate { - idx_t cardinality; + CardinalityValue cardinality; bool supported; + bool proven_empty = false; void Combine(const FilterEstimate &other) { cardinality = MinValue(cardinality, other.cardinality); supported &= other.supported; + proven_empty |= other.proven_empty; } }; -static idx_t FilterFraction(idx_t cardinality, double fraction) { - if (cardinality == 0) { - return 0; - } - return MinValue(cardinality, MaxValue(1, RelationStatisticsHelper::CardinalityFromDouble( - double(cardinality) * fraction))); +static CardinalityValue FilterFraction(CardinalityValue cardinality, double fraction) { + return cardinality * CardinalityValue(MaxValue(0.0, MinValue(fraction, 1.0))); } class IntegerRangeEstimate { @@ -221,7 +223,7 @@ static optional_ptr FilterColumn(const Expression &ex return nullptr; } -static FilterEstimate EstimateNullCheckRows(idx_t cardinality, const BoundOperatorExpression &expr, +static FilterEstimate EstimateNullCheckRows(CardinalityValue cardinality, const BoundOperatorExpression &expr, const RelationColumnStatsLookup &columns, const vector &positional_bindings) { auto &children = expr.GetChildren(); @@ -234,7 +236,8 @@ static FilterEstimate EstimateNullCheckRows(idx_t cardinality, const BoundOperat true}; } -static FilterEstimate EstimateEqualityRows(idx_t cardinality, ExpressionType type, const RelationColumnStats &column) { +static FilterEstimate EstimateEqualityRows(CardinalityValue cardinality, ExpressionType type, + const RelationColumnStats &column) { const auto selectivity = RelationStatisticsHelper::DEFAULT_SELECTIVITY; bool equal = type == ExpressionType::COMPARE_EQUAL || type == ExpressionType::COMPARE_NOT_DISTINCT_FROM; if (cardinality == 0) { @@ -247,12 +250,23 @@ static FilterEstimate EstimateEqualityRows(idx_t cardinality, ExpressionType typ if (domain == 0) { return {cardinality, false}; } - return {equal ? cardinality / domain + (cardinality % domain != 0) - : FilterFraction(cardinality, 1 - 1.0 / double(domain)), - true}; + auto fraction = MinValue(CardinalityValue(1), CardinalityValue(1) / domain); + auto rows = cardinality * (equal ? fraction : CardinalityValue(1) - fraction); + // Retain the existing equality-filter ceiling independently of fractional join estimates. + // Do not inflate a fractional input or materialize a scaled estimate outside double's range. + if (equal && rows > 1) { + auto value = rows.GetDouble(); + if (std::isfinite(value)) { + auto rounded = std::ceil(value); + if (rounded > value) { + rows = MinValue(cardinality, CardinalityValue(rounded)); + } + } + } + return {rows, true}; } -static FilterEstimate EstimateComparisonRows(idx_t cardinality, const BoundFunctionExpression &comparison, +static FilterEstimate EstimateComparisonRows(CardinalityValue cardinality, const BoundFunctionExpression &comparison, const RelationColumnStatsLookup &columns, const vector &positional_bindings, FilterPropagateResult pruning, optional_ptr range) { @@ -277,7 +291,7 @@ static FilterEstimate EstimateComparisonRows(idx_t cardinality, const BoundFunct type == ExpressionType::COMPARE_NOT_DISTINCT_FROM ? selectivity : 1 - selectivity), true}; } - return {0, true}; + return {0, true, true}; } if (pruning == FilterPropagateResult::FILTER_TRUE_OR_NULL && type != ExpressionType::COMPARE_DISTINCT_FROM && type != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { @@ -303,7 +317,7 @@ static FilterEstimate EstimateComparisonRows(idx_t cardinality, const BoundFunct } } -static FilterEstimate EstimateFilterRows(idx_t cardinality, const Expression &expr, +static FilterEstimate EstimateFilterRows(CardinalityValue cardinality, const Expression &expr, const RelationColumnStatsLookup &columns, const vector &positional_bindings, optional_ptr context = nullptr, @@ -328,12 +342,13 @@ static FilterEstimate EstimateFilterRows(idx_t cardinality, const Expression &ex } if (pruning == FilterPropagateResult::FILTER_ALWAYS_FALSE || pruning == FilterPropagateResult::FILTER_FALSE_OR_NULL) { - return {0, true}; + return {0, true, true}; } } if (expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT && expr.GetReturnType() == LogicalType::BOOLEAN) { auto &value = expr.Cast().GetValue(); - return {value.IsNull() || !BooleanValue::Get(value) ? 0 : cardinality, true}; + auto empty = value.IsNull() || !BooleanValue::Get(value); + return {empty ? CardinalityValue(0) : cardinality, true, empty}; } // Preserve the existing scan-specific non-null NOT LIKE estimate. if (scan_statistics && expr.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION && @@ -352,6 +367,9 @@ static FilterEstimate EstimateFilterRows(idx_t cardinality, const Expression &ex } static void ApplyFilterEstimate(RelationStats &stats, FilterEstimate estimate) { + if (estimate.proven_empty) { + stats.max_cardinality = optional_idx(0); + } if (!estimate.supported) { // An unsupported conjunct retains its fallback even when another conjunct has a weaker estimate. estimate.cardinality = MinValue( @@ -365,14 +383,17 @@ static void ApplyFilterDomainCap(RelationColumnStats &column, optional_idx cap) return; } column.current_domain = - DistinctCount(MinValue(column.current_domain.distinct_count, cap.GetIndex()), DistinctCountSource::CARDINALITY); + DistinctCount(MinValue(column.current_domain.distinct_count, CardinalityValue(cap.GetIndex())), + DistinctCountSource::CARDINALITY); column.semi_anti_join_domain_evidence.TightenDomainBound(cap.GetIndex()); } static void ApplyDirectFilterDomain(RelationColumnStats &column, const Expression &expression, optional binding) { - ApplyFilterDomainCap(column, RelationStatisticsHelper::EstimateDirectFilterDomain( - expression, binding, column.total_domain.distinct_count)); + auto bound = column.semi_anti_join_domain_evidence.GetDomainBound(); + ApplyFilterDomainCap( + column, RelationStatisticsHelper::EstimateDirectFilterDomain( + expression, binding, bound.IsValid() ? bound.GetIndex() : NumericLimits::Maximum())); } //===--------------------------------------------------------------------===// @@ -392,7 +413,7 @@ struct ZonemapFilter { //! can satisfy every table filter of the scan. A row group that cannot be skipped counts whole. //! Returns an invalid index if the bound is not below the estimate that the scan already has. static optional_idx ZonemapFilterBound(LogicalGet &get, ClientContext &context, - const vector &scan_statistics, idx_t estimate) { + const vector &scan_statistics, CardinalityValue estimate) { //! The work per plan is limited to the row groups of a table of this many row groups (2 billion rows at the //! default row group size). A larger table keeps its estimate: checking only some of its row groups would not //! give a bound, as the row groups that are not checked can hold all of the matching rows @@ -461,14 +482,16 @@ static optional_idx ZonemapFilterBound(LogicalGet &get, ClientContext &context, if (skipped) { continue; } - matching_rows += partition.count; + if (!TryAddOperator::Operation(matching_rows, partition.count, matching_rows)) { + return {}; + } if (matching_rows >= estimate) { // the bound only grows from here on: it cannot improve on the estimate, so the remaining row groups // need not be read return optional_idx(); } } - return MaxValue(1, matching_rows); + return optional_idx(matching_rows); } unique_ptr RelationStatisticsHelper::GetColumnStatistics(LogicalGet &get, ClientContext &context, @@ -484,14 +507,24 @@ unique_ptr RelationStatisticsHelper::GetColumnStatistics(Logical } RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientContext &context) { - return ExtractGetStats(get, context, get.EstimateSourceCardinality(context)); + return ExtractGetStats(get, context, get.EstimateSourceStatistics(context)); } RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientContext &context, idx_t base_table_cardinality) { + return ExtractGetStats(get, context, NodeStatistics(base_table_cardinality)); +} + +RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientContext &context, + const NodeStatistics &source_stats) { + D_ASSERT(source_stats.has_estimated_cardinality); + auto base_table_cardinality = source_stats.estimated_cardinality; RelationStats result; result.cardinality = base_table_cardinality; - result.row_retention = base_table_cardinality == 0 ? 0 : 1; + if (source_stats.has_max_cardinality) { + result.max_cardinality = optional_idx(source_stats.max_cardinality); + } + result.row_retention = result.IsEmpty() ? 0 : 1; result.table_name = get.GetTable() ? get.GetTable()->name : Identifier(get.GetName()); // Include hidden filter columns, and acquire each scanned column's provider statistics once. @@ -528,8 +561,9 @@ RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientC if (fraction) { // Intersect same-column bounds before applying the default-selectivity floor. auto range_cardinality = - *fraction == 0 ? 0 : FilterFraction(base_table_cardinality, MaxValue(DEFAULT_SELECTIVITY, *fraction)); - estimate.Combine({range_cardinality, true}); + *fraction == 0 ? CardinalityValue(0) + : FilterFraction(base_table_cardinality, MaxValue(DEFAULT_SELECTIVITY, *fraction)); + estimate.Combine({range_cardinality, true, *fraction == 0}); } } if (get.table_filters.HasFilters()) { @@ -542,7 +576,7 @@ RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientC if (current_estimate > 1) { auto zonemap_bound = ZonemapFilterBound(get, context, scan_statistics, current_estimate); if (zonemap_bound.IsValid()) { - estimate.Combine({zonemap_bound.GetIndex(), true}); + estimate.Combine({zonemap_bound.GetIndex(), true, zonemap_bound.GetIndex() == 0}); } } } @@ -564,25 +598,34 @@ RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientC } result.columns = std::move(output_columns); result.stats_initialized = true; - D_ASSERT(base_table_cardinality >= result.cardinality); + D_ASSERT(base_table_cardinality == 0 || base_table_cardinality >= result.cardinality); return result; } optional RelationStatisticsHelper::ExtractFilterStats(LogicalFilter &filter, const RelationStats &child_stats) { - auto result = ProjectOutputStats(child_stats, filter); - if (!result) { - return {}; - } + return ExtractFilterStats(filter, child_stats, filter.expressions); +} + +optional +RelationStatisticsHelper::ExtractFilterStats(LogicalFilter &filter, const RelationStats &child_stats, + const vector> &expressions) { + auto result = ConditionFilterStats(child_stats, expressions, filter.children[0]->GetColumnBindings()); + return ProjectOutputStats(result, filter); +} + +RelationStats RelationStatisticsHelper::ConditionFilterStats(const RelationStats &child_stats, + const vector> &expressions, + const vector &bindings) { + auto result = child_stats; RelationColumnStatsLookup columns(child_stats); - auto bindings = filter.children[0]->GetColumnBindings(); FilterEstimate estimate {child_stats.cardinality, true}; - for (auto &expression : filter.expressions) { + for (auto &expression : expressions) { estimate.Combine(EstimateFilterRows(child_stats.cardinality, *expression, columns, bindings)); } - ApplyFilterEstimate(*result, estimate); - for (auto &column : result->columns) { - for (auto &expression : filter.expressions) { + ApplyFilterEstimate(result, estimate); + for (auto &column : result.columns) { + for (auto &expression : expressions) { ApplyDirectFilterDomain(column, *expression, column.binding); } } @@ -596,7 +639,7 @@ RelationStats RelationStatisticsHelper::ExtractDelimGetStats(LogicalDelimGet &de result.stats_initialized = true; for (auto &binding : delim_get.GetColumnBindings()) { result.columns.emplace_back(binding, DistinctCount(1, DistinctCountSource::CARDINALITY), - Identifier("column" + to_string(binding.column_index))); + Identifier(StringUtil::Format("column%llu", binding.column_index.GetIndex()))); } result.CapCurrentDomainsToCardinality(); result.Verify(delim_get.GetColumnBindings()); @@ -606,6 +649,7 @@ RelationStats RelationStatisticsHelper::ExtractDelimGetStats(LogicalDelimGet &de RelationStats RelationStatisticsHelper::ExtractDummyScanStats(LogicalDummyScan &dummy_scan, ClientContext &context) { RelationStats result; result.cardinality = dummy_scan.EstimateCardinality(context); + result.max_cardinality = optional_idx(1); result.table_name = "dummy scan"; result.stats_initialized = true; for (auto &binding : dummy_scan.GetColumnBindings()) { @@ -620,6 +664,10 @@ RelationStats RelationStatisticsHelper::ExtractExpressionGetStats(LogicalExpress ClientContext &context) { RelationStats result; result.cardinality = expression_get.EstimateCardinality(context); + if (expression_get.children.size() == 1 && + expression_get.children[0]->type == LogicalOperatorType::LOGICAL_DUMMY_SCAN) { + result.max_cardinality = optional_idx(expression_get.expressions.size()); + } result.table_name = "expression_get"; result.stats_initialized = true; for (auto &binding : expression_get.GetColumnBindings()) { @@ -638,13 +686,21 @@ RelationStats RelationStatisticsHelper::ExtractColumnDataGetStats(LogicalColumnD ClientContext &) { RelationStats result; result.cardinality = column_data_get.collection->Count(); + // Borrowed or shared collections can be populated after planning. + if (column_data_get.collection.get_owned_unique()) { + result.max_cardinality = optional_idx(column_data_get.collection->Count()); + } result.table_name = Identifier(column_data_get.GetName()); result.stats_initialized = true; for (auto &binding : column_data_get.GetColumnBindings()) { result.columns.emplace_back(binding, DistinctCount(result.cardinality, DistinctCountSource::CARDINALITY), Identifier("column_data")); - result.columns.back().semi_anti_join_domain_evidence.TightenDomainBound(result.cardinality); + if (column_data_get.collection.get_owned_unique()) { + result.columns.back().semi_anti_join_domain_evidence.TightenDomainBound( + column_data_get.collection->Count()); + } } + result.CapCurrentDomainsToCardinality(); result.Verify(column_data_get.GetColumnBindings()); return result; } diff --git a/src/duckdb/src/optimizer/row_group_pruner.cpp b/src/duckdb/src/optimizer/row_group_pruner.cpp index 4690d3a53..1ce4bbf6b 100644 --- a/src/duckdb/src/optimizer/row_group_pruner.cpp +++ b/src/duckdb/src/optimizer/row_group_pruner.cpp @@ -142,10 +142,10 @@ optional_ptr RowGroupPruner::FindLogicalGet(const LogicalOrder &logi JoinFilterPushdownColumn column; column.probe_column_index = colref.Binding(); - vector columns {std::move(column)}; + vector columns; + columns.push_back(std::move(column)); vector pushdown_targets; - JoinFilterPushdownOptimizer::GetPushdownFilterTargets(*logical_order.children[0], std::move(columns), - pushdown_targets); + JoinFilterPushdownOptimizer::GetPushdownFilterTargets(*logical_order.children[0], columns, pushdown_targets); if (pushdown_targets.size() != 1 || pushdown_targets[0].columns.size() != 1) { return nullptr; diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp index 6bf0c4fca..f5077996c 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_aggregate.cpp @@ -609,6 +609,7 @@ void StatisticsPropagator::TryExecuteAggregates(LogicalAggregate &aggr, unique_p replacer.stop_operator = projection.get(); node_ptr = std::move(projection); + node_ptr->ResolveOperatorTypes(); replacer.VisitOperator(*root); return; } @@ -623,6 +624,7 @@ void StatisticsPropagator::TryExecuteAggregates(LogicalAggregate &aggr, unique_p auto expression_get = make_uniq(aggr.aggregate_index, std::move(types), std::move(expressions)); expression_get->children.push_back(make_uniq(aggr.group_index)); + expression_get->ResolveOperatorTypes(); node_ptr = std::move(expression_get); } diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp index 082553e99..4fba090e1 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp @@ -556,6 +556,8 @@ void StatisticsPropagator::CreateFilterFromJoinStats(unique_ptr FilterPushdown filter_pushdown(optimizer); child = filter_pushdown.Rewrite(std::move(child)); + // Filter pushdown can introduce operators below an already propagated child. + child->ResolveOperatorTypes(); PropagateExpression(expr); } diff --git a/src/duckdb/src/optimizer/statistics_propagator.cpp b/src/duckdb/src/optimizer/statistics_propagator.cpp index 38e8a9917..af4309f17 100644 --- a/src/duckdb/src/optimizer/statistics_propagator.cpp +++ b/src/duckdb/src/optimizer/statistics_propagator.cpp @@ -41,6 +41,8 @@ unique_ptr StatisticsPropagator::PropagateExpressionStatistics( void StatisticsPropagator::ReplaceWithEmptyResult(unique_ptr &node) { node = make_uniq(std::move(node)); + // A parent may retain this replacement as an already propagated child. + node->ResolveOperatorTypesFromChildren(); } unique_ptr StatisticsPropagator::PropagateChildren(LogicalOperator &node, @@ -135,6 +137,8 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalOper result = PropagateChildren(node, node_ptr); } + // Children have been propagated; only this operator's output types need refreshing. + node_ptr->ResolveOperatorTypesFromChildren(); if (mode == StatisticsPropagationMode::FULL && !optimizer.OptimizerDisabled(OptimizerType::COMPRESSED_MATERIALIZATION)) { // compress data based on statistics for materializing operators @@ -147,7 +151,12 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalOper } unique_ptr StatisticsPropagator::PropagateStatistics(unique_ptr &node_ptr) { - return PropagateStatistics(*node_ptr, node_ptr); + auto result = PropagateStatistics(*node_ptr, node_ptr); + if (propagation_path.empty() && Settings::Get(context)) { + // Check our bottom-up invariant before the ordinary plan verifier can repair stale types. + node_ptr->VerifyOperatorTypes(); + } + return result; } unique_ptr StatisticsPropagator::PropagateStatistics(LogicalCopyToFile &op, diff --git a/src/duckdb/src/optimizer/topn_optimizer.cpp b/src/duckdb/src/optimizer/topn_optimizer.cpp index 4a710a68d..03d26170e 100644 --- a/src/duckdb/src/optimizer/topn_optimizer.cpp +++ b/src/duckdb/src/optimizer/topn_optimizer.cpp @@ -66,9 +66,9 @@ shared_ptr TopN::PushDynamicFilterIntoScans(ClientContext &co vector columns; JoinFilterPushdownColumn column; column.probe_column_index = binding; - columns.emplace_back(column); + columns.push_back(std::move(column)); vector pushdown_targets; - JoinFilterPushdownOptimizer::GetPushdownFilterTargets(child, std::move(columns), pushdown_targets); + JoinFilterPushdownOptimizer::GetPushdownFilterTargets(child, columns, pushdown_targets); if (pushdown_targets.empty()) { // no pushdown targets return nullptr; diff --git a/src/duckdb/src/parser/parsed_data/transaction_info.cpp b/src/duckdb/src/parser/parsed_data/transaction_info.cpp index 5d5e2e4cf..1c55adb34 100644 --- a/src/duckdb/src/parser/parsed_data/transaction_info.cpp +++ b/src/duckdb/src/parser/parsed_data/transaction_info.cpp @@ -1,5 +1,6 @@ #include "duckdb/parser/parsed_data/transaction_info.hpp" #include "duckdb/common/enum_util.hpp" +#include "duckdb/common/sql_identifier.hpp" namespace duckdb { @@ -24,6 +25,8 @@ string TransactionInfo::ToString() const { case TransactionType::ROLLBACK: result += "ROLLBACK"; break; + case TransactionType::JOIN_TRANSACTION: + return "JOIN TRANSACTION " + SQLString(share_id) + ";"; default: { throw InternalException("ToString for TransactionStatement with type: %s not implemented", EnumUtil::ToString(type)); @@ -51,6 +54,7 @@ unique_ptr TransactionInfo::Copy() const { result->modifier = modifier; result->invalidation_policy = invalidation_policy; result->auto_rollback = auto_rollback; + result->share_id = share_id; return result; } diff --git a/src/duckdb/src/parser/peg/peg_rule_id.cpp b/src/duckdb/src/parser/peg/peg_rule_id.cpp index 84dc99b9c..0e4fd5f21 100644 --- a/src/duckdb/src/parser/peg/peg_rule_id.cpp +++ b/src/duckdb/src/parser/peg/peg_rule_id.cpp @@ -1203,6 +1203,7 @@ static const char *const PEG_RULE_NAMES[] = { "BeginTransaction", "RollbackTransaction", "CommitTransaction", + "JoinTransaction", "StartOrBegin", "Transaction", "ReadOrWrite", 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 826a8a6e8..3aae38af0 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp @@ -9599,6 +9599,8 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { &PEGTransformerFactory::FinalizeRollbackTransactionTrampoline, &FRAME_PLAN_Leaf}, {"CommitTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCommitTransactionTrampoline, &FRAME_PLAN_Leaf}, + {"JoinTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeJoinTransactionTrampoline, &FRAME_PLAN_Leaf}, {"ReadOrWrite", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_ReadOrWrite}, {"ReadOnlyOrReadWrite", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -19968,6 +19970,15 @@ PEGTransformerFactory::FinalizeCommitTransactionTrampoline(PEGTransformer &trans return transformer.MakeResult>(std::move(result)); } +arena_ptr +PEGTransformerFactory::FinalizeJoinTransactionTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto &list_pr = process.parse_result.Cast(); + auto string_literal = TransformStringLiteral(transformer, list_pr.GetChild(2)); + auto result = TransformJoinTransaction(transformer, string_literal); + return transformer.MakeResult>(std::move(result)); +} + arena_ptr PEGTransformerFactory::FinalizeReadOrWriteTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { auto read_only_or_read_write = process.TakeResult(0); diff --git a/src/duckdb/src/parser/peg/transformer/transform_transaction.cpp b/src/duckdb/src/parser/peg/transformer/transform_transaction.cpp index 487cf2614..31b538f21 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_transaction.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_transaction.cpp @@ -32,6 +32,13 @@ unique_ptr PEGTransformerFactory::TransformCommitTransaction(PEGTr return make_uniq(make_uniq(TransactionType::COMMIT)); } +unique_ptr PEGTransformerFactory::TransformJoinTransaction(PEGTransformer &transformer, + const string &share_id) { + auto info = make_uniq(TransactionType::JOIN_TRANSACTION); + info->share_id = share_id; + return make_uniq(std::move(info)); +} + unique_ptr PEGTransformerFactory::TransformRollbackTransaction(PEGTransformer &transformer, const bool &has_result) { return make_uniq(make_uniq(TransactionType::ROLLBACK)); diff --git a/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp b/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp index 77de85464..9d5273695 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp @@ -358,8 +358,12 @@ BoundStatement Binder::Bind(BaseTableRef &ref) { if (!view_binder->correlated_columns.empty()) { throw BinderException("Contents of view were altered - view bound correlated columns"); } - // update the view binding with the bound view information - view_catalog_entry.UpdateBinding(bound_child.types, bound_child.names); + if (GetBindingMode() == BindingMode::STANDARD_BINDING) { + // update the view binding with the bound view information + // skipped in other binding modes - e.g. in EXTRACT_NAMES mode tables bind as dummy columns, + // and storing those would corrupt the view's cached column information + view_catalog_entry.UpdateBinding(bound_child.types, bound_child.names); + } auto root_index = bound_child.plan->GetRootIndex(); if (view_catalog_entry.security_type == ViewSecurityType::SECURE_VIEW) { // wrap the plan of a secure view - this prevents the optimizer from pushing into the view diff --git a/src/duckdb/src/planner/expression_binder/index_binder.cpp b/src/duckdb/src/planner/expression_binder/index_binder.cpp index 01c472485..0ad5b04da 100644 --- a/src/duckdb/src/planner/expression_binder/index_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/index_binder.cpp @@ -25,6 +25,7 @@ #include "duckdb/function/cast/bound_cast_data.hpp" #include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/main/attached_database.hpp" +#include "duckdb/storage/index_storage_info.hpp" #include "duckdb/storage/storage_manager.hpp" namespace duckdb { @@ -269,6 +270,88 @@ void ThrowMismatchedStoredKey(const UnboundIndex &unbound_index, StorageVersion name); } +//! The types the keys of an index were stored with, from the record of the index: a record that is not a list of +//! types is a damaged file +vector ReadStoredKeyTypes(const UnboundIndex &unbound_index, const Value &record) { + auto corrupt = [&](const string &what) { + return DataCorruptionException("Corrupt index %s on table %s: the record of the types of its keys %s", + unbound_index.GetIndexName(), unbound_index.GetTableName(), what); + }; + if (record.IsNull() || record.type().id() != LogicalTypeId::LIST || + ListType::GetChildType(record.type()).id() != LogicalTypeId::TYPE) { + throw corrupt(StringUtil::Format("is not a list of types (%s)", record.ToSQLString())); + } + vector result; + for (auto &stored : ListValue::GetChildren(record)) { + if (stored.IsNull()) { + throw corrupt("holds a NULL"); + } + try { + result.push_back(TypeValue::GetType(stored)); + } catch (std::exception &ex) { + throw corrupt(StringUtil::Format("holds a type that cannot be read: %s", ErrorData(ex).RawMessage())); + } + } + return result; +} + +//! Whether keys stored with a type are encoded like the keys an expression of another type computes: the types are +//! the same, or decimals of the same scale and physical type, whose width does not enter the encoding +bool StoredKeyTypeMatches(const LogicalType &stored, const LogicalType &bound) { + if (stored == bound) { + return true; + } + if (stored.id() != LogicalTypeId::DECIMAL || bound.id() != LogicalTypeId::DECIMAL) { + return false; + } + return stored.InternalType() == bound.InternalType() && + DecimalType::GetScale(stored) == DecimalType::GetScale(bound); +} + +//! Why the stored keys of an index stored from the storage version of wide decimals on cannot be matched by the keys +//! its expressions compute now, empty when they can. The stored keys are encoded from the types the expressions were +//! bound to, which the index records: an expression that binds to another type now (the result type of a function is +//! decided by the engine that binds it) computes keys of another encoding. The engines of that storage version that +//! stored no record bound the same column types, so their keys over plain columns match; the type their key +//! expressions had is unknown +string DescribeStoredKeyTypeDifference(const UnboundIndex &unbound_index, const vector> &keys, + const IndexStorageInfo &storage_info) { + auto entry = storage_info.options.find("key_types"); + if (entry == storage_info.options.end()) { + for (auto &key : keys) { + if (key->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF && + key->GetExpressionClass() != ExpressionClass::BOUND_REF) { + return StringUtil::Format("the index does not record the types of its stored keys, and the type of " + "its key expression %s (%s now) is decided by the engine that binds it", + key->ToString(), key->GetReturnType().ToString()); + } + } + return string(); + } + auto stored_types = ReadStoredKeyTypes(unbound_index, entry->second); + if (stored_types.size() != keys.size()) { + return StringUtil::Format("the index stores %llu keys, its definition has %llu", stored_types.size(), + keys.size()); + } + for (idx_t i = 0; i < keys.size(); i++) { + auto &type = keys[i]->GetReturnType(); + if (!StoredKeyTypeMatches(stored_types[i], type)) { + return StringUtil::Format("the stored keys of %s have the type %s, the expression binds to %s now", + keys[i]->ToString(), stored_types[i].ToString(), type.ToString()); + } + } + return string(); +} + +void ThrowMismatchedStoredKeyType(const UnboundIndex &unbound_index, const string &difference) { + auto &name = unbound_index.GetIndexName(); + throw BinderException( + "Cannot bind index %s on table %s: %s, so the stored keys cannot be matched with the keys this " + "engine computes. DROP INDEX %s and CREATE it again; until then writes to the table fail, as does " + "a CHECKPOINT after writes replayed from the write-ahead log", + name, unbound_index.GetTableName(), difference, name); +} + //! The keys of a new index are stored at the storage version of its database: a key the engines of that version //! compute otherwise is refused, like a column type they cannot read, so that they compute the stored keys void CheckNewKeys(AttachedDatabase &db, const vector> &keys, const IndexKeyBinding &binding) { @@ -388,6 +471,14 @@ unique_ptr IndexBinder::BindIndex(const UnboundIndex &unbound_index, } ThrowMismatchedStoredKey(unbound_index, binding.version, difference); } + } else if (storage_info.IsValid()) { + auto difference = DescribeStoredKeyTypeDifference(unbound_index, unbound_expressions, storage_info); + if (!difference.empty()) { + if (skip_mismatched_keys) { + return nullptr; + } + ThrowMismatchedStoredKeyType(unbound_index, difference); + } } CreateIndexInput input(context, unbound_index.table_io_manager, unbound_index.db, create_info.constraint_type, diff --git a/src/duckdb/src/planner/filter/constant_filter_combiner.cpp b/src/duckdb/src/planner/filter/constant_filter_combiner.cpp new file mode 100644 index 000000000..a20f81f04 --- /dev/null +++ b/src/duckdb/src/planner/filter/constant_filter_combiner.cpp @@ -0,0 +1,163 @@ +#include "duckdb/planner/filter/constant_filter_combiner.hpp" + +namespace duckdb { + +bool ConstantFilterCombiner::IsSupportedComparison(ExpressionType expression_type) { + switch (expression_type) { + case ExpressionType::COMPARE_EQUAL: + case ExpressionType::COMPARE_GREATERTHAN: + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + case ExpressionType::COMPARE_LESSTHAN: + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + case ExpressionType::COMPARE_NOTEQUAL: + return true; + default: + return false; + } +} + +static ValueComparisonResult InvertValueComparisonResult(ValueComparisonResult result) { + if (result == ValueComparisonResult::PRUNE_RIGHT) { + return ValueComparisonResult::PRUNE_LEFT; + } + if (result == ValueComparisonResult::PRUNE_LEFT) { + return ValueComparisonResult::PRUNE_RIGHT; + } + return result; +} + +ValueComparisonResult ConstantFilterCombiner::Compare(const ConstantComparison &left, const ConstantComparison &right) { + if (left.comparison_type == ExpressionType::COMPARE_EQUAL) { + // left is COMPARE_EQUAL, we can either + // (1) prune the right side or + // (2) return UNSATISFIABLE + bool prune_right_side = false; + switch (right.comparison_type) { + case ExpressionType::COMPARE_LESSTHAN: + prune_right_side = left.constant < right.constant; + break; + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + prune_right_side = left.constant <= right.constant; + break; + case ExpressionType::COMPARE_GREATERTHAN: + prune_right_side = left.constant > right.constant; + break; + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + prune_right_side = left.constant >= right.constant; + break; + case ExpressionType::COMPARE_NOTEQUAL: + prune_right_side = left.constant != right.constant; + break; + default: + D_ASSERT(right.comparison_type == ExpressionType::COMPARE_EQUAL); + prune_right_side = left.constant == right.constant; + break; + } + if (prune_right_side) { + return ValueComparisonResult::PRUNE_RIGHT; + } else { + return ValueComparisonResult::UNSATISFIABLE_CONDITION; + } + } else if (right.comparison_type == ExpressionType::COMPARE_EQUAL) { + // right is COMPARE_EQUAL + return InvertValueComparisonResult(Compare(right, left)); + } else if (left.comparison_type == ExpressionType::COMPARE_NOTEQUAL) { + // left is COMPARE_NOTEQUAL, we can either + // (1) prune the left side or + // (2) not prune anything + bool prune_left_side = false; + switch (right.comparison_type) { + case ExpressionType::COMPARE_LESSTHAN: + prune_left_side = left.constant >= right.constant; + break; + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + prune_left_side = left.constant > right.constant; + break; + case ExpressionType::COMPARE_GREATERTHAN: + prune_left_side = left.constant <= right.constant; + break; + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + prune_left_side = left.constant < right.constant; + break; + default: + D_ASSERT(right.comparison_type == ExpressionType::COMPARE_NOTEQUAL); + prune_left_side = left.constant == right.constant; + break; + } + if (prune_left_side) { + return ValueComparisonResult::PRUNE_LEFT; + } else { + return ValueComparisonResult::PRUNE_NOTHING; + } + } else if (right.comparison_type == ExpressionType::COMPARE_NOTEQUAL) { + return InvertValueComparisonResult(Compare(right, left)); + } else if (IsLowerBound(left.comparison_type) && IsLowerBound(right.comparison_type)) { + // both comparisons are [>], we can either + // (1) prune the left side or + // (2) prune the right side + if (left.constant > right.constant) { + // left constant is more selective, prune right + return ValueComparisonResult::PRUNE_RIGHT; + } else if (left.constant < right.constant) { + // right constant is more selective, prune left + return ValueComparisonResult::PRUNE_LEFT; + } else { + // constants are equivalent + // however we can still have the scenario where one is [>=] and the other is [>] + // we want to prune the [>=] because [>] is more selective + // if left is [>=] we prune the left, else we prune the right + if (left.comparison_type == ExpressionType::COMPARE_GREATERTHANOREQUALTO) { + return ValueComparisonResult::PRUNE_LEFT; + } else { + return ValueComparisonResult::PRUNE_RIGHT; + } + } + } else if (IsUpperBound(left.comparison_type) && IsUpperBound(right.comparison_type)) { + // both comparisons are [<], we can either + // (1) prune the left side or + // (2) prune the right side + if (left.constant < right.constant) { + // left constant is more selective, prune right + return ValueComparisonResult::PRUNE_RIGHT; + } else if (left.constant > right.constant) { + // right constant is more selective, prune left + return ValueComparisonResult::PRUNE_LEFT; + } else { + // constants are equivalent + // however we can still have the scenario where one is [<=] and the other is [<] + // we want to prune the [<=] because [<] is more selective + // if left is [<=] we prune the left, else we prune the right + if (left.comparison_type == ExpressionType::COMPARE_LESSTHANOREQUALTO) { + return ValueComparisonResult::PRUNE_LEFT; + } else { + return ValueComparisonResult::PRUNE_RIGHT; + } + } + } else if (IsUpperBound(left.comparison_type)) { + D_ASSERT(IsLowerBound(right.comparison_type)); + // left is [<] and right is [>], in this case we can either + // (1) prune nothing or + // (2) return UNSATISFIABLE + // the SMALLER THAN constant has to be greater than the BIGGER THAN constant + if (left.constant > right.constant) { + return ValueComparisonResult::PRUNE_NOTHING; + } else if (left.constant < right.constant) { + return ValueComparisonResult::UNSATISFIABLE_CONDITION; + } else { + // the constants are equal + // This is only satisfiable if both bounds are inclusive + if (left.comparison_type == ExpressionType::COMPARE_LESSTHANOREQUALTO && + right.comparison_type == ExpressionType::COMPARE_GREATERTHANOREQUALTO) { + return ValueComparisonResult::PRUNE_NOTHING; + } else { + return ValueComparisonResult::UNSATISFIABLE_CONDITION; + } + } + } else { + // left is [>] and right is [<] or [!=] + D_ASSERT(IsUpperBound(right.comparison_type) && IsLowerBound(left.comparison_type)); + return InvertValueComparisonResult(Compare(right, left)); + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/planner/filter/expression_filter.cpp b/src/duckdb/src/planner/filter/expression_filter.cpp index 8515f12b0..1512f4d8b 100644 --- a/src/duckdb/src/planner/filter/expression_filter.cpp +++ b/src/duckdb/src/planner/filter/expression_filter.cpp @@ -1,4 +1,5 @@ #include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/common/in_clause.hpp" #include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/vector.hpp" #include "duckdb/function/arg_properties.hpp" @@ -35,6 +36,45 @@ namespace duckdb { +bool ExpressionFilter::IsNativeInFilter(const Expression &expr) { + if (expr.GetExpressionType() != ExpressionType::COMPARE_IN) { + return false; + } + auto &children = expr.Cast().GetChildren(); + if (children.size() < 2 || children[0]->GetExpressionClass() != ExpressionClass::BOUND_REF || + children[0]->Cast().Index() != 0) { + return false; + } + const auto type = children[0]->GetReturnType().InternalType(); + if (!TypeIsNumeric(type) && type != PhysicalType::BOOL && type != PhysicalType::VARCHAR && + type != PhysicalType::INTERVAL) { + return false; + } + for (idx_t i = 1; i < children.size(); i++) { + if (children[i]->GetExpressionClass() != ExpressionClass::BOUND_CONSTANT || + children[i]->GetReturnType().InternalType() != type) { + return false; + } + } + return true; +} + +bool ExpressionFilter::IsSmallNativeInFilter(const Expression &expr) { + return expr.GetExpressionType() == ExpressionType::COMPARE_IN && + expr.Cast().GetChildren().size() < IN_CLAUSE_REWRITE_THRESHOLD && + ExpressionFilter::IsNativeInFilter(expr); +} + +bool ExpressionFilter::SupportsConstantFilterPushdown(const LogicalType &type) { + if (TypeIsNumeric(type.InternalType())) { + return true; + } + if (type.InternalType() == PhysicalType::VARCHAR || type.InternalType() == PhysicalType::BOOL) { + return true; + } + return false; +} + ExpressionFilter::ExpressionFilter(unique_ptr expr_p) : ExpressionFilter(std::move(expr_p), {}) { } @@ -146,7 +186,7 @@ static bool IsOptionalExpressionInternal(const Expression &expr, bool recurse_th return true; } -static bool ContainsInternalTableFilterFunction(const Expression &expr) { +bool ExpressionFilter::ContainsInternalTableFilterFunction(const Expression &expr) { if (expr.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { auto &func = expr.Cast(); if (TableFilterFunctions::IsTableFilterFunction(func.Function())) { @@ -950,6 +990,10 @@ bool ExpressionFilter::IsOptionalExpression(const Expression &expr) { return IsOptionalExpressionInternal(expr, true, true); } +bool ExpressionFilter::IsPruningOnlyExpression(const Expression &expr) { + return IsOptionalExpressionInternal(expr, true, false); +} + bool ExpressionFilter::IsRootOptionalExpression(const Expression &expr) { return IsOptionalExpressionInternal(expr, false, true); } diff --git a/src/duckdb/src/planner/logical_operator.cpp b/src/duckdb/src/planner/logical_operator.cpp index 8865cc7f8..0d0136fba 100644 --- a/src/duckdb/src/planner/logical_operator.cpp +++ b/src/duckdb/src/planner/logical_operator.cpp @@ -93,7 +93,7 @@ InsertionOrderPreservingMap LogicalOperator::ParamsToString() const { return result; } -bool LogicalOperator::HasSideEffects() const { +bool LogicalOperator::HasLocalSideEffects() const { switch (type) { case LogicalOperatorType::LOGICAL_INSERT: case LogicalOperatorType::LOGICAL_UPDATE: @@ -102,7 +102,13 @@ bool LogicalOperator::HasSideEffects() const { case LogicalOperatorType::LOGICAL_COPY_TO_FILE: return true; default: - break; + return false; + } +} + +bool LogicalOperator::HasSideEffects() const { + if (HasLocalSideEffects()) { + return true; } for (auto &child : children) { if (child && child->HasSideEffects()) { @@ -169,11 +175,38 @@ void LogicalOperator::ResolveOperatorTypes() { for (auto &child : children) { child->ResolveOperatorTypes(); } + ResolveOperatorTypesFromChildren(); +} + +void LogicalOperator::ResolveOperatorTypesFromChildren() { + types.clear(); // now resolve the types for this operator ResolveTypes(); D_ASSERT(types.size() == GetColumnBindings().size()); } +void LogicalOperator::VerifyOperatorTypes() { + for (auto &child : children) { + child->VerifyOperatorTypes(); + } + auto original_types = std::move(types); + types.clear(); + try { + ResolveTypes(); + bool types_match = types.size() == original_types.size(); + for (idx_t i = 0; types_match && i < types.size(); i++) { + types_match = types[i].EqualsIncludingCollation(original_types[i]); + } + if (!types_match) { + throw InternalException("Stale output types in logical operator %s", GetName()); + } + } catch (...) { + types = std::move(original_types); + throw; + } + types = std::move(original_types); +} + vector LogicalOperator::GenerateColumnBindings(TableIndex table_idx, idx_t column_count) { vector result; result.reserve(column_count); diff --git a/src/duckdb/src/planner/logical_operator_repeatability.cpp b/src/duckdb/src/planner/logical_operator_repeatability.cpp index 3496096da..ec32d2e3e 100644 --- a/src/duckdb/src/planner/logical_operator_repeatability.cpp +++ b/src/duckdb/src/planner/logical_operator_repeatability.cpp @@ -122,10 +122,7 @@ static LogicalOperatorRepeatability ClassifyOperatorType(LogicalOperator &op) { return LogicalOperatorRepeatability::UNKNOWN; } -LogicalOperatorRepeatability ClassifyLogicalOperatorRepeatability(LogicalOperator &op) { - if (op.HasSideEffects()) { - return LogicalOperatorRepeatability::NON_REPEATABLE; - } +LogicalOperatorRepeatability ClassifyLogicalOperatorLocalRepeatability(LogicalOperator &op) { auto classification = ClassifyOperatorType(op); if (classification != LogicalOperatorRepeatability::REPEATABLE) { return classification; @@ -138,6 +135,13 @@ LogicalOperatorRepeatability ClassifyLogicalOperatorRepeatability(LogicalOperato : LogicalOperatorRepeatability::NON_REPEATABLE; } +LogicalOperatorRepeatability ClassifyLogicalOperatorRepeatability(LogicalOperator &op) { + if (op.HasSideEffects()) { + return LogicalOperatorRepeatability::NON_REPEATABLE; + } + return ClassifyLogicalOperatorLocalRepeatability(op); +} + bool LogicalSubtreeIsRepeatable(LogicalOperator &op) { if (ClassifyLogicalOperatorRepeatability(op) != LogicalOperatorRepeatability::REPEATABLE) { return false; diff --git a/src/duckdb/src/planner/operator/logical_get.cpp b/src/duckdb/src/planner/operator/logical_get.cpp index 944874246..8660c2856 100644 --- a/src/duckdb/src/planner/operator/logical_get.cpp +++ b/src/duckdb/src/planner/operator/logical_get.cpp @@ -309,18 +309,24 @@ idx_t LogicalGet::EstimateCardinality(ClientContext &context) { } idx_t LogicalGet::EstimateSourceCardinality(ClientContext &context) { + return EstimateSourceStatistics(context).estimated_cardinality; +} + +NodeStatistics LogicalGet::EstimateSourceStatistics(ClientContext &context) { + NodeStatistics result; // planning a LogicalGet consumes its bind data - the callbacks that require it must not be called, // while callbacks that accept a null bind data (e.g. the range functions) return no estimate anyway if (function.cardinality && bind_data) { auto node_stats = function.cardinality(context, bind_data.get()); - if (node_stats && node_stats->has_estimated_cardinality) { - return node_stats->estimated_cardinality; + if (node_stats) { + result = *node_stats; } } - if (!children.empty()) { - return children[0]->EstimateCardinality(context); + if (!result.has_estimated_cardinality) { + result.has_estimated_cardinality = true; + result.estimated_cardinality = children.empty() ? 1 : children[0]->EstimateCardinality(context); } - return 1; + return result; } void LogicalGet::SetScanOrder(unique_ptr options) { diff --git a/src/duckdb/src/planner/table_filter_combiner.cpp b/src/duckdb/src/planner/table_filter_combiner.cpp new file mode 100644 index 000000000..589f8ea48 --- /dev/null +++ b/src/duckdb/src/planner/table_filter_combiner.cpp @@ -0,0 +1,261 @@ +#include "duckdb/planner/table_filter_set.hpp" +#include "duckdb/common/reference_map.hpp" +#include "duckdb/optimizer/filter_combiner.hpp" +#include "duckdb/parser/expression_map.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" +#include "duckdb/planner/expression/expression_barrier.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/filter/constant_filter_combiner.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" + +namespace duckdb { + +static bool ScanInImpliesComparison(const BoundOperatorExpression &in, const ConstantComparison &bound) { + for (idx_t i = 1; i < in.GetChildren().size(); i++) { + auto &member = *in.GetChildren()[i]; + auto &value = member.Cast().GetValue(); + if (value.type() != bound.constant.type()) { + return false; + } + // NULL is not a matching member of IN in a filter. + if (value.IsNull()) { + continue; + } + ConstantComparison equality {value, ExpressionType::COMPARE_EQUAL}; + if (ConstantFilterCombiner::Compare(equality, bound) != ValueComparisonResult::PRUNE_RIGHT) { + return false; + } + } + return true; +} + +struct ScanBound : ConstantComparison { + ScanBound(const Expression &source_p, bool required_p) : source(source_p), required(required_p) { + } + + reference source; + bool required; +}; + +static FilterResult CombineScanComparison(const Expression &candidate, optional_ptr optional_child, + expression_map_t> &bounds, + reference_set_t &removed) { + auto &expr = optional_child ? *optional_child : candidate; + if (!ConstantFilterCombiner::IsSupportedComparison(expr.GetExpressionType())) { + return FilterResult::SUCCESS; + } + auto &comparison = expr.Cast(); + auto &left = BoundComparisonExpression::Left(comparison); + auto &right = BoundComparisonExpression::Right(comparison); + const bool flipped = left.GetExpressionType() == ExpressionType::VALUE_CONSTANT; + auto &target = flipped ? right : left; + auto &constant_expr = flipped ? left : right; + if (constant_expr.GetExpressionType() != ExpressionType::VALUE_CONSTANT || + target.GetExpressionType() == ExpressionType::VALUE_CONSTANT || !FilterCombiner::CanMatchExpression(target)) { + return FilterResult::SUCCESS; + } + auto &constant = constant_expr.Cast().GetValue(); + // Nested Value ordering (notably VARIANT) can differ from the expression's execution. + if (target.GetReturnType() != constant.type() || constant.type().IsNested()) { + return FilterResult::SUCCESS; + } + // Only promote cheap native comparisons; arbitrary optional predicates keep their execution policy. + if (optional_child && (!ExpressionFilter::IsSimpleFilterColumnRef(target) || + !ExpressionFilter::SupportsConstantFilterPushdown(constant.type()) || constant.IsNull())) { + return FilterResult::SUCCESS; + } + auto &required_bounds = bounds[target]; + if (optional_child && required_bounds.empty()) { + return FilterResult::SUCCESS; + } + ScanBound bound(candidate, !optional_child); + bound.constant = constant; + bound.comparison_type = + flipped ? FlipComparisonExpression(comparison.GetExpressionType()) : comparison.GetExpressionType(); + auto result = ConstantFilterCombiner::AddComparison( + required_bounds, std::move(bound), [&removed](ScanBound &retained, const ScanBound &removed_bound) { + retained.required |= removed_bound.required; + removed.insert(removed_bound.source); + }); + if (result == FilterResult::SUCCESS && !required_bounds.back().required) { + // This optional bound did not replace a required bound. Leave it optional and out of the solver. + required_bounds.pop_back(); + } + return result; +} + +static FilterResult CombineScanComparisons(const vector> &candidates, + reference_set_t &removed, + reference_set_t &promoted) { + expression_map_t> bounds; + // Establish the required bounds first; optional predicates only join this set when they replace one. + for (bool optional : {false, true}) { + for (auto &candidate_ref : candidates) { + auto &candidate = candidate_ref.get(); + auto optional_child = ExpressionFilter::GetOptionalFilterChild(candidate); + if (bool(optional_child) != optional) { + continue; + } + if (CombineScanComparison(candidate, optional_child, bounds, removed) == FilterResult::UNSATISFIABLE) { + return FilterResult::UNSATISFIABLE; + } + } + } + // Only an already-required IN can replace bounds. Optional IN keeps its cheaper pruning/bypass policy. + for (auto &candidate : candidates) { + auto &expr = candidate.get(); + if (!ExpressionFilter::IsSmallNativeInFilter(expr)) { + continue; + } + auto &in = expr.Cast(); + if (!FilterCombiner::CanMatchExpression(*in.GetChildren()[0])) { + continue; + } + auto entry = bounds.find(*in.GetChildren()[0]); + if (entry == bounds.end()) { + continue; + } + auto &required_bounds = entry->second; + for (idx_t i = 0; i < required_bounds.size(); i++) { + if (ScanInImpliesComparison(in, required_bounds[i])) { + removed.insert(required_bounds[i].source); + required_bounds.erase_at(i--); + } + } + } + for (auto &entry : bounds) { + for (auto &bound : entry.second) { + auto &candidate = bound.source.get(); + if (ExpressionFilter::GetOptionalFilterChild(candidate)) { + promoted.insert(candidate); + } + } + } + return FilterResult::SUCCESS; +} + +static bool CanReorderScanFilter(const Expression &expr) { + if (!expr.IsConsistent() || expr.CanThrow() || expr.HasParameter() || ExpressionBarrier::Contains(expr)) { + return false; + } + // Optional wrappers keep their predicate in bind data rather than in the expression's children. + auto optional_child = ExpressionFilter::GetOptionalFilterChild(expr); + if (optional_child && !CanReorderScanFilter(*optional_child)) { + return false; + } + bool can_reorder = true; + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { + if (can_reorder) { + can_reorder = CanReorderScanFilter(child); + } + }); + return can_reorder; +} + +static void CollectScanConjuncts(const Expression &expr, vector> &conjuncts) { + if (expr.GetExpressionType() != ExpressionType::CONJUNCTION_AND) { + conjuncts.push_back(expr); + return; + } + for (auto &child : expr.Cast().GetChildren()) { + CollectScanConjuncts(*child, conjuncts); + } +} + +static bool RewriteScanConjuncts(unique_ptr &expr, reference_set_t &removed, + reference_set_t &promoted) { + // Consume references before destroying their source expressions. + if (removed.erase(*expr)) { + expr.reset(); + return true; + } + if (promoted.erase(*expr)) { + expr = ExpressionFilter::GetOptionalFilterChild(*expr)->Copy(); + return true; + } + if (expr->GetExpressionType() != ExpressionType::CONJUNCTION_AND) { + return false; + } + auto &children = expr->Cast().GetChildrenMutable(); + bool changed = false; + for (idx_t i = 0; i < children.size(); i++) { + changed |= RewriteScanConjuncts(children[i], removed, promoted); + if (!children[i]) { + children.erase_at(i--); + } + } + if (changed) { + if (children.empty()) { + expr.reset(); + } else if (children.size() == 1) { + auto remaining = std::move(children[0]); + expr = std::move(remaining); + } + } + return changed; +} + +FilterResult TableFilterSet::Finalize() { + for (auto &entry : *this) { + auto &filter = entry.Filter().Cast(); + if (filter.expr->GetExpressionType() != ExpressionType::CONJUNCTION_AND) { + continue; + } + // Keep the original scan expressions and their order: a replacement form may not be supported by the scan. + vector> conjuncts; + CollectScanConjuncts(*filter.expr, conjuncts); + vector> candidates; + expression_set_t required; + bool can_reorder = true; + for (auto &conjunct : conjuncts) { + if (!CanReorderScanFilter(conjunct.get())) { + can_reorder = false; + break; + } + if (!ExpressionFilter::GetOptionalFilterChild(conjunct.get()) && + FilterCombiner::CanMatchExpression(conjunct.get())) { + required.insert(conjunct.get()); + } + } + if (!can_reorder) { + continue; + } + expression_set_t seen; + reference_set_t removed; + reference_set_t promoted; + for (auto &conjunct : conjuncts) { + auto &expr = conjunct.get(); + auto optional_child = ExpressionFilter::GetOptionalFilterChild(expr); + if (ExpressionFilter::ContainsInternalTableFilterFunction(optional_child ? *optional_child : expr)) { + continue; + } + // Expression equality can conflate constants that a function distinguishes, such as signed zeros. + const bool can_match = FilterCombiner::CanMatchExpression(expr) && + (!optional_child || FilterCombiner::CanMatchExpression(*optional_child)); + if (can_match && optional_child && required.find(*optional_child) != required.end()) { + removed.insert(expr); + continue; + } + // Optional duplicates include the wrapper's configuration. Runtime state stays opaque. + if (!can_match || seen.insert(expr).second) { + candidates.push_back(expr); + } else { + removed.insert(expr); + } + } + if (CombineScanComparisons(candidates, removed, promoted) == FilterResult::UNSATISFIABLE) { + return FilterResult::UNSATISFIABLE; + } + if (!removed.empty() || !promoted.empty()) { + RewriteScanConjuncts(filter.expr, removed, promoted); + D_ASSERT(filter.expr); + } + } + return FilterResult::SUCCESS; +} + +} // namespace duckdb diff --git a/src/duckdb/src/planner/table_filter_set.cpp b/src/duckdb/src/planner/table_filter_set.cpp index 97102e827..068914f32 100644 --- a/src/duckdb/src/planner/table_filter_set.cpp +++ b/src/duckdb/src/planner/table_filter_set.cpp @@ -1,4 +1,5 @@ #include "duckdb/planner/table_filter_set.hpp" +#include "duckdb/planner/filter/constant_filter_combiner.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/filter/conjunction_filter.hpp" #include "duckdb/planner/filter/constant_filter.hpp" @@ -24,27 +25,6 @@ namespace duckdb { -static bool ContainsInternalTableFilterFunction(const Expression &expr) { - if (expr.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { - auto &func = expr.Cast(); - if (TableFilterFunctions::IsTableFilterFunction(func.Function())) { - return true; - } - auto optional_child = ExpressionFilter::GetOptionalFilterChild(func); - if (optional_child && ContainsInternalTableFilterFunction(*optional_child)) { - return true; - } - } - bool found = false; - ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { - if (found) { - return; - } - found = ContainsInternalTableFilterFunction(child); - }); - return found; -} - static unique_ptr SerializeExpressionToLegacyFilter(const Expression &expr); static ExpressionType FlipComparisonType(ExpressionType type) { @@ -62,20 +42,6 @@ static ExpressionType FlipComparisonType(ExpressionType type) { } } -static bool IsSupportedConstantComparison(ExpressionType type) { - switch (type) { - case ExpressionType::COMPARE_EQUAL: - case ExpressionType::COMPARE_NOTEQUAL: - case ExpressionType::COMPARE_LESSTHAN: - case ExpressionType::COMPARE_LESSTHANOREQUALTO: - case ExpressionType::COMPARE_GREATERTHAN: - case ExpressionType::COMPARE_GREATERTHANOREQUALTO: - return true; - default: - return false; - } -} - static bool TryExtractLegacySubject(const Expression &expr, vector &struct_path) { return ExpressionFilter::IsSimpleFilterColumnRef(PeelStructExtractPath(expr, struct_path)); } @@ -131,7 +97,7 @@ static unique_ptr TrySerializeComparisonToLegacyFilter(const BoundF return nullptr; } } - if (!IsSupportedConstantComparison(comparison_type)) { + if (!ConstantFilterCombiner::IsSupportedComparison(comparison_type)) { return nullptr; } return WrapStructFilterPath(make_uniq(comparison_type, constant), struct_path); @@ -257,7 +223,7 @@ static unique_ptr SerializeExpressionToLegacyFilter(const Expressio return SerializeInternalFunctionToLegacyFilter(func); } } - if (ContainsInternalTableFilterFunction(expr)) { + if (ExpressionFilter::ContainsInternalTableFilterFunction(expr)) { return nullptr; } auto normalized_expr = expr.Copy(); @@ -565,6 +531,8 @@ DynamicTableFilterSet::GetFinalTableFilters(const PhysicalTableScan &scan, if (!result->HasFilters() && !result->HasMultiColumnFilters()) { return nullptr; } + // Work only on this execution's copy. Contradictions can safely retain their original scan predicates. + result->Finalize(); return result; } diff --git a/src/duckdb/src/planner/table_filter_state.cpp b/src/duckdb/src/planner/table_filter_state.cpp index a516eb615..3e4a83f16 100644 --- a/src/duckdb/src/planner/table_filter_state.cpp +++ b/src/duckdb/src/planner/table_filter_state.cpp @@ -220,7 +220,8 @@ static FilterCacheProperties GetCacheProperties(const Expression &expression) { } static unique_ptr TryCreateFastExecutor(const Expression &expression, - bool inside_selectivity_optional); + bool inside_selectivity_optional, + optional_ptr cost = nullptr); static void InitializeExecutor(Context &context, const Expression &expression, ExpressionFilterState &state) { state.executor = make_uniq(context); @@ -1125,31 +1126,19 @@ static unique_ptr TryCreateComparisonExecutor(const Bo } static unique_ptr TryCreateInExecutor(const BoundOperatorExpression &expr) { - auto &expressions = expr.GetChildren(); - if (expr.GetExpressionType() != ExpressionType::COMPARE_IN || expressions.size() < 2 || - !IsColumnReferenceExpression(*expressions[0])) { - return nullptr; - } - const auto type = expressions[0]->GetReturnType().InternalType(); - if (!IsSupportedComparisonType(type)) { + if (!ExpressionFilter::IsNativeInFilter(expr)) { return nullptr; } vector constants; - for (idx_t i = 1; i < expressions.size(); i++) { - if (expressions[i]->GetExpressionClass() != ExpressionClass::BOUND_CONSTANT) { - return nullptr; - } - const auto &constant = expressions[i]->Cast().GetValue(); - if (constant.type().InternalType() != type) { - return nullptr; - } - constants.push_back(constant); + for (idx_t i = 1; i < expr.GetChildren().size(); i++) { + constants.push_back(expr.GetChildren()[i]->Cast().GetValue()); } return make_uniq(std::move(constants)); } static unique_ptr TryCreateFunctionExecutor(const BoundFunctionExpression &func, - bool inside_selectivity_optional) { + bool inside_selectivity_optional, + optional_ptr cost) { if (func.GetChildren().size() == 2 && BoundComparisonExpression::IsComparison(func.GetExpressionType())) { return TryCreateComparisonExecutor(func); } @@ -1166,7 +1155,7 @@ static unique_ptr TryCreateFunctionExecutor(const Boun if (!optional_child) { return make_uniq(); } - auto child = TryCreateFastExecutor(*optional_child, true); + auto child = TryCreateFastExecutor(*optional_child, true, cost); if (!child) { return nullptr; } @@ -1191,11 +1180,14 @@ static unique_ptr TryCreateFunctionExecutor(const Boun return nullptr; } -static unique_ptr TryCreateFastExecutor(const Expression &expression, - bool inside_selectivity_optional) { +static unique_ptr +TryCreateFastExecutor(const Expression &expression, bool inside_selectivity_optional, optional_ptr cost) { + if (cost) { + *cost = ExpressionHeuristics::Cost(expression); + } switch (expression.GetExpressionClass()) { case ExpressionClass::BOUND_FUNCTION: - return TryCreateFunctionExecutor(expression.Cast(), inside_selectivity_optional); + return TryCreateFunctionExecutor(expression.Cast(), inside_selectivity_optional, cost); case ExpressionClass::BOUND_OPERATOR: return TryCreateInExecutor(expression.Cast()); case ExpressionClass::BOUND_CONJUNCTION: { @@ -1210,14 +1202,35 @@ static unique_ptr TryCreateFastExecutor(const Expressi }; vector filters; const auto is_and = expression.GetExpressionType() == ExpressionType::CONJUNCTION_AND; + idx_t row_filter_count = 0; + idx_t row_filter_index = 0; for (auto &child_expr : conjunction.GetChildren()) { - auto child_executor = TryCreateFastExecutor(*child_expr, inside_selectivity_optional); + idx_t child_cost = 0; + auto child_executor = + TryCreateFastExecutor(*child_expr, inside_selectivity_optional, is_and ? &child_cost : nullptr); if (!child_executor) { return nullptr; } - filters.push_back({std::move(child_executor), is_and ? ExpressionHeuristics::Cost(*child_expr) : 0}); + if (is_and && !ExpressionFilter::IsPruningOnlyExpression(*child_expr)) { + row_filter_count++; + row_filter_index = filters.size(); + } + filters.push_back({std::move(child_executor), child_cost}); } if (is_and) { + // Keep pruning hints in the expression, but avoid an AND executor for zero or one row filter. + if (row_filter_count == 0) { + if (cost) { + *cost = 0; + } + return make_uniq(); + } + if (row_filter_count == 1) { + if (cost) { + *cost = filters[row_filter_index].cost; + } + return std::move(filters[row_filter_index].executor); + } std::stable_sort(filters.begin(), filters.end(), [](const FilterCost &left, const FilterCost &right) { return left.cost < right.cost; }); } diff --git a/src/duckdb/src/storage/block_allocator.cpp b/src/duckdb/src/storage/block_allocator.cpp index e2a79ab99..bbb60a348 100644 --- a/src/duckdb/src/storage/block_allocator.cpp +++ b/src/duckdb/src/storage/block_allocator.cpp @@ -1140,10 +1140,7 @@ class BlockAllocatorFlushTask : public Task { BlockAllocator::ReclaimMode::DECAY); const auto cache_freed = allocator.FlushAllocationCache( BlockAllocatorConfig::MAX_FLUSH_BLOCKS * allocator.block_size, BlockAllocator::ReclaimMode::DECAY); - if (cache_freed > 0) { - allocator.FlushFallbackAllocator( - allocator.estimated_unflushed_memory.exchange(0, std::memory_order_relaxed)); - } + allocator.FlushDeallocated(); annotated_lock_guard guard(allocator.flush_lock); const bool reschedule = allocator.flush_state == FlushState::RESCHEDULE_REQUESTED; allocator.flush_state = FlushState::IDLE; @@ -1212,9 +1209,8 @@ void BlockAllocator::ThreadIdle() const { if (!scheduler_ref || !TryScheduleFlush(*scheduler_ref)) { const auto mode = scheduler_ref ? ReclaimMode::DECAY : ReclaimMode::FORCE; FlushPool(optional_idx(), optional_idx(), mode); - if (FlushAllocationCache(NumericLimits::Maximum(), mode) > 0) { - FlushFallbackAllocator(estimated_unflushed_memory.exchange(0, std::memory_order_relaxed)); - } + FlushAllocationCache(NumericLimits::Maximum(), mode); + FlushDeallocated(); } } catch (...) { // Reclamation is best effort on scheduler threads. @@ -1266,7 +1262,8 @@ static idx_t AllocationCacheIdleCutoff() { bool BlockAllocator::HasReclaimableMemory() const { return GetReclaimableBlockCount(ReclaimMode::DECAY) > 0 || - allocation_cache->GetCachedMemory(AllocationCacheIdleCutoff()) > 0; + allocation_cache->GetCachedMemory(AllocationCacheIdleCutoff()) > 0 || + estimated_unflushed_memory.load(std::memory_order_relaxed) > 0; } bool BlockAllocator::HasPendingCacheDecay() const { @@ -1288,28 +1285,26 @@ idx_t BlockAllocator::FlushAllocationCache(idx_t byte_limit, ReclaimMode mode) c return freed; } -idx_t BlockAllocator::TrimCachedMemory(idx_t memory_headroom, optional_idx pool_block_limit) const noexcept { +void BlockAllocator::TrimCachedMemory(idx_t memory_headroom, optional_idx pool_block_limit) const noexcept { const auto cached = allocation_cache->GetCachedMemory(); // Avoid reading the fixed pool's per-thread counters when even its capacity fits. if (cached <= memory_headroom && (GetUsableBlockCount() * block_size <= memory_headroom - cached || GetCachedPoolMemory() <= memory_headroom - cached)) { - return 0; + return; } - idx_t freed = 0; idx_t pool_headroom; { annotated_lock_guard guard(flush_lock); const auto total = GetCachedMemory(); if (total <= memory_headroom) { - return 0; + return; } - freed = allocation_cache->Flush(total - memory_headroom); + const auto freed = allocation_cache->Flush(total - memory_headroom); estimated_unflushed_memory.fetch_add(freed, std::memory_order_relaxed); const auto remaining = allocation_cache->GetCachedMemory(); pool_headroom = memory_headroom - MinValue(memory_headroom, remaining); } FlushPool(pool_block_limit, optional_idx(), ReclaimMode::FORCE, DivBlockSize(pool_headroom)); - return freed; } void BlockAllocator::FlushAll() const noexcept { @@ -1329,21 +1324,22 @@ void BlockAllocator::FlushForAllocation(const idx_t extra_memory, const idx_t me } bool BlockAllocator::TryFlushDeallocated(const idx_t threshold, const idx_t memory_headroom) const noexcept { - if (TrimCachedMemory(memory_headroom) > 0) { - FlushFallbackAllocator(estimated_unflushed_memory.exchange(0, std::memory_order_relaxed)); - return true; - } + // Trimmed allocations join the other fallback frees, and are purged with them. + TrimCachedMemory(memory_headroom); auto deallocated = estimated_unflushed_memory.load(std::memory_order_relaxed); - if (deallocated == 0 || deallocated < threshold || !Allocator::SupportsFlush()) { - return false; - } - if (deallocated <= memory_headroom && GetCachedMemory() <= memory_headroom - deallocated) { - return false; - } - if (!estimated_unflushed_memory.compare_exchange_strong(deallocated, 0, std::memory_order_relaxed)) { - return false; - } - const auto mapped_memory = allocator.GetMappedMemory(); + do { + if (deallocated == 0 || deallocated < threshold || !Allocator::SupportsFlush()) { + return false; + } + if (deallocated <= memory_headroom && GetCachedMemory() <= memory_headroom - deallocated) { + return false; + } + // A failed claim reloads the estimate: frees added meanwhile do not cancel the purge, a claim by another + // thread does. + } while (!estimated_unflushed_memory.compare_exchange_weak(deallocated, 0, std::memory_order_relaxed)); + // Allocator statistics can only defer the purge when the room next to the cached memory holds a threshold. + const auto room = memory_headroom - MinValue(memory_headroom, GetCachedMemory()); + const auto mapped_memory = room >= threshold ? allocator.GetMappedMemory() : optional_idx(); if (mapped_memory.IsValid()) { // Repeated frees of reused memory cannot retain more than the fallback allocator's mapped footprint. const auto unflushed = MinValue(deallocated, mapped_memory.GetIndex()); @@ -1357,6 +1353,13 @@ bool BlockAllocator::TryFlushDeallocated(const idx_t threshold, const idx_t memo return true; } +void BlockAllocator::FlushDeallocated() const noexcept { + const auto deallocated = estimated_unflushed_memory.exchange(0, std::memory_order_relaxed); + if (deallocated > 0) { + FlushFallbackAllocator(deallocated); + } +} + void BlockAllocator::FlushFallbackAllocator(const idx_t deallocated) const noexcept { try { if (Allocator::SupportsFlush()) { diff --git a/src/duckdb/src/storage/data_table.cpp b/src/duckdb/src/storage/data_table.cpp index 5c9235b98..e09a5e443 100644 --- a/src/duckdb/src/storage/data_table.cpp +++ b/src/duckdb/src/storage/data_table.cpp @@ -32,6 +32,7 @@ #include "duckdb/storage/storage_manager.hpp" #include "duckdb/storage/table/append_state.hpp" #include "duckdb/storage/table/delete_state.hpp" +#include "duckdb/storage/table/index_entry.hpp" #include "duckdb/storage/table/persistent_table_data.hpp" #include "duckdb/storage/table/row_group.hpp" #include "duckdb/storage/table/scan_state.hpp" @@ -162,7 +163,8 @@ DataTable::DataTable(ClientContext &context, DataTable &parent, idx_t removed_co parent.version = DataTableVersion::ALTERED; } -DataTable::DataTable(ClientContext &context, DataTable &parent, BoundConstraint &constraint) +DataTable::DataTable(ClientContext &context, DataTable &parent, BoundConstraint &constraint, + optional_idx max_index_count) : db(parent.db), info(parent.info), row_groups(parent.row_groups), version(DataTableVersion::MAIN_TABLE) { // ALTER COLUMN to add a new constraint. @@ -171,6 +173,11 @@ DataTable::DataTable(ClientContext &context, DataTable &parent, BoundConstraint auto &local_storage = LocalStorage::Get(context, db); lock_guard parent_lock(parent.append_lock); + // publishing needs this lock and fails once the parent is ALTERED, so no index appears after this count + if (max_index_count.IsValid() && info->indexes.CountBuiltIndexes() > max_index_count.GetIndex()) { + throw DependencyException("Cannot alter entry %s because there are entries that depend on it.", + parent.GetTableName()); + } for (auto &column_def : parent.column_definitions) { column_definitions.emplace_back(column_def.Copy()); } @@ -370,7 +377,15 @@ void DataTable::Scan(DuckTransaction &transaction, DataChunk &result, TableScanS local_storage.Scan(state.local_state, state.GetColumnIds(), result); } -bool DataTable::CreateIndexScan(TableScanState &state, DataChunk &result) { +bool DataTable::CreateIndexScan(TableScanState &state, DataChunk &result, optional_ptr build) { + if (build) { + ScanOptions options( + TransactionData(build->GetBuildTransaction(), VisibilityBound::Through(build->GetLastCommit()))); + // the transaction's own deletes reach the index when it commits + options.delete_type = DeletedScanType::OMIT_COMMITTED_DELETES; + options.update_type = UpdateScanType::DISALLOW_UPDATES; + return state.table_state.Scan(options, result); + } return state.table_state.Scan(result, TableScanType::TABLE_SCAN_OMIT_PERMANENTLY_DELETED); } @@ -393,10 +408,92 @@ bool DataTable::HasUniqueIndexes() const { return info->indexes.HasUniqueIndexes(); } +unique_lock DataTable::LockMainTableForIndex(unique_lock &table_lock) { + while (true) { + auto commit_lock = db.GetStorageManager().GetCommitLock(); + // an ALTER holds the append lock while replacing the table: don't wait for it under the commit lock + table_lock = unique_lock(append_lock, std::try_to_lock); + if (!table_lock.owns_lock()) { + commit_lock.unlock(); + lock_guard wait_for_alter(append_lock); + continue; + } + if (!IsMainTable()) { + // commits to the new table cannot maintain an index on the old columns + throw TransactionException( + "Transaction conflict: cannot add an index to a table that has been altered or dropped"); + } + return commit_lock; + } +} + +shared_ptr DataTable::AddBuildingIndex(DuckTransaction &transaction, const BoundIndex &index_template) { + auto &transaction_manager = DuckTransactionManager::Get(db); + // no commit is in progress: every later commit sees the entry + unique_lock table_lock; + auto commit_lock = LockMainTableForIndex(table_lock); + // the transaction holds the checkpoint lock, so no checkpoint runs during the build + D_ASSERT(!transaction_manager.GetActiveCheckpoint().IsValid()); + return info->indexes.AddBuildingIndex(index_template, transaction_manager.GetLastCommit(), + transaction.GetTransactionId()); +} + +//! The maximum changed rows merged while holding the commit lock +static constexpr idx_t INDEX_BUILD_LOCKED_ROWS = DEFAULT_ROW_GROUP_SIZE; +//! The maximum merge rounds outside the commit lock +static constexpr idx_t INDEX_BUILD_MAX_ROUNDS = 64; +//! The maximum consecutive rounds in which the changed rows grow +static constexpr idx_t INDEX_BUILD_MAX_GROWING_ROUNDS = 3; + void DataTable::AddIndex(unique_ptr index, idx_t index_oid) { + unique_lock table_lock; + auto commit_lock = LockMainTableForIndex(table_lock); info->indexes.AddIndex(std::move(index), index_oid, ConstraintCheckMode::DEFAULT); } +shared_ptr DataTable::FinishIndexBuild(ClientContext &context, DuckTransaction &transaction, + unique_ptr index, idx_t index_oid, + ConstraintCheckMode check_mode) { + auto entry = info->indexes.FindBuildingIndex(transaction.GetTransactionId()); + if (!entry) { + // no building entry: publish between commits + D_ASSERT(!index->SupportsDeltaIndexes()); + unique_lock table_lock; + auto commit_lock = LockMainTableForIndex(table_lock); + return info->indexes.AddIndex(std::move(index), index_oid, check_mode); + } + idx_t rounds = 0; + idx_t growing_rounds = 0; + idx_t previous_changed_rows = 0; + // merge outside the locks until few changed rows are left + while (true) { + unique_lock table_lock; + auto commit_lock = LockMainTableForIndex(table_lock); + // under the commit lock, a commit and its revert always land in the same deltas + auto deltas = entry->TakeBuildDeltas(); + if (deltas.changed_rows <= INDEX_BUILD_LOCKED_ROWS) { + IndexEntry::MergeBuildDeltas(*index, deltas); + entry->FinishBuild(std::move(index), index_oid, check_mode); + return entry; + } + if (rounds > 0) { + growing_rounds = deltas.changed_rows > previous_changed_rows ? growing_rounds + 1 : 0; + } + if (rounds == INDEX_BUILD_MAX_ROUNDS || growing_rounds == INDEX_BUILD_MAX_GROWING_ROUNDS) { + throw TransactionException( + "CREATE INDEX on table %s cannot keep up with concurrent changes to it: %llu changed rows are left " + "after %llu rounds. Retry when fewer rows are written to the table", + GetTableName(), deltas.changed_rows, rounds); + } + table_lock.unlock(); + commit_lock.unlock(); + IndexEntry::MergeBuildDeltas(*index, deltas); + context.FastInterruptCheck(); + previous_changed_rows = deltas.changed_rows; + rounds++; + } +} + bool DataTable::HasForeignKeyIndex(const vector &keys, ForeignKeyType type) { auto index = info->indexes.FindForeignKeyIndex(keys, type); return index != nullptr; @@ -550,6 +647,7 @@ void DataTable::Fetch(DuckTransaction &transaction, DataChunk &result, const vec Vector local_row_ids(row_identifiers, local_sel, local_count); local_row_ids.Flatten(); ColumnFetchState local_fetch_state; + local_fetch_state.context = state.context; local_storage.FetchChunk(*this, local_row_ids, local_count, column_ids, local_chunk, local_fetch_state); // Append local rows after committed rows in the result. @@ -1291,8 +1389,10 @@ void DataTable::RevertAppend(DuckTransaction &transaction, idx_t start_row, idx_ // Indexes //===--------------------------------------------------------------------===// void DataTable::RemoveFromIndexes(const QueryContext &context, Vector &row_identifiers, idx_t count, - IndexRemovalType removal_type, optional_idx active_checkpoint) { - row_groups->RemoveFromIndexes(context, info->indexes, row_identifiers, count, removal_type, active_checkpoint); + IndexRemovalType removal_type, optional_idx active_checkpoint, + VisibilityBound bound) { + row_groups->RemoveFromIndexes(context, info->indexes, row_identifiers, count, removal_type, active_checkpoint, + bound); } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp index 856d3aa5d..7fd3ee93f 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp @@ -389,7 +389,7 @@ shared_ptr CachingFileHandle::TryGetFileHandle() { // Request parallel access on the underlying filesystem handle to avoid races in implementations that // require explicit opt-in for concurrent pread-style access (e.g., HTTPFS). auto internal_flags = flags | FileFlags::FILE_FLAGS_PARALLEL_ACCESS; - file_handle = file_system.OpenFile(path, internal_flags, opener); + file_handle = file_system.OpenFile(path, internal_flags); if (!file_handle) { return nullptr; } 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 6f77041b2..48f5dff99 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 @@ -2,26 +2,12 @@ #include "duckdb/common/compressed_file_system.hpp" #include "duckdb/common/exception.hpp" -#include "duckdb/common/file_system.hpp" +#include "duckdb/common/base_file_system.hpp" #include "duckdb/common/numeric_utils.hpp" #include "duckdb/main/client_context.hpp" namespace duckdb { -namespace { -// Get database instance from file opener, throw InvalidInput exception. -DatabaseInstance &GetDatabaseInstance(optional_ptr file_opener) { - if (file_opener == nullptr) { - throw InvalidInputException("Cannot get database instance out of file opener, because file opener is nullptr."); - } - auto database_ptr = file_opener->TryGetDatabase(); - if (database_ptr == nullptr) { - throw InvalidInputException("Cannot extract database instance out of file opener."); - } - return *database_ptr; -} -} // namespace - //===----------------------------------------------------------------------===// // CachingFileHandleWrapper implementation //===----------------------------------------------------------------------===// @@ -36,6 +22,10 @@ CachingFileHandleWrapper::CachingFileHandleWrapper(shared_ptrGetFileHandle()->CanSeek(); +} + void CachingFileHandleWrapper::Close() { if (caching_handle) { caching_handle.reset(); @@ -46,13 +36,7 @@ void CachingFileHandleWrapper::Close() { // CachingFileSystemWrapper implementation //===----------------------------------------------------------------------===// CachingFileSystemWrapper::CachingFileSystemWrapper(FileSystem &file_system, DatabaseInstance &db, CachingMode mode) - : caching_file_system(file_system, db), underlying_file_system(file_system), caching_mode(mode) { -} - -CachingFileSystemWrapper::CachingFileSystemWrapper(FileSystem &file_system, optional_ptr file_opener, - CachingMode mode) - : caching_file_system(file_system, GetDatabaseInstance(file_opener)), underlying_file_system(file_system), - caching_mode(mode) { + : underlying_file_system(file_system), caching_file_system(file_system, db), caching_mode(mode) { } bool CachingFileSystemWrapper::ShouldUseCache(const string &path) const { @@ -145,7 +129,7 @@ unique_ptr CachingFileSystemWrapper::OpenFileExtended(const OpenFile return make_uniq(shared_from_this(), std::move(caching_handle), flags); } // Bypass cache, use underlying file system directly. - return underlying_file_system.OpenFile(path, flags, opener); + return underlying_file_system.OpenFile(path, flags); } bool CachingFileSystemWrapper::SupportsOpenFileExtended() const { @@ -226,14 +210,14 @@ FileMetadata CachingFileSystemWrapper::Stats(FileHandle &handle) { optional CachingFileSystemWrapper::GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) { - return underlying_file_system.GetStatsIfExists(file, opener); + return underlying_file_system.GetStatsIfExists(file); } //===----------------------------------------------------------------------===// // Directory Operations //===----------------------------------------------------------------------===// bool CachingFileSystemWrapper::DirectoryExists(const string &directory, optional_ptr opener) { - return underlying_file_system.DirectoryExists(directory, opener); + return underlying_file_system.DirectoryExists(directory); } void CachingFileSystemWrapper::CreateDirectory(const string &directory, optional_ptr opener) { @@ -242,7 +226,7 @@ void CachingFileSystemWrapper::CreateDirectory(const string &directory, optional bool CachingFileSystemWrapper::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, optional_ptr opener) { - return underlying_file_system.CreateDirectoryExtended(directory, options, opener); + return underlying_file_system.CreateDirectoryExtended(directory, options); } void CachingFileSystemWrapper::CreateDirectoriesRecursive(const string &path, optional_ptr opener) { @@ -255,20 +239,20 @@ void CachingFileSystemWrapper::RemoveDirectory(const string &directory, optional bool CachingFileSystemWrapper::RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, optional_ptr opener) { - return underlying_file_system.RemoveDirectoryExtended(directory, options, opener); + return underlying_file_system.RemoveDirectoryExtended(directory, options); } bool CachingFileSystemWrapper::ListFiles(const string &directory, const std::function &callback, FileOpener *opener) { - return underlying_file_system.ListFiles(directory, callback, opener); + return underlying_file_system.ListFiles(directory, callback); } bool CachingFileSystemWrapper::ListFilesExtended(const string &directory, const std::function &callback, optional_ptr opener) { // Use the public ListFiles API which will internally call `ListFilesExtended` if supported. - return underlying_file_system.ListFiles(directory, callback, opener); + return underlying_file_system.ListFiles(directory, callback); } bool CachingFileSystemWrapper::SupportsListFilesExtended() const { @@ -277,23 +261,23 @@ bool CachingFileSystemWrapper::SupportsListFilesExtended() const { } void CachingFileSystemWrapper::MoveFile(const string &source, const string &target, optional_ptr opener) { - underlying_file_system.MoveFile(source, target, opener); + underlying_file_system.MoveFile(source, target); } bool CachingFileSystemWrapper::FileExists(const string &filename, optional_ptr opener) { - return underlying_file_system.FileExists(filename, opener); + return underlying_file_system.FileExists(filename); } bool CachingFileSystemWrapper::IsPipe(const string &filename, optional_ptr opener) { - return underlying_file_system.IsPipe(filename, opener); + return underlying_file_system.IsPipe(filename); } void CachingFileSystemWrapper::RemoveFile(const string &filename, optional_ptr opener) { - underlying_file_system.RemoveFile(filename, opener); + underlying_file_system.RemoveFile(filename); } bool CachingFileSystemWrapper::TryRemoveFile(const string &filename, optional_ptr opener) { - return underlying_file_system.TryRemoveFile(filename, opener); + return underlying_file_system.TryRemoveFile(filename); } //===----------------------------------------------------------------------===// @@ -312,14 +296,14 @@ string CachingFileSystemWrapper::PathSeparator(const string &path) { } vector CachingFileSystemWrapper::Glob(const string &path, FileOpener *opener) { - return underlying_file_system.Glob(path, opener); + return underlying_file_system.Glob(path); } //===----------------------------------------------------------------------===// // SubSystem Operations //===----------------------------------------------------------------------===// bool CachingFileSystemWrapper::CanHandleFile(const string &fpath) { - return underlying_file_system.CanHandleFile(fpath); + return BaseFileSystem::CanHandleFile(fpath); } //===----------------------------------------------------------------------===// @@ -328,7 +312,7 @@ bool CachingFileSystemWrapper::CanHandleFile(const string &fpath) { void CachingFileSystemWrapper::Seek(FileHandle &handle, idx_t location) { auto *caching_handle = GetCachingHandleIfPossible(handle); if (!caching_handle) { - return underlying_file_system.Seek(handle, location); + return handle.file_system.Seek(handle, location); } caching_handle->Seek(location); @@ -341,24 +325,20 @@ void CachingFileSystemWrapper::Reset(FileHandle &handle) { idx_t CachingFileSystemWrapper::SeekPosition(FileHandle &handle) { auto *caching_handle = GetCachingHandleIfPossible(handle); if (!caching_handle) { - return underlying_file_system.SeekPosition(handle); + return handle.file_system.SeekPosition(handle); } return caching_handle->SeekPosition(); } bool CachingFileSystemWrapper::IsManuallySet() { - return underlying_file_system.IsManuallySet(); -} - -bool CachingFileSystemWrapper::CanSeek() { - return underlying_file_system.CanSeek(); + return BaseFileSystem::IsManuallySet(); } bool CachingFileSystemWrapper::OnDiskFile(FileHandle &handle) { auto *caching_handle = GetCachingHandleIfPossible(handle); if (!caching_handle) { - return underlying_file_system.OnDiskFile(handle); + return handle.file_system.OnDiskFile(handle); } return caching_handle->OnDiskFile(); @@ -369,7 +349,8 @@ bool CachingFileSystemWrapper::OnDiskFile(FileHandle &handle) { //===----------------------------------------------------------------------===// unique_ptr CachingFileSystemWrapper::OpenCompressedFile(QueryContext context, unique_ptr handle, bool write) { - return underlying_file_system.OpenCompressedFile(context, std::move(handle), write); + auto &file_system = handle->file_system; + return file_system.OpenCompressedFile(context, std::move(handle), write); } } // namespace duckdb diff --git a/src/duckdb/src/storage/index_entry.cpp b/src/duckdb/src/storage/index_entry.cpp index 509ccf301..56d63589e 100644 --- a/src/duckdb/src/storage/index_entry.cpp +++ b/src/duckdb/src/storage/index_entry.cpp @@ -15,7 +15,8 @@ namespace duckdb { IndexEntry::IndexEntry(unique_ptr index_p, idx_t index_oid_p, const ConstraintCheckMode check_mode_p) - : index_oid(index_oid_p), owned_index(std::move(index_p)), check_mode(check_mode_p) { + : index_oid(index_oid_p), last_commit(0), owned_index(std::move(index_p)), check_mode(check_mode_p), + building(false), build_transaction(0) { if (owned_index->IsBound()) { bind_state = IndexBindState::BOUND; } else { @@ -23,6 +24,14 @@ IndexEntry::IndexEntry(unique_ptr index_p, idx_t index_oid_p, const Const } } +IndexEntry::IndexEntry(const BoundIndex &index_template, transaction_t build_commit, transaction_t build_transaction_p) + : bind_state(IndexBindState::BOUND), index_oid(DConstants::INVALID_INDEX), last_commit(build_commit), + owned_index(index_template.CreateEmptyCopy(IndexConstraintType::NONE)), check_mode(ConstraintCheckMode::DEFAULT), + building(true), build_transaction(build_transaction_p) { + D_ASSERT(owned_index->GetConstraintType() == IndexConstraintType::NONE); + D_ASSERT(owned_index->Cast().SupportsDeltaIndexes()); +} + void IndexEntry::Append(DataChunk &chunk, Vector &row_ids) { auto entry_lock = lock.GetExclusiveLock(); if (!owned_index->IsBound()) { @@ -55,10 +64,29 @@ ErrorData IndexEntry::Append(DataChunk &chunk, Vector &row_ids, const shared_ptr delete_index = delete_entry->owned_index->Cast(); } + if (building) { + // a building index never fails a commit: an error fails the build instead + if (build_error.HasError()) { + return ErrorData(); + } + build_changed_rows += chunk.size(); + try { + auto &added_data = deltas.GetOrCreate(bound_index, IndexDeltaType::ADDED_DATA); + IndexAppendInfo index_append_info(append_mode, nullptr); + auto error = added_data.Append(chunk, row_ids, index_append_info); + if (error.HasError()) { + build_error = std::move(error); + } + } catch (std::exception &ex) { + RecordBuildError(ex); + } + return ErrorData(); + } + bool lookup_main_index = false; optional_ptr append_index; - if (bound_index.SupportsDeltaIndexes() && deltas.ShouldUse(active_checkpoint)) { - append_index = deltas.GetOrCreate(bound_index, IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT); + if (bound_index.SupportsDeltaIndexes() && UseDeltas(active_checkpoint)) { + append_index = deltas.GetOrCreate(bound_index, IndexDeltaType::ADDED_DATA); if (bound_index.IsUnique()) { lookup_main_index = true; } @@ -70,7 +98,7 @@ ErrorData IndexEntry::Append(DataChunk &chunk, Vector &row_ids, const shared_ptr if (delete_index) { lookup_append_info.delete_indexes.push_back(*delete_index); } - if (auto delta = deltas.Find(IndexDeltaType::REMOVED_DATA_DURING_CHECKPOINT)) { + if (auto delta = deltas.Find(IndexDeltaType::REMOVED_DATA)) { lookup_append_info.delete_indexes.push_back(*delta); } bound_index.VerifyAppend(chunk, lookup_append_info, optional_ptr()); @@ -90,9 +118,21 @@ ErrorData IndexEntry::Append(DataChunk &chunk, Vector &row_ids, const shared_ptr return bound_index.Append(chunk, row_ids, index_append_info); } +void IndexEntry::RecordBuildError(std::exception &ex) { + ErrorData error(ex); + if (Exception::InvalidatesDatabase(error.Type())) { + // the database is already invalidated: don't hide it + throw; + } + build_error = std::move(error); +} + void IndexEntry::RevertAppend(DataChunk &chunk, Vector &row_ids) { auto entry_lock = lock.GetExclusiveLock(); - if (auto delta = deltas.Find(IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT)) { + if (building && build_error.HasError()) { + return; + } + if (auto delta = deltas.Find(IndexDeltaType::ADDED_DATA)) { delta->Delete(chunk, row_ids); return; } @@ -156,17 +196,24 @@ static void AppendIndexEntries(BoundIndex &index, DataChunk &chunk, Vector &row_ } } -static bool TryDeleteAll(BoundIndex &index, DataChunk &chunk, Vector &row_ids) { - const auto delete_count = index.TryDelete(chunk, row_ids, nullptr, nullptr); - if (delete_count == 0) { - return false; +//! Deletes the rows that are in the delta, and appends the others to the target +static void DeleteOrAppend(BoundIndex &delta, BoundIndex &target, DataChunk &chunk, Vector &row_ids) { + SelectionVector remaining_sel(STANDARD_VECTOR_SIZE); + const auto delete_count = delta.TryDelete(chunk, row_ids, nullptr, remaining_sel); + if (delete_count == chunk.size()) { + return; } - if (delete_count != chunk.size()) { - // This should not happen: RemoveFromIndexes works on a per-row-group basis, and appends during a checkpoint - // always use new row groups, so the two groups of data should be separate. - throw InternalException("IndexEntry::RemoveFromIndex - partially deleted from the checkpoint delta"); + if (delete_count == 0) { + AppendIndexEntries(target, chunk, row_ids); + return; } - return true; + // the delete covers rows from both before and after the delta was created + const auto remaining_count = chunk.size() - delete_count; + DataChunk remaining_chunk; + remaining_chunk.InitializeEmpty(chunk.GetTypes()); + remaining_chunk.Slice(chunk, remaining_sel, remaining_count); + Vector remaining_row_ids(row_ids, remaining_sel, remaining_count); + AppendIndexEntries(target, remaining_chunk, remaining_row_ids); } static void ApplyIndexRemoval(BoundIndex &index, IndexDeltas &deltas, DataChunk &chunk, Vector &row_ids, @@ -213,22 +260,23 @@ static void ApplyIndexRemoval(BoundIndex &index, IndexDeltas &deltas, DataChunk } } -static void ApplyIndexRemovalDuringCheckpoint(BoundIndex &index, IndexDeltas &deltas, DataChunk &chunk, Vector &row_ids, - const IndexRemovalType removal_type) { +static void ApplyIndexRemovalToDeltas(BoundIndex &index, IndexDeltas &deltas, DataChunk &chunk, Vector &row_ids, + const IndexRemovalType removal_type) { D_ASSERT(removal_type != IndexRemovalType::DELETED_ROWS_IN_USE); switch (removal_type) { case IndexRemovalType::MAIN_INDEX_ONLY: case IndexRemovalType::MAIN_INDEX: { - // Removing from the main index cannot happen directly due to the concurrent checkpoint; add the removal to a + // Removing from the main index cannot happen directly during a checkpoint or a build; add the removal to a // delta index. - auto &removed_data = deltas.GetOrCreate(index, IndexDeltaType::REMOVED_DATA_DURING_CHECKPOINT); - auto added_data = deltas.Find(IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT); + auto &removed_data = deltas.GetOrCreate(index, IndexDeltaType::REMOVED_DATA); + auto added_data = deltas.Find(IndexDeltaType::ADDED_DATA); - // If we have also added data during this checkpoint, we might need to remove from there instead. - // We FIRST try to remove from "added_data_during_checkpoint"; any rows that are not there are added to - // "removed_data_during_checkpoint". - if (!added_data || !TryDeleteAll(*added_data, chunk, row_ids)) { + // If we have also added data to the deltas, we might need to remove from there instead. + // We FIRST try to remove from "added_data"; any rows that are not there are added to "removed_data". + if (added_data) { + DeleteOrAppend(*added_data, removed_data, chunk, row_ids); + } else { AppendIndexEntries(removed_data, chunk, row_ids); } if (removal_type == IndexRemovalType::MAIN_INDEX) { @@ -240,17 +288,15 @@ static void ApplyIndexRemovalDuringCheckpoint(BoundIndex &index, IndexDeltas &de } case IndexRemovalType::REVERT_MAIN_INDEX_ONLY: case IndexRemovalType::REVERT_MAIN_INDEX: { - auto &removed_data = deltas.GetOrCreate(index, IndexDeltaType::REMOVED_DATA_DURING_CHECKPOINT); + auto &removed_data = deltas.GetOrCreate(index, IndexDeltaType::REMOVED_DATA); // Revert adding to the main index. - // We have added data during this checkpoint as well, so the removal might have EITHER: - // (1) added data to "removed_data_during_checkpoint" or - // (2) removed data from "added_data_during_checkpoint". - // Revert by first trying to remove from "removed_data_during_checkpoint"; any rows that were not removed are - // re-added to "added_data_during_checkpoint". - if (auto added_data = deltas.Find(IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT)) { - if (!TryDeleteAll(removed_data, chunk, row_ids)) { - AppendIndexEntries(*added_data, chunk, row_ids); - } + // We have added data to the deltas as well, so the removal might have EITHER: + // (1) added data to "removed_data" or + // (2) removed data from "added_data". + // Revert by first trying to remove from "removed_data"; any rows that were not removed are re-added to + // "added_data". + if (auto added_data = deltas.Find(IndexDeltaType::ADDED_DATA)) { + DeleteOrAppend(removed_data, *added_data, chunk, row_ids); } else { removed_data.Delete(chunk, row_ids); } @@ -277,15 +323,33 @@ void IndexEntry::RemoveFromIndex(DataChunk &chunk, Vector &row_ids, const IndexR } auto &bound_index = owned_index->Cast(); + if (building) { + if (build_error.HasError()) { + return; + } + if (removal_type != IndexRemovalType::DELETED_ROWS_IN_USE) { + build_changed_rows += chunk.size(); + } + try { + if (removal_type == IndexRemovalType::DELETED_ROWS_IN_USE) { + ApplyIndexRemoval(bound_index, deltas, chunk, row_ids, removal_type); + } else { + ApplyIndexRemovalToDeltas(bound_index, deltas, chunk, row_ids, removal_type); + } + } catch (std::exception &ex) { + RecordBuildError(ex); + } + return; + } // Check which indexes we should append to or remove from. This method might also involve appending to indexes: // delta indexes must be filled with data we are removing, or we may be reverting a previous removal. // Not all indexes require delta indexes, so those skip "deleted_rows_in_use" bookkeeping. if (removal_type == IndexRemovalType::DELETED_ROWS_IN_USE) { // Cleanup always removes directly from "deleted_rows_in_use", even during a checkpoint. ApplyIndexRemoval(bound_index, deltas, chunk, row_ids, removal_type); - } else if (bound_index.SupportsDeltaIndexes() && deltas.ShouldUse(active_checkpoint)) { - // During a checkpoint, route changes through the checkpoint deltas instead of the main index. - ApplyIndexRemovalDuringCheckpoint(bound_index, deltas, chunk, row_ids, removal_type); + } else if (bound_index.SupportsDeltaIndexes() && UseDeltas(active_checkpoint)) { + // During a checkpoint, route changes through the deltas. + ApplyIndexRemovalToDeltas(bound_index, deltas, chunk, row_ids, removal_type); } else { ApplyIndexRemoval(bound_index, deltas, chunk, row_ids, removal_type); } @@ -382,12 +446,12 @@ void IndexEntry::VerifyAppend(const shared_ptr &delete_entry, DataCh index_append_info.delete_indexes.push_back(delete_entry->owned_index->Cast()); } if (!manager) { - if (auto delta = deltas.Find(IndexDeltaType::REMOVED_DATA_DURING_CHECKPOINT)) { + if (auto delta = deltas.Find(IndexDeltaType::REMOVED_DATA)) { index_append_info.delete_indexes.push_back(*delta); } } bound_index.VerifyAppend(chunk, index_append_info, manager); - if (auto delta = deltas.Find(IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT)) { + if (auto delta = deltas.Find(IndexDeltaType::ADDED_DATA)) { // rows committed while a checkpoint runs are only in this delta delta->VerifyAppend(chunk, index_append_info, manager); } @@ -406,15 +470,15 @@ void IndexEntry::VerifyForeignKey(const shared_ptr &delete_entry, Da D_ASSERT(delete_entry->owned_index->IsBound()); index_append_info.delete_indexes.push_back(delete_entry->owned_index->Cast()); } - if (auto delta = deltas.Find(IndexDeltaType::REMOVED_DATA_DURING_CHECKPOINT)) { + if (auto delta = deltas.Find(IndexDeltaType::REMOVED_DATA)) { index_append_info.delete_indexes.push_back(*delta); } bound_index.VerifyConstraint(chunk, index_append_info, conflict_manager); - if (auto delta = deltas.Find(IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT)) { + if (auto delta = deltas.Find(IndexDeltaType::ADDED_DATA)) { // if we have added any rows during checkpoint - check in that index as well - IndexAppendInfo added_during_checkpoint_info; - delta->VerifyConstraint(chunk, added_during_checkpoint_info, conflict_manager); + IndexAppendInfo added_data_info; + delta->VerifyConstraint(chunk, added_data_info, conflict_manager); } } @@ -565,13 +629,56 @@ void IndexEntry::MergeCheckpointDeltas(const optional_idx checkpoint_id) { deltas.MarkWritten(checkpoint_id); } +void IndexEntry::MergeBuildDeltas(BoundIndex &index, const IndexBuildDeltas &deltas) { + // remove first, so that a key moved to another row is not a duplicate + for (const auto type : {IndexDeltaType::REMOVED_DATA, IndexDeltaType::ADDED_DATA}) { + auto &delta = type == IndexDeltaType::REMOVED_DATA ? deltas.removed : deltas.added; + if (!delta) { + continue; + } + auto error = index.MergeDelta(type, *delta, IndexAppendMode::DEFAULT); + if (error.HasError()) { + if (error.Type() == ExceptionType::CONSTRAINT) { + throw ConstraintException("Data contains duplicates on indexed column(s)"); + } + error.Throw(); + } + } +} + +IndexBuildDeltas IndexEntry::TakeBuildDeltas() { + auto entry_lock = lock.GetExclusiveLock(); + D_ASSERT(building); + if (build_error.HasError()) { + build_error.Throw(); + } + IndexBuildDeltas result; + result.added = deltas.Take(IndexDeltaType::ADDED_DATA); + result.removed = deltas.Take(IndexDeltaType::REMOVED_DATA); + result.changed_rows = build_changed_rows; + build_changed_rows = 0; + return result; +} + +void IndexEntry::FinishBuild(unique_ptr index, idx_t index_oid_p, ConstraintCheckMode check_mode_p) { + auto entry_lock = lock.GetExclusiveLock(); + D_ASSERT(building); + D_ASSERT(!build_error.HasError()); + D_ASSERT(!deltas.Find(IndexDeltaType::ADDED_DATA)); + D_ASSERT(!deltas.Find(IndexDeltaType::REMOVED_DATA)); + owned_index = std::move(index); + index_oid = index_oid_p; + check_mode = check_mode_p; + building = false; +} + const unique_ptr &IndexDeltas::GetPointer(const IndexDeltaType type) const { switch (type) { case IndexDeltaType::DELETED_ROWS_IN_USE: return deleted_rows_in_use; - case IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT: + case IndexDeltaType::ADDED_DATA: return checkpoint.added_data; - case IndexDeltaType::REMOVED_DATA_DURING_CHECKPOINT: + case IndexDeltaType::REMOVED_DATA: return checkpoint.removed_data; } throw InternalException("Unsupported index delta type"); @@ -581,9 +688,9 @@ unique_ptr &IndexDeltas::GetPointer(const IndexDeltaType type) { switch (type) { case IndexDeltaType::DELETED_ROWS_IN_USE: return deleted_rows_in_use; - case IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT: + case IndexDeltaType::ADDED_DATA: return checkpoint.added_data; - case IndexDeltaType::REMOVED_DATA_DURING_CHECKPOINT: + case IndexDeltaType::REMOVED_DATA: return checkpoint.removed_data; } throw InternalException("Unsupported index delta type"); @@ -623,13 +730,13 @@ bool IndexDeltas::ShouldUse(const optional_idx active_checkpoint) const { } ErrorData IndexDeltas::MergeCheckpointDeltas(BoundIndex &index) { - for (const auto type : - {IndexDeltaType::REMOVED_DATA_DURING_CHECKPOINT, IndexDeltaType::ADDED_DATA_DURING_CHECKPOINT}) { + for (const auto type : {IndexDeltaType::REMOVED_DATA, IndexDeltaType::ADDED_DATA}) { auto &delta = GetPointer(type); if (!delta) { continue; } - auto error = index.MergeCheckpointDelta(type, *delta); + // Inserts happen before deletes during commit, so duplicates must be accepted while merging the added rows. + auto error = index.MergeDelta(type, *delta, IndexAppendMode::INSERT_DUPLICATES); if (error.HasError()) { return error; } @@ -638,6 +745,10 @@ ErrorData IndexDeltas::MergeCheckpointDeltas(BoundIndex &index) { return ErrorData(); } +unique_ptr IndexDeltas::Take(const IndexDeltaType type) { + return std::move(GetPointer(type)); +} + void IndexDeltas::MarkWritten(const optional_idx checkpoint_id) { checkpoint.last_written_checkpoint = checkpoint_id; } diff --git a/src/duckdb/src/storage/local_storage.cpp b/src/duckdb/src/storage/local_storage.cpp index 83280d3c9..66525f328 100644 --- a/src/duckdb/src/storage/local_storage.cpp +++ b/src/duckdb/src/storage/local_storage.cpp @@ -37,13 +37,11 @@ LocalTableStorage::LocalTableStorage(Context &context, DataTable &table) //! 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) { + if (parent.HasOptimisticCollections()) { + throw TransactionException("Cannot alter a table that is being written to by another statement"); + } // 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) { @@ -304,15 +302,47 @@ PhysicalIndex LocalTableStorage::CreateOptimisticCollection(unique_ptr l(collections_lock); - auto &collection = optimistic_collections[collection_index.index]; - return *collection; + if (collection_index.index >= optimistic_collections.size() || !optimistic_collections[collection_index.index]) { + // the table was altered by a connection that shares the transaction while the statement was running + throw TransactionException("The table was modified concurrently by a connection sharing the transaction"); + } + return *optimistic_collections[collection_index.index]; } void LocalTableStorage::ResetOptimisticCollection(const PhysicalIndex collection_index) { lock_guard l(collections_lock); + if (collection_index.index >= optimistic_collections.size()) { + throw TransactionException("The table was modified concurrently by a connection sharing the transaction"); + } optimistic_collections[collection_index.index].reset(); } +unique_ptr LocalTableStorage::LockShared() { + auto key = flush_lock.GetSharedLock(); + if (replaced_by_alter) { + throw TransactionException("The table was altered concurrently by a connection sharing the transaction"); + } + return key; +} + +unique_ptr LocalTableStorage::LockAppend() { + auto key = append_lock.GetExclusiveLock(); + if (replaced_by_alter) { + throw TransactionException("The table was altered concurrently by a connection sharing the transaction"); + } + return key; +} + +bool LocalTableStorage::HasOptimisticCollections() { + lock_guard l(collections_lock); + for (auto &collection : optimistic_collections) { + if (collection) { + return true; + } + } + return false; +} + OptimisticDataWriter &LocalTableStorage::GetOptimisticWriter() { return optimistic_writer; } @@ -345,6 +375,9 @@ shared_ptr LocalTableManager::GetOrCreateStorage(Context &con lock_guard l(table_storage_lock); auto entry = table_storage.find(table); if (entry == table_storage.end()) { + if (altered_tables.find(table) != altered_tables.end()) { + throw TransactionException("The table was altered concurrently by a connection sharing the transaction"); + } auto new_storage = make_shared_ptr(context, table); table_storage.insert(make_pair(reference(table), new_storage)); return new_storage; @@ -368,6 +401,17 @@ shared_ptr LocalTableManager::MoveEntry(DataTable &table) { return storage_entry; } +void LocalTableManager::ReplaceEntry(DataTable &old_table, DataTable &new_table, shared_ptr entry) { + lock_guard l(table_storage_lock); + auto old_entry = table_storage.find(old_table); + D_ASSERT(old_entry != table_storage.end()); + old_entry->second->replaced_by_alter = true; + table_storage.erase(old_entry); + altered_tables.insert(old_table); + D_ASSERT(table_storage.find(new_table) == table_storage.end()); + table_storage[new_table] = std::move(entry); +} + reference_map_t> LocalTableManager::MoveEntries() { lock_guard l(table_storage_lock); return std::move(table_storage); @@ -425,11 +469,15 @@ LocalStorage &LocalStorage::Get(ClientContext &context, Catalog &catalog) { void LocalStorage::InitializeScan(const QueryContext &context, DataTable &table, CollectionScanState &state, optional_ptr table_filters) { auto storage = table_manager.GetStorage(table); - if (storage == nullptr || storage->GetCollection().GetTotalRows() == 0) { + if (storage == nullptr) { return; } state.local_storage = storage; - state.local_row_groups_lock = storage->flush_lock.GetSharedLock(); + auto row_groups_lock = storage->LockShared(); + if (storage->GetCollection().GetTotalRows() == 0) { + return; + } + state.local_row_groups_lock = std::move(row_groups_lock); storage->InitializeScan(context, state, table_filters); } @@ -444,6 +492,7 @@ void LocalStorage::InitializeParallelScan(DataTable &table, ParallelCollectionSc state.vector_index = 0; state.current_row_group = nullptr; } else { + auto flush_key = storage->LockShared(); storage->GetCollection().InitializeParallelScan(state); } } @@ -465,7 +514,7 @@ optional_idx LocalStorage::NextParallelScan(ClientContext &context, DataTable &t } if (!scan_state.local_row_groups_lock) { scan_state.local_storage = storage; - scan_state.local_row_groups_lock = storage->flush_lock.GetSharedLock(); + scan_state.local_row_groups_lock = storage->LockShared(); } return storage->GetCollection().NextParallelScan(context, state, scan_state, initialize_columns); } @@ -474,7 +523,7 @@ void LocalStorage::InitializeAppend(Context &context, LocalAppendState &state, D DuckTableEntry &table_entry) { state.context = &context; state.storage = table_manager.GetOrCreateStorage(context, table); - state.append_lock = state.storage->append_lock.GetExclusiveLock(); + state.append_lock = state.storage->LockAppend(); state.storage->table_entry = &table_entry; state.storage->GetCollection().InitializeAppend(TransactionData(transaction), state.append_state); } @@ -555,7 +604,7 @@ void LocalStorage::LocalMerge(Context &context, DataTable &table, DuckTableEntry OptimisticWriteCollection &collection) { auto storage_ptr = table_manager.GetOrCreateStorage(context, table); auto &storage = *storage_ptr; - auto append_lock = storage.append_lock.GetExclusiveLock(); + auto append_lock = storage.LockAppend(); storage.table_entry = &table_entry; if (!storage.GetAppendIndexes().Empty()) { // append data to indexes if required @@ -613,7 +662,7 @@ idx_t LocalStorage::Delete(Context &context, DataTable &table, DuckTableEntry &t auto storage = table_manager.GetStorage(table); D_ASSERT(storage); - auto flush_key = storage->flush_lock.GetSharedLock(); + auto flush_key = storage->LockShared(); auto ids = FlatVector::GetDataMutable(row_ids); if (storage->GetAppendIndexes().Empty()) { idx_t delete_count = storage->GetCollection().Delete(TransactionData::Unversioned(), table_entry, ids, count); @@ -653,7 +702,7 @@ void LocalStorage::Update(DataTable &table, DuckTableEntry &table_entry, Vector auto storage = table_manager.GetStorage(table); D_ASSERT(storage); - auto flush_key = storage->flush_lock.GetSharedLock(); + auto flush_key = storage->LockShared(); auto ids = FlatVector::GetDataMutable(row_ids); storage->GetCollection().Update(TransactionData::Unversioned(), table_entry, ids, column_ids, updates); } @@ -713,8 +762,9 @@ void LocalStorage::Flush(Context &context, DataTable &table, LocalTableStorage & throw IOException("Forced flush append failure (debug_force_flush_append_failure)"); } // table_entry is set through the append path (InitializeAppend/Append/LocalMerge/Alter) - D_ASSERT(storage.table_entry); - transaction.PushAppend(*storage.table_entry, NumericCast(append_state.row_start), append_count); + auto table_entry = storage.table_entry.load(); + D_ASSERT(table_entry); + transaction.PushAppend(*table_entry, NumericCast(append_state.row_start), append_count); } } catch (std::exception &ex) { // the shared table or indexes may be partially modified: no checkpoint may persist them @@ -782,6 +832,7 @@ idx_t LocalStorage::AddedRows(DataTable &table) { if (!storage) { return 0; } + auto flush_key = storage->LockShared(); return storage->GetCollection().GetTotalRows() - storage->deleted_rows; } @@ -790,7 +841,7 @@ vector LocalStorage::GetPartitionStats(DataTable &table, Tr if (!storage) { return vector(); } - auto flush_key = storage->flush_lock.GetSharedLock(); + auto flush_key = storage->LockShared(); return storage->GetCollection().GetPartitionStats(transaction); } @@ -804,46 +855,68 @@ void LocalStorage::DropTable(DataTable &table) { 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 storage = table_manager.MoveEntry(old_dt); + LocalStorageAlterLocks locks; + auto storage = BeginAlter(old_dt, locks); if (!storage) { return; } - table_manager.InsertEntry(new_dt, make_shared_ptr(context, new_dt, *storage)); + FinishAlter(old_dt, new_dt, make_shared_ptr(context, new_dt, *storage)); +} + +shared_ptr LocalStorage::BeginAlter(DataTable &old_dt, LocalStorageAlterLocks &locks) { + auto storage = table_manager.GetStorage(old_dt); + if (!storage) { + return nullptr; + } + // statements of other connections that share the transaction can be using the storage + locks.append_key = storage->append_lock.TryGetExclusiveLock(); + locks.flush_key = storage->flush_lock.TryGetExclusiveLock(); + if (!locks.append_key || !locks.flush_key) { + throw TransactionException("Cannot alter a table that is used by another connection of the shared transaction"); + } + return storage; +} + +void LocalStorage::FinishAlter(DataTable &old_dt, DataTable &new_dt, shared_ptr new_storage) { + // statements that wait for the locks of the old storage see that it was replaced + table_manager.ReplaceEntry(old_dt, new_dt, std::move(new_storage)); } void LocalStorage::AddColumn(ClientContext &context, DataTable &old_dt, DataTable &new_dt, ColumnDefinition &new_column, ExpressionExecutor &default_executor) { // check if there are any pending appends for the old version of the table - auto storage = table_manager.MoveEntry(old_dt); + LocalStorageAlterLocks locks; + auto storage = BeginAlter(old_dt, locks); if (!storage) { return; } - auto new_storage = make_shared_ptr(context, new_dt, *storage, new_column, default_executor); - table_manager.InsertEntry(new_dt, std::move(new_storage)); + FinishAlter(old_dt, new_dt, + make_shared_ptr(context, new_dt, *storage, new_column, default_executor)); } 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); + LocalStorageAlterLocks locks; + auto storage = BeginAlter(old_dt, locks); if (!storage) { return; } - auto new_storage = make_shared_ptr(context, new_dt, *storage, drop_column_index); - table_manager.InsertEntry(new_dt, std::move(new_storage)); + FinishAlter(old_dt, new_dt, make_shared_ptr(context, new_dt, *storage, drop_column_index)); } void LocalStorage::ChangeType(ClientContext &context, DataTable &old_dt, DataTable &new_dt, idx_t changed_idx, const LogicalType &target_type, const vector &bound_columns, Expression &cast_expr) { // check if there are any pending appends for the old version of the table - auto storage = table_manager.MoveEntry(old_dt); + LocalStorageAlterLocks locks; + auto storage = BeginAlter(old_dt, locks); if (!storage) { return; } - auto new_storage = make_shared_ptr(context, new_dt, *storage, changed_idx, target_type, - bound_columns, cast_expr, transaction); - table_manager.InsertEntry(new_dt, std::move(new_storage)); + FinishAlter(old_dt, new_dt, + make_shared_ptr(context, new_dt, *storage, changed_idx, target_type, bound_columns, + cast_expr, transaction)); } void LocalStorage::FetchChunk(DataTable &table, const Vector &row_ids, idx_t count, const vector &col_ids, @@ -852,7 +925,7 @@ void LocalStorage::FetchChunk(DataTable &table, const Vector &row_ids, idx_t cou if (!storage) { throw InternalException("LocalStorage::FetchChunk - local storage not found"); } - auto flush_key = storage->flush_lock.GetSharedLock(); + auto flush_key = storage->LockShared(); storage->GetCollection().Fetch(transaction, chunk, col_ids, row_ids, count, fetch_state); } @@ -861,7 +934,7 @@ bool LocalStorage::CanFetch(DataTable &table, const row_t row_id) { if (!storage) { throw InternalException("LocalStorage::CanFetch - local storage not found"); } - auto flush_key = storage->flush_lock.GetSharedLock(); + auto flush_key = storage->LockShared(); return storage->GetCollection().CanFetch(transaction, row_id); } @@ -880,7 +953,7 @@ void LocalStorage::VerifyNewConstraint(Context &context, DataTable &parent, cons if (!storage) { return; } - auto flush_key = storage->flush_lock.GetSharedLock(); + auto flush_key = storage->LockShared(); storage->GetCollection().VerifyNewConstraint(context, transaction, parent, constraint); } diff --git a/src/duckdb/src/storage/serialization/serialize_parse_info.cpp b/src/duckdb/src/storage/serialization/serialize_parse_info.cpp index 9e4382872..b7ecfda5a 100644 --- a/src/duckdb/src/storage/serialization/serialize_parse_info.cpp +++ b/src/duckdb/src/storage/serialization/serialize_parse_info.cpp @@ -844,6 +844,7 @@ void TransactionInfo::Serialize(Serializer &serializer) const { serializer.WriteProperty(201, "modifier", modifier); serializer.WritePropertyWithDefault(202, "invalidation_policy", invalidation_policy, TransactionInvalidationPolicy::STANDARD_POLICY); serializer.WritePropertyWithDefault(203, "auto_rollback", auto_rollback); + serializer.WritePropertyWithDefault(204, "share_id", share_id, string()); } unique_ptr TransactionInfo::Deserialize(Deserializer &deserializer) { @@ -852,6 +853,7 @@ unique_ptr TransactionInfo::Deserialize(Deserializer &deserializer) { deserializer.ReadProperty(201, "modifier", result->modifier); deserializer.ReadPropertyWithExplicitDefault(202, "invalidation_policy", result->invalidation_policy, TransactionInvalidationPolicy::STANDARD_POLICY); deserializer.ReadPropertyWithDefault(203, "auto_rollback", result->auto_rollback); + deserializer.ReadPropertyWithExplicitDefault(204, "share_id", result->share_id, string()); return std::move(result); } diff --git a/src/duckdb/src/storage/table/column_data.cpp b/src/duckdb/src/storage/table/column_data.cpp index f0f6b3a46..263e59c80 100644 --- a/src/duckdb/src/storage/table/column_data.cpp +++ b/src/duckdb/src/storage/table/column_data.cpp @@ -89,6 +89,10 @@ StorageManager &ColumnData::GetStorageManager() const { } bool ColumnData::HasUpdates() const { + if (!updates_may_exist.load(std::memory_order_acquire)) { + return false; + } + // Also synchronizes callers with the writer; the guard does not publish a constructed segment. lock_guard update_guard(update_lock); return updates.get(); } @@ -360,6 +364,8 @@ void ColumnData::UpdateInternal(TransactionData transaction, DuckTableEntry &tab idx_t row_group_start) { lock_guard update_guard(update_lock); if (!updates) { + // Publish before construction so readers synchronize through update_lock. + updates_may_exist.store(true, std::memory_order_release); updates = make_uniq(*this); } updates->Update(transaction, table_entry, column_index, update_vector, row_ids, update_count, base_vector, diff --git a/src/duckdb/src/storage/table/list_column_data.cpp b/src/duckdb/src/storage/table/list_column_data.cpp index c45faf971..aae750a48 100644 --- a/src/duckdb/src/storage/table/list_column_data.cpp +++ b/src/duckdb/src/storage/table/list_column_data.cpp @@ -144,7 +144,7 @@ idx_t ListColumnData::ScanCount(ColumnScanState &state, Vector &result, idx_t co return 0; } // updates not supported for lists - D_ASSERT(!updates); + D_ASSERT(!HasUpdates()); Vector offset_vector(LogicalType::UBIGINT, count); idx_t scan_count = ScanVector(state, offset_vector, count, ScanVectorType::SCAN_FLAT_VECTOR); diff --git a/src/duckdb/src/storage/table/row_group_collection.cpp b/src/duckdb/src/storage/table/row_group_collection.cpp index e88d3d074..245144b73 100644 --- a/src/duckdb/src/storage/table/row_group_collection.cpp +++ b/src/duckdb/src/storage/table/row_group_collection.cpp @@ -372,6 +372,15 @@ void RowGroupCollection::InitializeParallelScan(ParallelCollectionScanState &sta state.max_row = state.row_groups->GetBaseRowId() + next_row_id.load(); state.batch_index = 0; state.skipped_rows = 0; + state.claim_index.store(0, std::memory_order_relaxed); + state.claim_nodes.clear(); + if (state.claim_mode == ParallelScanClaimMode::ATOMIC) { + auto l = state.row_groups->Lock(); + state.claim_nodes.reserve(state.row_groups->GetSegmentCount(l)); + for (auto &node : state.row_groups->ReferenceLoadedSegmentsMutable(l)) { + state.claim_nodes.emplace_back(*node); + } + } if (state.reorderer) { // row groups pruned by the reorderer are never scanned idx_t total_rows = 0; @@ -386,6 +395,54 @@ void RowGroupCollection::InitializeParallelScan(ParallelCollectionScanState &sta optional_idx RowGroupCollection::NextParallelScan(ClientContext &context, ParallelCollectionScanState &state, CollectionScanState &scan_state, bool initialize_columns) { AssignSharedPointer(scan_state.row_groups, state.row_groups); + switch (state.claim_mode) { + case ParallelScanClaimMode::ATOMIC: + return NextParallelScanAtomic(context, state, scan_state, initialize_columns); + case ParallelScanClaimMode::LOCKED: + return NextParallelScanLocked(context, state, scan_state, initialize_columns); + default: + throw InternalException("Unknown parallel scan claim mode"); + } +} + +optional_idx RowGroupCollection::NextParallelScanAtomic(ClientContext &context, ParallelCollectionScanState &state, + CollectionScanState &scan_state, bool initialize_columns) { + D_ASSERT(!state.reorderer && !state.partitions_to_scan); + D_ASSERT(!state.row_number_base.IsValid() && !scan_state.row_number_base.IsValid()); + D_ASSERT(!ClientConfig::GetConfig(context).verify_parallelism); + idx_t skipped_rows = 0; + while (true) { + const auto index = state.claim_index.fetch_add(1, std::memory_order_relaxed); + if (index >= state.claim_nodes.size()) { + break; + } + auto &node = state.claim_nodes[index].get(); + auto &row_group = node.GetNode(); + const auto start = node.GetRowStart(); + const auto end = MinValue(start + row_group.count, state.max_row); + const auto count = end > start ? end - start : 0; + scan_state.batch_index = node.GetIndex() + 1; + if (count && + InitializeScanInRowGroup(context, scan_state, *state.collection, node, 0, end, initialize_columns)) { + if (skipped_rows) { + state.skipped_rows.fetch_add(skipped_rows, std::memory_order_relaxed); + } + return count; + } + skipped_rows += count; + if ((index + 1) % 2048 == 0) { + context.InterruptCheck(); + } + } + if (skipped_rows) { + state.skipped_rows.fetch_add(skipped_rows, std::memory_order_relaxed); + } + scan_state.batch_index = state.claim_nodes.size(); + return optional_idx(); +} + +optional_idx RowGroupCollection::NextParallelScanLocked(ClientContext &context, ParallelCollectionScanState &state, + CollectionScanState &scan_state, bool initialize_columns) { while (true) { idx_t vector_index; idx_t max_row; @@ -1074,9 +1131,13 @@ void RowGroupCollection::Update(TransactionData transaction, DuckTableEntry &tab void RowGroupCollection::RemoveFromIndexes(const QueryContext &context, TableIndexList &indexes, Vector &row_identifiers, idx_t count, IndexRemovalType removal_type, - optional_idx active_checkpoint) { - // Collect all Indexed columns on the table. - auto indexed_column_id_set = indexes.GetIndexedColumns(); + optional_idx active_checkpoint, VisibilityBound bound) { + // Collect the indexed columns of the indexes we remove from. + auto indexed_column_id_set = indexes.GetIndexedColumns(bound); + if (indexed_column_id_set.empty()) { + // no index was added before this commit + return; + } // Sorted so that the fetched columns align with the ascending physical order used when // referencing them into result_chunk below. @@ -1117,7 +1178,7 @@ void RowGroupCollection::RemoveFromIndexes(const QueryContext &context, TableInd result_chunk.data[j].Reference(Value(types[j]), count_t(fetch_chunk.size())); } - indexes.RemoveFromIndexes(result_chunk, row_identifiers, removal_type, active_checkpoint); + indexes.RemoveFromIndexes(result_chunk, row_identifiers, removal_type, active_checkpoint, bound); } void RowGroupCollection::UpdateColumn(TransactionData transaction, DuckTableEntry &table_entry, Vector &row_ids, diff --git a/src/duckdb/src/storage/table/standard_column_data.cpp b/src/duckdb/src/storage/table/standard_column_data.cpp index 6c06d1474..85b9e925a 100644 --- a/src/duckdb/src/storage/table/standard_column_data.cpp +++ b/src/duckdb/src/storage/table/standard_column_data.cpp @@ -198,11 +198,7 @@ void StandardColumnData::UpdateColumn(TransactionData transaction, DuckTableEntr } unique_ptr StandardColumnData::GetUpdateStatistics() { - unique_ptr stats; - { - lock_guard update_guard(update_lock); - stats = updates ? updates->GetStatistics() : nullptr; - } + auto stats = ColumnData::GetUpdateStatistics(); auto validity_stats = validity->GetUpdateStatistics(); if (!stats && !validity_stats) { return nullptr; diff --git a/src/duckdb/src/storage/table/struct_column_data.cpp b/src/duckdb/src/storage/table/struct_column_data.cpp index 70d380cb3..e1f963ba1 100644 --- a/src/duckdb/src/storage/table/struct_column_data.cpp +++ b/src/duckdb/src/storage/table/struct_column_data.cpp @@ -352,7 +352,8 @@ void StructColumnData::FetchRows(TransactionData transaction, ColumnFetchState & if (!child_storage_index.HasChildren() && child_storage_index.HasType() && child_storage_index.GetType() != child_type) { auto &cast_set = CastFunctionSet::Get(GetDatabase()); - auto cast_input = GetCastFunctionInput::Default(); + auto context = state.context.GetContext(); + auto cast_input = context ? GetCastFunctionInput(*context) : GetCastFunctionInput::Default(); for (idx_t idx = 0; idx < fetch_count; idx++) { const idx_t offset = offsets[sel.get_index(idx)]; Vector intermediate(child_type, 1); diff --git a/src/duckdb/src/storage/table/variant_column_data.cpp b/src/duckdb/src/storage/table/variant_column_data.cpp index 1def6c626..bbed61537 100644 --- a/src/duckdb/src/storage/table/variant_column_data.cpp +++ b/src/duckdb/src/storage/table/variant_column_data.cpp @@ -385,8 +385,13 @@ struct VariantShreddedAppendInput { } // namespace -//! Whether a VARIANT value holds a decimal wider than 38 digits, which engines before wide decimals cannot read -static bool ContainsWideDecimal(const VariantNode &root) { +//! A value inside a VARIANT that engines of an older storage version cannot read back +enum class VariantUnsupportedValue : uint8_t { NONE, WIDE_DECIMAL, GEOGRAPHY }; + +//! Finds a value in a VARIANT that the given storage version cannot represent +static VariantUnsupportedValue FindUnsupportedValue(const VariantNode &root, StorageVersion storage_version) { + const bool check_wide_decimals = storage_version < Decimal::WIDE_VERSION_ADDED; + const bool check_geography = storage_version < Geometry::GEOGRAPHY_VERSION_ADDED; // an explicit work list, deeply nested values must not consume stack vector pending; pending.push_back(root); @@ -395,8 +400,13 @@ static bool ContainsWideDecimal(const VariantNode &root) { pending.pop_back(); switch (node.GetTypeId()) { case LogicalTypeId::DECIMAL: - if (Decimal::IsWide(node.GetDecimalProperties().width)) { - return true; + if (check_wide_decimals && Decimal::IsWide(node.GetDecimalProperties().width)) { + return VariantUnsupportedValue::WIDE_DECIMAL; + } + break; + case LogicalTypeId::GEOGRAPHY: + if (check_geography) { + return VariantUnsupportedValue::GEOGRAPHY; } break; case LogicalTypeId::STRUCT: @@ -413,22 +423,32 @@ static bool ContainsWideDecimal(const VariantNode &root) { break; } } - return false; + return VariantUnsupportedValue::NONE; } -//! The unshredded payload of a wide decimal is stored as it is, so a storage version before wide decimals refuses it -static void CheckWideDecimals(StorageManager &storage_manager, const Vector &vector, idx_t count) { +//! The unshredded payload stores values as they are, so a storage version that predates a value's type refuses it +static void CheckStorageVersionSupport(StorageManager &storage_manager, const Vector &vector, idx_t count) { const auto storage_version = storage_manager.GetStorageVersion(); - if (storage_version >= Decimal::WIDE_VERSION_ADDED) { + if (storage_version >= Decimal::WIDE_VERSION_ADDED && storage_version >= Geometry::GEOGRAPHY_VERSION_ADDED) { return; } VariantIterator iterator(vector); for (idx_t row = 0; row < count; row++) { - if (!iterator.RowIsValid(row) || !ContainsWideDecimal(iterator.Root(row))) { + if (!iterator.RowIsValid(row)) { + continue; + } + auto unsupported = FindUnsupportedValue(iterator.Root(row), storage_version); + if (unsupported == VariantUnsupportedValue::NONE) { continue; } - auto required = GetStorageVersionName(Decimal::WIDE_VERSION_ADDED, false); auto current = GetStorageVersionName(storage_version, false); + if (unsupported == VariantUnsupportedValue::GEOGRAPHY) { + auto required = GetStorageVersionName(Geometry::GEOGRAPHY_VERSION_ADDED, false); + throw InvalidInputException("GEOGRAPHY values cannot be stored in a VARIANT column in storage versions " + "prior to %s (database %s is using storage version %s)", + required, storage_manager.GetAttached().GetName(), current); + } + auto required = GetStorageVersionName(Decimal::WIDE_VERSION_ADDED, false); throw InvalidInputException("DECIMAL values wider than %d digits cannot be stored in a VARIANT column in " "storage versions prior to %s (database %s is using storage version %s)", Decimal::MAX_WIDTH_INT128, required, storage_manager.GetAttached().GetName(), @@ -443,7 +463,7 @@ void VariantColumnData::Append(ColumnAppendState &state, const Vector &vector, i Append(state, append_vector, count); return; } - CheckWideDecimals(GetStorageManager(), vector, count); + CheckStorageVersionSupport(GetStorageManager(), vector, count); // append the null values validity->Append(state.child_appends[0], vector, count); @@ -567,7 +587,8 @@ void VariantColumnData::FetchRows(TransactionData transaction, ColumnFetchState //! Need to perform the cast here as well auto &cast_set = CastFunctionSet::Get(GetDatabase()); - auto cast_input = GetCastFunctionInput::Default(); + auto context = state.context.GetContext(); + auto cast_input = context ? GetCastFunctionInput(*context) : GetCastFunctionInput::Default(); auto fetched_row = extracted_variant.GetValue(0).CastAs(cast_set, cast_input, result.GetType()); result.SetValue(result_idx, fetched_row); } diff --git a/src/duckdb/src/storage/table_index_list.cpp b/src/duckdb/src/storage/table_index_list.cpp index b68a62b56..a33102e86 100644 --- a/src/duckdb/src/storage/table_index_list.cpp +++ b/src/duckdb/src/storage/table_index_list.cpp @@ -28,14 +28,14 @@ namespace duckdb { template -TableIndexIterationHelper::TableIndexIterationHelper(const TableIndexList &index_list) - : lock(index_list.index_entries_lock), index_entries(index_list.index_entries) { +TableIndexIterationHelper::TableIndexIterationHelper(const TableIndexList &index_list, bool skip_building_p) + : lock(index_list.index_entries_lock), index_entries(index_list.index_entries), skip_building(skip_building_p) { } template TableIndexIterationHelper::TableIndexIterator::TableIndexIterator( - optional_ptr>> index_entries_p) - : index_entries(index_entries_p) { + optional_ptr>> index_entries_p, bool skip_building_p) + : index_entries(index_entries_p), skip_building(skip_building_p) { if (index_entries) { if (index_entries->empty()) { index_entries = nullptr; @@ -43,11 +43,11 @@ TableIndexIterationHelper::TableIndexIterator::TableIndexIterator( index = 0; } } + SkipBuilding(); } template -typename TableIndexIterationHelper::TableIndexIterator & -TableIndexIterationHelper::TableIndexIterator::operator++() { +void TableIndexIterationHelper::TableIndexIterator::Advance() { if (index_entries) { auto next_index = index.GetIndex() + 1; if (next_index >= index_entries->size()) { @@ -59,6 +59,20 @@ TableIndexIterationHelper::TableIndexIterator::operator++() { index = next_index; } } +} + +template +void TableIndexIterationHelper::TableIndexIterator::SkipBuilding() { + while (skip_building && index_entries && index_entries->at(index.GetIndex())->IsBuilding()) { + Advance(); + } +} + +template +typename TableIndexIterationHelper::TableIndexIterator & +TableIndexIterationHelper::TableIndexIterator::operator++() { + Advance(); + SkipBuilding(); return *this; } @@ -68,7 +82,11 @@ bool TableIndexIterationHelper::TableIndexIterator::operator!=(const TableInd } TableIndexIterationHelper> TableIndexList::IndexEntries() const { - return TableIndexIterationHelper>(*this); + return TableIndexIterationHelper>(*this, false); +} + +TableIndexIterationHelper> TableIndexList::BuiltIndexEntries() const { + return TableIndexIterationHelper>(*this, true); } template <> @@ -103,6 +121,44 @@ shared_ptr TableIndexList::AddIndex(unique_ptr index, idx_t i return index_entry; } +shared_ptr TableIndexList::AddBuildingIndex(const BoundIndex &index_template, transaction_t build_commit, + transaction_t build_transaction) { + annotated_lock_guard lock(index_entries_lock); + auto index_entry = make_shared_ptr(index_template, build_commit, build_transaction); + index_entries.push_back(index_entry); + return index_entry; +} + +shared_ptr TableIndexList::FindBuildingIndex(transaction_t build_transaction) const { + annotated_lock_guard lock(index_entries_lock); + for (auto &entry : index_entries) { + if (entry->IsBuilding() && entry->GetBuildTransaction() == build_transaction) { + return entry; + } + } + return nullptr; +} + +void TableIndexList::RemoveBuildingIndex(const IndexEntry &entry) { + // a failed build is never published: commits that still hold it only write deltas nobody reads + annotated_lock_guard lock(index_entries_lock); + for (idx_t i = 0; i < index_entries.size(); i++) { + if (index_entries[i].get() == &entry && entry.IsBuilding()) { + index_entries.erase_at(i); + return; + } + } +} + +idx_t TableIndexList::CountBuiltIndexes() const { + idx_t count = 0; + for (auto entry : BuiltIndexEntries()) { + (void)entry; + count++; + } + return count; +} + void TableIndexList::InitializeLocalIndexes(TableIndexList &delete_indexes, TableIndexList &append_indexes) const { D_ASSERT(this != &delete_indexes); D_ASSERT(this != &append_indexes); @@ -173,9 +229,13 @@ void TableIndexList::AppendToDeleteIndexes(DataChunk &chunk, Vector &row_ids) { } void TableIndexList::RemoveFromIndexes(DataChunk &chunk, Vector &row_ids, const IndexRemovalType removal_type, - const optional_idx active_checkpoint) { + const optional_idx active_checkpoint, const VisibilityBound bound) { annotated_lock_guard lock(index_entries_lock); for (const auto &entry : index_entries) { + if (!entry->AddedBefore(bound)) { + // the index was added after this delete committed, so its build never inserted the deleted rows + continue; + } entry->RemoveFromIndex(chunk, row_ids, removal_type, active_checkpoint); } } @@ -267,8 +327,7 @@ void TableIndexList::Vacuum() { } void TableIndexList::Rebuild(const IndexRebuildScan &scan) { - annotated_lock_guard lock(index_entries_lock); - for (const auto &entry : index_entries) { + for (auto entry : BuiltIndexEntries()) { entry->Rebuild(scan); } } @@ -494,10 +553,13 @@ void TableIndexList::VerifyForeignKey(optional_ptr delete_ entry->VerifyForeignKey(delete_entry, chunk, conflict_manager); } -unordered_set TableIndexList::GetIndexedColumns() const { +unordered_set TableIndexList::GetIndexedColumns(const VisibilityBound bound) const { annotated_lock_guard lock(index_entries_lock); unordered_set column_ids; for (const auto &entry : index_entries) { + if (!entry->AddedBefore(bound)) { + continue; + } auto index_info = entry->GetStorageInfo(); column_ids.insert(index_info.column_set.begin(), index_info.column_set.end()); } @@ -527,12 +589,8 @@ class PendingIndexPublication final : public PendingPublication { } // namespace vector> TableIndexList::Checkpoint(TableIndexWriter &writer) { - annotated_lock_guard lock(index_entries_lock); - vector> infos; - infos.reserve(index_entries.size()); - - for (const auto &entry : index_entries) { + for (auto entry : BuiltIndexEntries()) { auto checkpoint = entry->Checkpoint(writer); if (checkpoint.shadow_index) { writer.AddPendingPublication(make_uniq(entry, std::move(checkpoint.shadow_index))); @@ -582,8 +640,7 @@ unique_ptr TableIndexList::SerializeToWAL(idx_t index_oid, con } void TableIndexList::MergeCheckpointDeltas(const optional_idx checkpoint_id) const { - annotated_lock_guard lock(index_entries_lock); - for (const auto &entry : index_entries) { + for (auto entry : BuiltIndexEntries()) { entry->MergeCheckpointDeltas(checkpoint_id); } } diff --git a/src/duckdb/src/transaction/commit_state.cpp b/src/duckdb/src/transaction/commit_state.cpp index 153b38b28..cb80295ce 100644 --- a/src/duckdb/src/transaction/commit_state.cpp +++ b/src/duckdb/src/transaction/commit_state.cpp @@ -89,11 +89,11 @@ IndexDataRemover::IndexDataRemover(DuckTransaction &transaction_p, QueryContext : transaction(transaction_p), context(context), removal_type(removal_type) { } -void IndexDataRemover::PushDelete(DeleteInfo &info) { +bool IndexDataRemover::PushDelete(DeleteInfo &info) { auto &version_table = info.table->GetStorage(); if (!version_table.HasIndexes()) { // this table has no indexes: no cleanup to be done - return; + return false; } idx_t count = 0; @@ -109,6 +109,7 @@ void IndexDataRemover::PushDelete(DeleteInfo &info) { } } Flush(version_table, row_numbers, count); + return removal_type == IndexRemovalType::MAIN_INDEX; } void IndexDataRemover::Verify() { @@ -140,7 +141,8 @@ void IndexDataRemover::Flush(DataTable &table, row_t *row_numbers, idx_t count) // If there is any issue with removal, a FatalException must be thrown since there may be a corruption of // data, hence the transaction cannot be guaranteed. try { - table.RemoveFromIndexes(context, row_identifiers, count, removal_type, checkpoint_id); + table.RemoveFromIndexes(context, row_identifiers, count, removal_type, checkpoint_id, + VisibilityBound::Before(transaction.commit_id)); } catch (std::exception &ex) { throw FatalException(ErrorData(ex).Message()); } catch (...) { @@ -288,7 +290,7 @@ void CommitState::CommitEntryDrop(CatalogEntry &entry, data_ptr_t dataptr, Commi } } -void CommitState::CommitEntry(UndoFlags type, data_ptr_t data, CommitInfo &info) { +void CommitState::CommitEntry(UndoFlags type, data_ptr_t data, CommitInfo &commit_info) { switch (type) { case UndoFlags::CATALOG_ENTRY: { auto &old_entry = *Load(data); @@ -371,7 +373,7 @@ void CommitState::CommitEntry(UndoFlags type, data_ptr_t data, CommitInfo &info) CatalogSet::UpdateTimestamp(old_entry.Parent(), commit_id); // drop any blocks associated with the catalog entry if possible (e.g. in case of a DROP or ALTER) - CommitEntryDrop(old_entry, data + sizeof(CatalogEntry *), info); + CommitEntryDrop(old_entry, data + sizeof(CatalogEntry *), commit_info); break; } case UndoFlags::INSERT_TUPLE: { @@ -398,7 +400,9 @@ void CommitState::CommitEntry(UndoFlags type, data_ptr_t data, CommitInfo &info) throw TransactionException("Attempting to modify table %s but another transaction has %s this table", table_name, table_modification); } - CommitDelete(*info, transaction.GetTransactionId()); + if (CommitDelete(*info, transaction.GetTransactionId())) { + commit_info.has_index_deletes = true; + } break; } case UndoFlags::UPDATE_TUPLE: { @@ -428,11 +432,11 @@ void CommitState::CommitEntry(UndoFlags type, data_ptr_t data, CommitInfo &info) } } -void CommitState::CommitDelete(DeleteInfo &info, transaction_t old_id) { +bool CommitState::CommitDelete(DeleteInfo &info, transaction_t old_id) { // mark the tuples as committed info.version_info->CommitWrite(old_id, commit_id, info, true); // delete from indexes - index_data_remover.PushDelete(info); + return index_data_remover.PushDelete(info); } void CommitState::RevertCommit(UndoFlags type, data_ptr_t data) { diff --git a/src/duckdb/src/transaction/duck_transaction_manager.cpp b/src/duckdb/src/transaction/duck_transaction_manager.cpp index e70351d14..40095460f 100644 --- a/src/duckdb/src/transaction/duck_transaction_manager.cpp +++ b/src/duckdb/src/transaction/duck_transaction_manager.cpp @@ -562,7 +562,7 @@ ErrorData DuckTransactionManager::CommitTransaction(ClientContext &context, Tran // commit successful: remove the transaction id from the list of active transactions // potentially resulting in garbage collection - bool store_transaction = undo_properties.has_updates || undo_properties.has_index_deletes || + bool store_transaction = undo_properties.has_updates || info.has_index_deletes || undo_properties.has_catalog_changes || error.HasError(); if (!commit_wal) { diff --git a/src/duckdb/src/transaction/meta_transaction.cpp b/src/duckdb/src/transaction/meta_transaction.cpp index 4c544bb73..04d1a1730 100644 --- a/src/duckdb/src/transaction/meta_transaction.cpp +++ b/src/duckdb/src/transaction/meta_transaction.cpp @@ -1,8 +1,11 @@ #include "duckdb/transaction/meta_transaction.hpp" #include "duckdb/common/exception/transaction_exception.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/common/types/uuid.hpp" #include "duckdb/main/attached_database.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/client_data.hpp" #include "duckdb/main/database.hpp" #include "duckdb/transaction/transaction_manager.hpp" #include "duckdb/catalog/catalog.hpp" @@ -10,9 +13,11 @@ namespace duckdb { -MetaTransaction::MetaTransaction(DatabaseInstance &db, timestamp_t start_timestamp_p, transaction_t transaction_id_p) +MetaTransaction::MetaTransaction(DatabaseInstance &db, shared_ptr temporary_objects_p, + timestamp_t start_timestamp_p, transaction_t transaction_id_p) : start_timestamp(start_timestamp_p), global_transaction_id(transaction_id_p), transaction_validity(db), - modified_database(nullptr), is_read_only(false) { + modified_database(nullptr), is_read_only(false), temporary_objects(std::move(temporary_objects_p)), + finished(false) { } MetaTransaction::~MetaTransaction() = default; @@ -190,6 +195,60 @@ void MetaTransaction::Rollback(ClientContext &context) { } } +string MetaTransaction::ShareTransaction() { + lock_guard guard(shared_lock); + if (share_id.empty()) { + // the identifier grants access to the transaction, so it must not be predictable + share_id = UUID::ToString(UUIDv4::GenerateRandomUUID()); + } + return share_id; +} + +string MetaTransaction::GetShareId() { + lock_guard guard(shared_lock); + return share_id; +} + +bool MetaTransaction::Join(bool inherited) { + lock_guard guard(shared_lock); + if (finished) { + return false; + } + participants++; + if (inherited) { + inherited_participants++; + this->inherited = true; + } + return true; +} + +MetaTransaction::LeaveResult MetaTransaction::Leave(bool commit, bool inherited) { + lock_guard guard(shared_lock); + D_ASSERT(participants > 0); + D_ASSERT(!inherited || inherited_participants > 0); + if (!commit) { + rollback_vote = true; + } + participants--; + if (inherited) { + inherited_participants--; + } + LeaveResult result; + result.last = participants == 0; + result.orphaned = !inherited && !result.last && participants == inherited_participants; + if (result.orphaned) { + // the inheriting connections cannot end the transaction on their own: it is rolled back once they leave + rollback_vote = true; + } + result.commit = !rollback_vote; + // a transaction that only inheriting connections are in is rolled back + D_ASSERT(!inherited || !result.last || !result.commit); + if (result.last) { + finished = true; + } + return result; +} + void MetaTransaction::Finalize(ClientContext &context) { // Try to checkpoint any attached databases potentially still held by this transaction. for (auto &database : referenced_databases) { diff --git a/src/duckdb/src/transaction/transaction_context.cpp b/src/duckdb/src/transaction/transaction_context.cpp index fbbff31a0..28ba4674d 100644 --- a/src/duckdb/src/transaction/transaction_context.cpp +++ b/src/duckdb/src/transaction/transaction_context.cpp @@ -10,6 +10,8 @@ #include "duckdb/main/attached_database.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/main/database_manager.hpp" +#include "duckdb/main/connection_manager.hpp" +#include "duckdb/main/valid_checker.hpp" namespace duckdb { @@ -18,6 +20,35 @@ TransactionContext::TransactionContext(ClientContext &context) auto_rollback(false), current_transaction(nullptr) { } +void TransactionContext::SetCurrentTransaction(shared_ptr transaction) { + lock_guard guard(current_transaction_lock); + current_transaction = std::move(transaction); +} + +shared_ptr TransactionContext::TakeCurrentTransaction() { + lock_guard guard(current_transaction_lock); + return std::move(current_transaction); +} + +shared_ptr TransactionContext::GetCurrentTransaction() { + lock_guard guard(current_transaction_lock); + return current_transaction; +} + +shared_ptr TransactionContext::GetSharedTransaction(const string &share_id) { + lock_guard guard(current_transaction_lock); + // a transaction that was never shared has an empty share id, which must not match + if (!share_id.empty() && current_transaction && current_transaction->GetShareId() == share_id) { + return current_transaction; + } + return nullptr; +} + +bool TransactionContext::IsInSharedTransaction() { + lock_guard guard(current_transaction_lock); + return current_transaction && current_transaction->IsShared(); +} + TransactionContext::~TransactionContext() { } @@ -27,7 +58,8 @@ void TransactionContext::BeginTransaction() { } auto start_timestamp = Timestamp::GetCurrentTimestamp(); auto global_transaction_id = context.db->GetDatabaseManager().GetNewTransactionNumber(); - current_transaction = make_uniq(*context.db, start_timestamp, global_transaction_id); + SetCurrentTransaction(make_shared_ptr(*context.db, context.client_data->temporary_objects, + start_timestamp, global_transaction_id)); // Notify any registered state of transaction begin for (auto &state : context.GetContext().GetRegisteredState().States()) { @@ -52,8 +84,32 @@ void TransactionContext::Commit() { throw TransactionException("failed to commit: no transaction active"); } autocheckpoint_error = ErrorData(); - auto transaction = std::move(current_transaction); + const bool was_inherited = inherited; + auto transaction = TakeCurrentTransaction(); ClearTransaction(); + auto leave = transaction->Leave(true, was_inherited); + if (!leave.last) { + if (leave.orphaned) { + ValidChecker::Invalidate(*transaction, "the transaction was rolled back: it was ended while a connection " + "that inherited it was still open"); + for (auto const &state : context.GetContext().GetRegisteredState().States()) { + state->TransactionRollback(*transaction, context, nullptr); + } + throw TransactionException( + "Failed to commit: a connection that inherited the transaction is still open, it is rolled back"); + } + // other connections still participate in the transaction, the last one to leave ends it + for (auto &state : context.GetContext().GetRegisteredState().States()) { + state->TransactionCommit(*transaction, context); + } + return; + } + const bool commit_result = leave.commit; + if (!commit_result) { + // a participant rolled back: the transaction cannot be committed + RollbackTransaction(transaction, nullptr); + throw TransactionException("Failed to commit: a connection sharing the transaction rolled it back"); + } auto error = transaction->Commit(context); // Notify any registered state of transaction commit if (error.HasError()) { @@ -92,9 +148,26 @@ void TransactionContext::Rollback(optional_ptr error) { if (!current_transaction) { throw TransactionException("failed to rollback: no transaction active"); } - auto transaction = std::move(current_transaction); + const bool was_inherited = inherited; + auto transaction = TakeCurrentTransaction(); ClearTransaction(); + // a connection that inherited the transaction does not vote: its failures already invalidated the transaction + auto leave = transaction->Leave(was_inherited, was_inherited); + if (!leave.last) { + if (leave.orphaned) { + ValidChecker::Invalidate(*transaction, "the transaction was rolled back while a connection that " + "inherited it was still open"); + } + for (auto &state : context.GetContext().GetRegisteredState().States()) { + state->TransactionRollback(*transaction, context, error); + } + return; + } + RollbackTransaction(transaction, error); +} +void TransactionContext::RollbackTransaction(const shared_ptr &transaction, + optional_ptr error) { ErrorData rollback_error; try { transaction->Rollback(context); @@ -117,9 +190,83 @@ void TransactionContext::Rollback(optional_ptr error) { transaction->Finalize(context); } +string TransactionContext::ShareTransaction() { + if (!HasActiveTransaction() || auto_commit) { + throw TransactionException("a transaction can only be shared from within a BEGIN TRANSACTION block"); + } + return current_transaction->ShareTransaction(); +} + +void TransactionContext::JoinTransaction(const string &share_id) { + if (!auto_commit) { + throw TransactionException("cannot join a transaction within a transaction"); + } + // find a connection that participates in the shared transaction + shared_ptr source; + for (auto &connection : ConnectionManager::Get(*context.db).GetConnectionList()) { + if (connection.get() == &context) { + continue; + } + source = connection->transaction.GetSharedTransaction(share_id); + if (source) { + break; + } + } + auto not_active = StringUtil::Format("invalid transaction identifier: \"%s\"", share_id); + auto aborted = StringUtil::Format("cannot join transaction \"%s\": it was aborted", share_id); + EnterTransaction(std::move(source), false, not_active, aborted); +} + +void TransactionContext::InheritTransaction(ClientContext &source) { + if (&source == &context) { + throw InvalidInputException("a connection cannot inherit its own transaction"); + } + if (source.db != context.db) { + throw InvalidInputException("cannot inherit the transaction of a connection to another database instance"); + } + if (!auto_commit || current_transaction) { + throw TransactionException("cannot inherit a transaction within a transaction"); + } + // errors invalidate the transaction as they would in the connection it was inherited from + invalidation_policy = source.transaction.GetInvalidationPolicy(); + EnterTransaction(source.transaction.GetCurrentTransaction(), true, + "cannot inherit the transaction of a connection that has no active transaction", + "cannot inherit the transaction: it was aborted"); +} + +void TransactionContext::EnterTransaction(shared_ptr transaction, bool inherit, + const string ¬_active_error, const string &aborted_error) { + if (!transaction || transaction->IsFinished()) { + throw TransactionException(not_active_error); + } + if (ValidChecker::IsInvalidated(*transaction)) { + throw TransactionException(aborted_error); + } + if (!transaction->Join(inherit)) { + throw TransactionException(not_active_error); + } + // a JOIN TRANSACTION statement runs in a transaction of its own: discard it and continue in the joined one + auto previous = TakeCurrentTransaction(); + SetCurrentTransaction(std::move(transaction)); + auto_commit = false; + inherited = inherit; + if (previous) { + previous->MarkFinished(); + try { + RollbackTransaction(previous, nullptr); + } catch (std::exception &) { + // the discarded transaction is empty, a failure to end it must not undo the join + } + } + for (auto &state : context.GetContext().GetRegisteredState().States()) { + state->TransactionBegin(*current_transaction, context); + } +} + void TransactionContext::ClearTransaction() { + inherited = false; SetAutoCommit(true); - current_transaction = nullptr; + SetCurrentTransaction(nullptr); active_query_id = MAXIMUM_QUERY_ID; } diff --git a/src/duckdb/src/transaction/undo_buffer.cpp b/src/duckdb/src/transaction/undo_buffer.cpp index fe20a9345..b90b27142 100644 --- a/src/duckdb/src/transaction/undo_buffer.cpp +++ b/src/duckdb/src/transaction/undo_buffer.cpp @@ -104,7 +104,8 @@ void UndoBuffer::ReverseIterateEntries(T &&callback) { } bool UndoBuffer::ChangesMade() { - // we need to search for any index creation entries + // statements of connections that share the transaction can add entries concurrently + lock_guard guard(allocator.lock); return allocator.head.get(); } @@ -131,9 +132,6 @@ UndoBufferProperties UndoBuffer::GetProperties() { if (info->is_consecutive) { properties.estimated_size += sizeof(row_t) * info->count; } - if (info->table->GetStorage().HasIndexes()) { - properties.has_index_deletes = true; - } properties.has_deletes = true; break; } diff --git a/src/duckdb/ub_src_common.cpp b/src/duckdb/ub_src_common.cpp index 433104204..f53389f48 100644 --- a/src/duckdb/ub_src_common.cpp +++ b/src/duckdb/ub_src_common.cpp @@ -1,5 +1,7 @@ #include "src/common/assert.cpp" +#include "src/common/base_file_system.cpp" + #include "src/common/bignum.cpp" #include "src/common/bind_helpers.cpp" @@ -70,8 +72,6 @@ #include "src/common/open_file_info.cpp" -#include "src/common/opener_file_system.cpp" - #include "src/common/optional_idx.cpp" #include "src/common/path.cpp" diff --git a/src/duckdb/ub_src_function_aggregate.cpp b/src/duckdb/ub_src_function_aggregate.cpp new file mode 100644 index 000000000..5ae4ecb43 --- /dev/null +++ b/src/duckdb/ub_src_function_aggregate.cpp @@ -0,0 +1,4 @@ +#include "src/function/aggregate/bignum_aggregates.cpp" + +#include "src/function/aggregate/sorted_aggregate_function.cpp" + diff --git a/src/duckdb/ub_src_function_scalar_system.cpp b/src/duckdb/ub_src_function_scalar_system.cpp index b46a555b1..fb2616dbe 100644 --- a/src/duckdb/ub_src_function_scalar_system.cpp +++ b/src/duckdb/ub_src_function_scalar_system.cpp @@ -10,5 +10,7 @@ #include "src/function/scalar/system/parse_log_message.cpp" +#include "src/function/scalar/system/share_transaction.cpp" + #include "src/function/scalar/system/write_log.cpp" diff --git a/src/duckdb/ub_src_main_capi_v2.cpp b/src/duckdb/ub_src_main_capi_v2.cpp index 5c70d1a2a..4081b4153 100644 --- a/src/duckdb/ub_src_main_capi_v2.cpp +++ b/src/duckdb/ub_src_main_capi_v2.cpp @@ -20,6 +20,8 @@ #include "src/main/capi/v2/capi_v2_data_chunk.cpp" +#include "src/main/capi/v2/capi_v2_data_source.cpp" + #include "src/main/capi/v2/capi_v2_environment.cpp" #include "src/main/capi/v2/capi_v2_error.cpp" diff --git a/src/duckdb/ub_src_optimizer_pullup.cpp b/src/duckdb/ub_src_optimizer_pullup.cpp index e1aa0e575..3d20e2bea 100644 --- a/src/duckdb/ub_src_optimizer_pullup.cpp +++ b/src/duckdb/ub_src_optimizer_pullup.cpp @@ -1,5 +1,7 @@ #include "src/optimizer/pullup/pullup_both_side.cpp" +#include "src/optimizer/pullup/pullup_constraints.cpp" + #include "src/optimizer/pullup/pullup_filter.cpp" #include "src/optimizer/pullup/pullup_from_left.cpp" diff --git a/src/duckdb/ub_src_planner.cpp b/src/duckdb/ub_src_planner.cpp index caf2a8218..8b2405c02 100644 --- a/src/duckdb/ub_src_planner.cpp +++ b/src/duckdb/ub_src_planner.cpp @@ -42,6 +42,8 @@ #include "src/planner/table_binding.cpp" +#include "src/planner/table_filter_combiner.cpp" + #include "src/planner/table_filter_set.cpp" #include "src/planner/table_filter_state.cpp" diff --git a/src/duckdb/ub_src_planner_filter.cpp b/src/duckdb/ub_src_planner_filter.cpp index 2e6f65ddc..2bf44dc1c 100644 --- a/src/duckdb/ub_src_planner_filter.cpp +++ b/src/duckdb/ub_src_planner_filter.cpp @@ -4,6 +4,8 @@ #include "src/planner/filter/constant_filter.cpp" +#include "src/planner/filter/constant_filter_combiner.cpp" + #include "src/planner/filter/dynamic_filter.cpp" #include "src/planner/filter/expression_filter.cpp" From f80025367764482304aec2bf755cf98effbaa8d5 Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Sat, 28 Nov 2026 03:42:17 +0000 Subject: [PATCH 3/8] Update vendored DuckDB sources to 07c9a117d02 --- ...nerated_extension_loader_package_build.cpp | 8 +- .../src/execution/physical_plan/plan_get.cpp | 5 + .../function/table/version/pragma_version.cpp | 6 +- .../capi_v2/capi_v2_function_internal.hpp | 107 +++ .../duckdb/main/capi_v2/capi_v2_internal.hpp | 2 + .../duckdb/main/capi_v2/extension_api_v2.hpp | 105 +++ .../src/include/duckdb/main/connection.hpp | 3 +- .../include/duckdb/main/extension_entries.hpp | 47 +- .../duckdb/optimizer/filter_combiner.hpp | 12 +- .../join_order/cardinality_estimator.hpp | 2 + src/duckdb/src/include/duckdb_extension_v2.h | 174 ++++ src/duckdb/src/include/duckdb_v2.h | 849 +++++++++++++++++- src/duckdb/src/main/capi/v2/capi_v2_func.cpp | 13 +- .../main/capi/v2/capi_v2_func_properties.cpp | 11 + .../src/main/capi/v2/capi_v2_func_table.cpp | 404 ++++++++- .../src/main/capi/v2/capi_v2_operator.cpp | 243 +++++ src/duckdb/src/main/connection.cpp | 6 + src/duckdb/src/main/secret/secret.cpp | 4 +- src/duckdb/src/optimizer/filter_combiner.cpp | 161 +++- .../join_order/cardinality_estimator.cpp | 97 +- .../optimizer/pullup/pullup_projection.cpp | 29 +- .../binder/tableref/bind_table_function.cpp | 2 +- .../src/planner/filter/expression_filter.cpp | 13 + src/duckdb/ub_src_main_capi_v2.cpp | 2 + 24 files changed, 2190 insertions(+), 115 deletions(-) create mode 100644 src/duckdb/src/main/capi/v2/capi_v2_operator.cpp diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 9a32effb0..e2a92527b 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-alpha58110"; + descriptor->api_version = "v2.1.0-alpha58157"; 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-alpha58110"; + descriptor->api_version = "v2.1.0-alpha58157"; 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-alpha58110"; + descriptor->api_version = "v2.1.0-alpha58157"; 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-alpha58110"; + descriptor->api_version = "v2.1.0-alpha58157"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/execution/physical_plan/plan_get.cpp b/src/duckdb/src/execution/physical_plan/plan_get.cpp index 634eea199..97464698d 100644 --- a/src/duckdb/src/execution/physical_plan/plan_get.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_get.cpp @@ -97,6 +97,11 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalGet &op) { break; } } + if (!op.projected_input.empty() && op.function.in_out_function_final) { + throw NotImplementedException("Table in-out function %s has a finalize step, which is not supported for " + "input that is correlated with an outer query", + op.function.GetName()); + } auto &table_in_out = Make( op.types, op.function, std::move(op.bind_data), column_ids, std::move(projection_indices), std::move(table_filters), op.estimated_cardinality, std::move(op.projected_input)); diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index f2708516a..b36854a73 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-alpha58110" +#define DUCKDB_PATCH_VERSION "0-alpha58157" #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-alpha58110" +#define DUCKDB_VERSION "v2.1.0-alpha58157" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "704d4d288a" +#define DUCKDB_SOURCE_ID "07c9a117d0" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp index 7ce27d1db..a17e4f0f8 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/main/capi_v2/capi_v2_internal.hpp" +#include "duckdb/common/enums/operator_result_type.hpp" #include "duckdb/common/named_parameter_map.hpp" #include "duckdb/function/function.hpp" #include "duckdb/function/table_function.hpp" @@ -184,4 +185,110 @@ inline auto Convert(CV2FunctionBindInfo *info) -> duckdb_v2_function_bind_info_h return reinterpret_cast(info); } +//---------------------------------------------------------------------------------------------------------------------- +// Operators +//---------------------------------------------------------------------------------------------------------------------- +//! The callbacks and user data of a custom streaming operator. Copied into what runs it, which shares the user data. +class CV2OperatorInfo { +public: + void *GetUserData() const { + return user_data ? user_data->GetData() : nullptr; + } + +public: + duckdb_v2_operator_init_global_callback_fn init_global_cb = nullptr; + duckdb_v2_operator_init_local_callback_fn init_local_cb = nullptr; + duckdb_v2_operator_execute_callback_fn execute_cb = nullptr; + duckdb_v2_operator_finalize_callback_fn finalize_cb = nullptr; + shared_ptr user_data; +}; + +//! An operator being built through the C API +class CV2Operator { +public: + explicit CV2Operator(DatabaseInstance &db) : db(db) { + } + +public: + //! The database it was created for: the only one whose objects can run it. + DatabaseInstance &db; + CV2OperatorInfo info; +}; + +inline auto Convert(duckdb_v2_operator_handle op) -> CV2Operator * { + return reinterpret_cast(op); +} +inline auto Convert(CV2Operator *op) -> duckdb_v2_operator_handle { + return reinterpret_cast(op); +} + +class CV2OperatorInitGlobalInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + + duckdb_v2_opaque out_global_state = {}; + optional_idx out_max_threads; +}; + +inline auto Convert(duckdb_v2_operator_init_global_info_handle info) -> CV2OperatorInitGlobalInfo * { + return reinterpret_cast(info); +} +inline auto Convert(CV2OperatorInitGlobalInfo *info) -> duckdb_v2_operator_init_global_info_handle { + return reinterpret_cast(info); +} + +class CV2OperatorInitLocalInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + void *in_global_state = nullptr; + + duckdb_v2_opaque out_local_state = {}; +}; + +inline auto Convert(duckdb_v2_operator_init_local_info_handle info) -> CV2OperatorInitLocalInfo * { + return reinterpret_cast(info); +} +inline auto Convert(CV2OperatorInitLocalInfo *info) -> duckdb_v2_operator_init_local_info_handle { + return reinterpret_cast(info); +} + +class CV2OperatorExecuteInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + void *in_global_state = nullptr; + void *in_local_state = nullptr; + optional_ptr input; + optional_ptr output; + + OperatorResultType out_result = OperatorResultType::NEED_MORE_INPUT; +}; + +inline auto Convert(duckdb_v2_operator_execute_info_handle info) -> CV2OperatorExecuteInfo * { + return reinterpret_cast(info); +} +inline auto Convert(CV2OperatorExecuteInfo *info) -> duckdb_v2_operator_execute_info_handle { + return reinterpret_cast(info); +} + +class CV2OperatorFinalizeInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + void *in_global_state = nullptr; + void *in_local_state = nullptr; + optional_ptr output; + + bool out_have_more_output = false; +}; + +inline auto Convert(duckdb_v2_operator_finalize_info_handle info) -> CV2OperatorFinalizeInfo * { + return reinterpret_cast(info); +} +inline auto Convert(CV2OperatorFinalizeInfo *info) -> duckdb_v2_operator_finalize_info_handle { + return reinterpret_cast(info); +} + } // namespace duckdb::capiv2 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 41833770e..0ed5aa12c 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 @@ -514,6 +514,8 @@ auto GetExtensionLoader(duckdb_v2_extension_handle handle) -> ExtensionLoader &; //! capi_v2_func_properties.cpp and shared by the scalar and aggregate set_property entry points. void SetScalarFunctionProperty(FunctionProperties &props, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, DUCKDB_V2_FUNCTION_PROPERTY_VALUE value); +void SetTableFunctionProperty(FunctionStability &stability, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value); void SetAggregateFunctionProperty(AggregateFunctionProperties &props, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, DUCKDB_V2_FUNCTION_PROPERTY_VALUE value); //! Set / get a generic, named function property; shared by the scalar and aggregate entry points 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 3e0a94a66..f4b133dc5 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 @@ -1670,9 +1670,78 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_user_data) (duckdb_v2_data_source_handle source, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_create) + (duckdb_v2_factory_handle factory, duckdb_v2_operator_handle *op, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_operator_destroy)(duckdb_v2_operator_handle *op); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_bind_data) + (duckdb_v2_operator_execute_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_global_state) + (duckdb_v2_operator_execute_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_input_chunk) + (duckdb_v2_operator_execute_info_handle info, duckdb_v2_data_chunk_handle *chunk, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_local_state) + (duckdb_v2_operator_execute_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_output_chunk) + (duckdb_v2_operator_execute_info_handle info, duckdb_v2_data_chunk_handle *chunk, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_user_data) + (duckdb_v2_operator_execute_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_set_result) + (duckdb_v2_operator_execute_info_handle info, DUCKDB_V2_OPERATOR_RESULT result, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_get_bind_data) + (duckdb_v2_operator_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_get_global_state) + (duckdb_v2_operator_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_get_local_state) + (duckdb_v2_operator_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_get_output_chunk) + (duckdb_v2_operator_finalize_info_handle info, duckdb_v2_data_chunk_handle *chunk, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_get_user_data) + (duckdb_v2_operator_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_set_have_more_output) + (duckdb_v2_operator_finalize_info_handle info, bool have_more_output, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_global_get_bind_data) + (duckdb_v2_operator_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_global_get_user_data) + (duckdb_v2_operator_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_global_set_global_state) + (duckdb_v2_operator_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_global_set_max_threads) + (duckdb_v2_operator_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_local_get_bind_data) + (duckdb_v2_operator_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_local_get_global_state) + (duckdb_v2_operator_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_local_get_user_data) + (duckdb_v2_operator_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_local_set_local_state) + (duckdb_v2_operator_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_set_execute_callback) + (duckdb_v2_operator_handle op, duckdb_v2_operator_execute_callback_fn callback, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_set_finalize_callback) + (duckdb_v2_operator_handle op, duckdb_v2_operator_finalize_callback_fn callback, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_set_init_global_callback) + (duckdb_v2_operator_handle op, duckdb_v2_operator_init_global_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_set_init_local_callback) + (duckdb_v2_operator_handle op, duckdb_v2_operator_init_local_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_set_user_data) + (duckdb_v2_operator_handle op, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_get_input_column_count) + (duckdb_v2_table_function_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_get_input_column_name) + (duckdb_v2_table_function_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_get_input_column_type) + (duckdb_v2_table_function_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_data_source) (duckdb_v2_table_function_handle function, duckdb_v2_data_source_handle data_source, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_operator) + (duckdb_v2_table_function_handle function, duckdb_v2_operator_handle op, DUCKDB_V2_TABLE_OPERATOR_INPUT input, + 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_V2_ERROR(*duckdb_v2_copy_from_set_data_source) @@ -1680,6 +1749,9 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_create_in_transaction) (duckdb_v2_context_handle ctx, duckdb_v2_connection_handle *out_conn, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_property) + (duckdb_v2_table_function_handle function, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, duckdb_v2_error_info_handle *err); } duckdb_ext_api_v2; //===--------------------------------------------------------------------===// @@ -2423,10 +2495,43 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_data_source_set_partition_data_callback = duckdb_v2_data_source_set_partition_data_callback; result.duckdb_v2_data_source_set_progress_callback = duckdb_v2_data_source_set_progress_callback; result.duckdb_v2_data_source_set_user_data = duckdb_v2_data_source_set_user_data; + result.duckdb_v2_operator_create = duckdb_v2_operator_create; + result.duckdb_v2_operator_destroy = duckdb_v2_operator_destroy; + result.duckdb_v2_operator_execute_get_bind_data = duckdb_v2_operator_execute_get_bind_data; + result.duckdb_v2_operator_execute_get_global_state = duckdb_v2_operator_execute_get_global_state; + result.duckdb_v2_operator_execute_get_input_chunk = duckdb_v2_operator_execute_get_input_chunk; + result.duckdb_v2_operator_execute_get_local_state = duckdb_v2_operator_execute_get_local_state; + result.duckdb_v2_operator_execute_get_output_chunk = duckdb_v2_operator_execute_get_output_chunk; + result.duckdb_v2_operator_execute_get_user_data = duckdb_v2_operator_execute_get_user_data; + result.duckdb_v2_operator_execute_set_result = duckdb_v2_operator_execute_set_result; + result.duckdb_v2_operator_finalize_get_bind_data = duckdb_v2_operator_finalize_get_bind_data; + result.duckdb_v2_operator_finalize_get_global_state = duckdb_v2_operator_finalize_get_global_state; + result.duckdb_v2_operator_finalize_get_local_state = duckdb_v2_operator_finalize_get_local_state; + result.duckdb_v2_operator_finalize_get_output_chunk = duckdb_v2_operator_finalize_get_output_chunk; + result.duckdb_v2_operator_finalize_get_user_data = duckdb_v2_operator_finalize_get_user_data; + result.duckdb_v2_operator_finalize_set_have_more_output = duckdb_v2_operator_finalize_set_have_more_output; + result.duckdb_v2_operator_init_global_get_bind_data = duckdb_v2_operator_init_global_get_bind_data; + result.duckdb_v2_operator_init_global_get_user_data = duckdb_v2_operator_init_global_get_user_data; + result.duckdb_v2_operator_init_global_set_global_state = duckdb_v2_operator_init_global_set_global_state; + result.duckdb_v2_operator_init_global_set_max_threads = duckdb_v2_operator_init_global_set_max_threads; + result.duckdb_v2_operator_init_local_get_bind_data = duckdb_v2_operator_init_local_get_bind_data; + result.duckdb_v2_operator_init_local_get_global_state = duckdb_v2_operator_init_local_get_global_state; + result.duckdb_v2_operator_init_local_get_user_data = duckdb_v2_operator_init_local_get_user_data; + result.duckdb_v2_operator_init_local_set_local_state = duckdb_v2_operator_init_local_set_local_state; + result.duckdb_v2_operator_set_execute_callback = duckdb_v2_operator_set_execute_callback; + result.duckdb_v2_operator_set_finalize_callback = duckdb_v2_operator_set_finalize_callback; + result.duckdb_v2_operator_set_init_global_callback = duckdb_v2_operator_set_init_global_callback; + result.duckdb_v2_operator_set_init_local_callback = duckdb_v2_operator_set_init_local_callback; + result.duckdb_v2_operator_set_user_data = duckdb_v2_operator_set_user_data; + result.duckdb_v2_table_function_bind_get_input_column_count = duckdb_v2_table_function_bind_get_input_column_count; + result.duckdb_v2_table_function_bind_get_input_column_name = duckdb_v2_table_function_bind_get_input_column_name; + result.duckdb_v2_table_function_bind_get_input_column_type = duckdb_v2_table_function_bind_get_input_column_type; result.duckdb_v2_table_function_set_data_source = duckdb_v2_table_function_set_data_source; + result.duckdb_v2_table_function_set_operator = duckdb_v2_table_function_set_operator; result.duckdb_v2_value_variant_to_value = duckdb_v2_value_variant_to_value; result.duckdb_v2_copy_from_set_data_source = duckdb_v2_copy_from_set_data_source; result.duckdb_v2_connection_create_in_transaction = duckdb_v2_connection_create_in_transaction; + result.duckdb_v2_table_function_set_property = duckdb_v2_table_function_set_property; return result; } diff --git a/src/duckdb/src/include/duckdb/main/connection.hpp b/src/duckdb/src/include/duckdb/main/connection.hpp index 77a8a42f7..046bfa945 100644 --- a/src/duckdb/src/include/duckdb/main/connection.hpp +++ b/src/duckdb/src/include/duckdb/main/connection.hpp @@ -43,7 +43,8 @@ class Connection { //! deadline of caller's base client DUCKDB_API static Connection CreateInternal(ClientContext &caller); //! Creates a connection that runs in the transaction active on `context`, e.g. the one a bind callback runs in. - //! It sees and can modify everything the transaction can, and follows the interrupts of `context`. It cannot + //! It sees and can modify everything the transaction can, starts with the search path of `context` (so unqualified + //! names resolve as they do there), and follows the interrupts of `context`. It cannot //! start, commit or roll back a transaction, and the transaction cannot commit while the connection is open: an //! error of one of its statements invalidates the transaction as one of `context` would. DUCKDB_API static Connection CreateInTransaction(ClientContext &context); diff --git a/src/duckdb/src/include/duckdb/main/extension_entries.hpp b/src/duckdb/src/include/duckdb/main/extension_entries.hpp index f7f556f10..ca8e2cce9 100644 --- a/src/duckdb/src/include/duckdb/main/extension_entries.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_entries.hpp @@ -56,17 +56,25 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"@>", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"^", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"^@", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"__aws__cloudformation__quack_on_ec2__create", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, - {"__aws__cloudformation__quack_on_ec2__destroy", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, - {"__aws__cloudformation__quack_on_ec2__list", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, - {"__aws__cloudformation__quack_on_ec2__resolve", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, - {"__aws__cloudformation__quack_on_ec2__status", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__cloudformation__stack__create", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__cloudformation__stack__destroy", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__cloudformation__stack__list", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__cloudformation__stack__resolve", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__cloudformation__stack__status", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"__aws__expired", "aws", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"__aws__s3tables__table_bucket__create", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, - {"__aws__s3tables__table_bucket__destroy", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, - {"__aws__s3tables__table_bucket__list", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, - {"__aws__s3tables__table_bucket__resolve", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, - {"__aws__s3tables__table_bucket__status", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3__bucket__create", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3__bucket__destroy", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3__bucket__list", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3__bucket__status", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3tables__bucket__create", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3tables__bucket__destroy", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3tables__bucket__list", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3tables__bucket__resolve", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__s3tables__bucket__status", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__system_table__create", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__system_table__destroy", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__system_table__list", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"__aws__system_table__status", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"__internal_json_copy_to_geojson", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, {"__internal_json_copy_to_json", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, {"abs", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, @@ -121,6 +129,9 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"atanh", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"avg", "core_functions", CatalogType::AGGREGATE_FUNCTION_ENTRY}, {"avro_metadata", "avro", CatalogType::TABLE_FUNCTION_ENTRY}, + {"aws_system_table", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"aws_system_table_families", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"aws_system_tables", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"bar", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"base64", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"bin", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, @@ -663,12 +674,22 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"rtree_index_dump", "spatial", CatalogType::TABLE_FUNCTION_ENTRY}, {"rtree_index_scan", "spatial", CatalogType::TABLE_FUNCTION_ENTRY}, {"rtrim", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, + {"s3_bucket_metadata_configuration", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3_bucket_tags", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3_buckets", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3_create_bucket", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3_create_bucket_metadata_configuration", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3_delete_bucket", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3_delete_bucket_metadata_configuration", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3_get_bucket", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3_update_bucket", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"s3tables_create_table_bucket", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"s3tables_delete_table_bucket", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"s3tables_get_table_bucket", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"s3tables_namespaces", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"s3tables_table_bucket_tags", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"s3tables_table_buckets", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, + {"s3tables_table_metadata_location", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"s3tables_tables", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"scan_data_from_quack_client", "quack", CatalogType::TABLE_FUNCTION_ENTRY}, {"sem", "core_functions", CatalogType::AGGREGATE_FUNCTION_ENTRY}, @@ -1497,8 +1518,10 @@ static constexpr ExtensionEntry EXTENSION_SECRET_TYPES[] = { // Resource types registered by extensions: CREATE/REGISTER EXTERNAL RESOURCE '' autoloads the extension static constexpr ExtensionEntry EXTENSION_EXTERNAL_RESOURCE_TYPES[] = { - {"aws:cloudformation:quack-on-ec2", "aws"}, - {"aws:s3tables:table-bucket", "aws"}, + {"aws.cloudformation.stack", "aws"}, + {"aws.s3.bucket", "aws"}, + {"aws.s3tables.bucket", "aws"}, + {"aws.system-table", "aws"}, }; // END_OF_EXTENSION_EXTERNAL_RESOURCE_TYPES // Note: these are currently hardcoded in scripts/generate_extensions_function.py diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp index ded98e6a8..2ec6cde9e 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_combiner.hpp @@ -20,6 +20,7 @@ #include namespace duckdb { +class BoundColumnRefExpression; class LogicalGet; class Optimizer; @@ -57,10 +58,12 @@ class FilterCombiner { static bool CanCopyFilter(const Expression &filter); //! A safe predicate with the same truth value for keys equal under NOT DISTINCT FROM. static bool IsKeyConstraint(const Expression &filter, const vector> &keys); - //! Derive a linear set of visible equalities and key constraints, retaining the source filters. - static void GenerateProjectionFilters(ClientContext &context, const vector> &filters, - const std::function &can_project, - const std::function)> &callback); + //! Append a linear set of equalities and key constraints in projection output bindings. + //! lookup_output maps an exact input expression to an existing output column; source filters are retained. + static void GenerateProjectionFilters( + ClientContext &context, const vector> &filters, + const std::function(const Expression &)> &lookup_output, + vector> &result); //! Remove exact duplicate, non-throwing, non-volatile predicates. static void DeduplicateFilters(vector> &filters); void GenerateEquivalentFilters(const Expression &filter, @@ -80,6 +83,7 @@ class FilterCombiner { FilterPushdownResult TryPushdownGenericExpression(LogicalGet &get, Expression &expr); private: + void AddProjectionEqualities(const vector> &filters); void GenerateEquivalentKeyFilters(const Expression &filter, const std::function filter)> &callback); FilterResult AddFilter(Expression &expr); diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp index d000af06b..7e90a1f6d 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp @@ -18,6 +18,7 @@ namespace duckdb { class FilterInfo; class JoinPredicateModel; +enum class JoinSelectivityModel; struct CardinalityEstimatorState; struct FilterInfoWithTotalDomains; struct SelectivitySubgraph; @@ -56,6 +57,7 @@ class CardinalityEstimator { CardinalityValue GetInnerSelectivity(JoinRelationSet &set); CardinalityValue GetJoinSelectivity(JoinRelationSet &set, JoinRelationSet &left, JoinRelationSet &right); CardinalityValue GetSelectivity(JoinRelationSet &set); + JoinSelectivityModel ChooseSelectivityModel(); void ProcessSelectivityEdge(FilterInfoWithTotalDomains &edge, JoinRelationSet &requested_set, SelectivityState &state); void CreateSelectivitySubgraph(FilterInfoWithTotalDomains &edge, JoinRelationSet &edge_left_set, diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index a39052d96..1c3af0dd7 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -1744,9 +1744,78 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_data_source_set_user_data) (duckdb_v2_data_source_handle source, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_create) + (duckdb_v2_factory_handle factory, duckdb_v2_operator_handle *op, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_operator_destroy)(duckdb_v2_operator_handle *op); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_bind_data) + (duckdb_v2_operator_execute_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_global_state) + (duckdb_v2_operator_execute_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_input_chunk) + (duckdb_v2_operator_execute_info_handle info, duckdb_v2_data_chunk_handle *chunk, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_local_state) + (duckdb_v2_operator_execute_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_output_chunk) + (duckdb_v2_operator_execute_info_handle info, duckdb_v2_data_chunk_handle *chunk, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_get_user_data) + (duckdb_v2_operator_execute_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_execute_set_result) + (duckdb_v2_operator_execute_info_handle info, DUCKDB_V2_OPERATOR_RESULT result, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_get_bind_data) + (duckdb_v2_operator_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_get_global_state) + (duckdb_v2_operator_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_get_local_state) + (duckdb_v2_operator_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_get_output_chunk) + (duckdb_v2_operator_finalize_info_handle info, duckdb_v2_data_chunk_handle *chunk, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_get_user_data) + (duckdb_v2_operator_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_finalize_set_have_more_output) + (duckdb_v2_operator_finalize_info_handle info, bool have_more_output, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_global_get_bind_data) + (duckdb_v2_operator_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_global_get_user_data) + (duckdb_v2_operator_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_global_set_global_state) + (duckdb_v2_operator_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_global_set_max_threads) + (duckdb_v2_operator_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_local_get_bind_data) + (duckdb_v2_operator_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_local_get_global_state) + (duckdb_v2_operator_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_local_get_user_data) + (duckdb_v2_operator_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_init_local_set_local_state) + (duckdb_v2_operator_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_set_execute_callback) + (duckdb_v2_operator_handle op, duckdb_v2_operator_execute_callback_fn callback, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_set_finalize_callback) + (duckdb_v2_operator_handle op, duckdb_v2_operator_finalize_callback_fn callback, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_set_init_global_callback) + (duckdb_v2_operator_handle op, duckdb_v2_operator_init_global_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_set_init_local_callback) + (duckdb_v2_operator_handle op, duckdb_v2_operator_init_local_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_operator_set_user_data) + (duckdb_v2_operator_handle op, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_get_input_column_count) + (duckdb_v2_table_function_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_get_input_column_name) + (duckdb_v2_table_function_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_bind_get_input_column_type) + (duckdb_v2_table_function_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_data_source) (duckdb_v2_table_function_handle function, duckdb_v2_data_source_handle data_source, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_operator) + (duckdb_v2_table_function_handle function, duckdb_v2_operator_handle op, DUCKDB_V2_TABLE_OPERATOR_INPUT input, + 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_V2_ERROR(*duckdb_v2_copy_from_set_data_source) @@ -1754,6 +1823,9 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_create_in_transaction) (duckdb_v2_context_handle ctx, duckdb_v2_connection_handle *out_conn, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_property) + (duckdb_v2_table_function_handle function, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, duckdb_v2_error_info_handle *err); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -3969,15 +4041,117 @@ typedef struct { #define duckdb_v2_data_source_set_user_data duckdb_ext_api.duckdb_v2_data_source_set_user_data #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_create duckdb_ext_api.duckdb_v2_operator_create +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_destroy duckdb_ext_api.duckdb_v2_operator_destroy +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_execute_get_bind_data duckdb_ext_api.duckdb_v2_operator_execute_get_bind_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_execute_get_global_state duckdb_ext_api.duckdb_v2_operator_execute_get_global_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_execute_get_input_chunk duckdb_ext_api.duckdb_v2_operator_execute_get_input_chunk +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_execute_get_local_state duckdb_ext_api.duckdb_v2_operator_execute_get_local_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_execute_get_output_chunk duckdb_ext_api.duckdb_v2_operator_execute_get_output_chunk +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_execute_get_user_data duckdb_ext_api.duckdb_v2_operator_execute_get_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_execute_set_result duckdb_ext_api.duckdb_v2_operator_execute_set_result +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_finalize_get_bind_data duckdb_ext_api.duckdb_v2_operator_finalize_get_bind_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_finalize_get_global_state duckdb_ext_api.duckdb_v2_operator_finalize_get_global_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_finalize_get_local_state duckdb_ext_api.duckdb_v2_operator_finalize_get_local_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_finalize_get_output_chunk duckdb_ext_api.duckdb_v2_operator_finalize_get_output_chunk +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_finalize_get_user_data duckdb_ext_api.duckdb_v2_operator_finalize_get_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_finalize_set_have_more_output duckdb_ext_api.duckdb_v2_operator_finalize_set_have_more_output +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_init_global_get_bind_data duckdb_ext_api.duckdb_v2_operator_init_global_get_bind_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_init_global_get_user_data duckdb_ext_api.duckdb_v2_operator_init_global_get_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_init_global_set_global_state duckdb_ext_api.duckdb_v2_operator_init_global_set_global_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_init_global_set_max_threads duckdb_ext_api.duckdb_v2_operator_init_global_set_max_threads +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_init_local_get_bind_data duckdb_ext_api.duckdb_v2_operator_init_local_get_bind_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_init_local_get_global_state duckdb_ext_api.duckdb_v2_operator_init_local_get_global_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_init_local_get_user_data duckdb_ext_api.duckdb_v2_operator_init_local_get_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_init_local_set_local_state duckdb_ext_api.duckdb_v2_operator_init_local_set_local_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_set_execute_callback duckdb_ext_api.duckdb_v2_operator_set_execute_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_set_finalize_callback duckdb_ext_api.duckdb_v2_operator_set_finalize_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_set_init_global_callback duckdb_ext_api.duckdb_v2_operator_set_init_global_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_set_init_local_callback duckdb_ext_api.duckdb_v2_operator_set_init_local_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_operator_set_user_data duckdb_ext_api.duckdb_v2_operator_set_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_bind_get_input_column_count \ + duckdb_ext_api.duckdb_v2_table_function_bind_get_input_column_count +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_bind_get_input_column_name \ + duckdb_ext_api.duckdb_v2_table_function_bind_get_input_column_name +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_bind_get_input_column_type \ + duckdb_ext_api.duckdb_v2_table_function_bind_get_input_column_type +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_set_data_source duckdb_ext_api.duckdb_v2_table_function_set_data_source #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_set_operator duckdb_ext_api.duckdb_v2_table_function_set_operator +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_value_variant_to_value duckdb_ext_api.duckdb_v2_value_variant_to_value #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_copy_from_set_data_source duckdb_ext_api.duckdb_v2_copy_from_set_data_source #define duckdb_v2_connection_create_in_transaction duckdb_ext_api.duckdb_v2_connection_create_in_transaction #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_set_property duckdb_ext_api.duckdb_v2_table_function_set_property +#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 675c77488..256899246 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -646,10 +646,11 @@ typedef enum DUCKDB_V2_ERROR { /* --- Enums for function properties --- */ /*! - * Identifies a configurable function property. Pass one of these to `duckdb_v2_scalar_function_set_property()` or - * `duckdb_v2_aggregate_function_set_property()` together with a matching `DUCKDB_V2_FUNCTION_PROPERTY_VALUE`. The high - * byte is the function-type group: COMMON (`0x01xxxx`) keys apply to all function types, while group-specific keys - * (e.g. aggregate `0x03xxxx`) are only valid for that function type and are rejected with an error otherwise. + * Identifies a configurable function property. Pass one of these to `duckdb_v2_scalar_function_set_property()`, + * `duckdb_v2_aggregate_function_set_property()` or `duckdb_v2_table_function_set_property()` together with a matching + * `DUCKDB_V2_FUNCTION_PROPERTY_VALUE`. The high byte is the function-type group: COMMON (`0x01xxxx`) keys apply to all + * function types, while group-specific keys (e.g. aggregate `0x03xxxx`) are only valid for that function type and are + * rejected with an error otherwise. */ typedef enum DUCKDB_V2_FUNCTION_PROPERTY_KEY { /*! @@ -1972,7 +1973,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_create(duckdb_v2_instance_hand * Lets a callback run SQL inside the transaction it is called in, such as a table function's bind callback reading a * table. The connection sees everything the context's transaction sees, including its uncommitted changes and the * context's temporary objects, and what it changes is part of that transaction. A statement of the connection that - * fails invalidates the transaction as a failure of the context's own statement would. + * fails invalidates the transaction as a failure of the context's own statement would. It starts with the context's + * search path (`USE`, `SET schema`, `SET search_path`), so unqualified names resolve as they do in the context's own + * statements. * * The connection cannot start, commit or roll back a transaction: those statements fail with * ERROR_DATABASE_TRANSACTION, and like any failing statement invalidate the transaction. The connection stays in the @@ -5212,6 +5215,662 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_object_cache_entry_destroy(duckdb_v2_obje /* --- Struct definitions for object cache --- */ +/* ============================================================================ + * MODULE: operator + * ============================================================================ */ + +/* --- Enums for operator --- */ + +/*! + * What an operator's execute callback reports about the input chunk it was given, set with + * `duckdb_v2_operator_execute_set_result()`. + */ +typedef enum DUCKDB_V2_OPERATOR_RESULT { + /*! + * The operator is done with the input chunk: the engine calls the execute callback again with the next input chunk. + * The default. + */ + DUCKDB_V2_OPERATOR_RESULT_NEED_MORE_INPUT = 0, + + /*! + * The output chunk is full but the operator is not done with the input chunk: the engine calls the execute callback + * again with the same input chunk once it has consumed the output. + */ + DUCKDB_V2_OPERATOR_RESULT_HAVE_MORE_OUTPUT = 1, + + /*! + * The operator needs no more input at all, e.g. because it has produced every row it ever will. The engine stops + * feeding it input, and calls the finalize callback if one is set. + */ + DUCKDB_V2_OPERATOR_RESULT_FINISHED = 2, + DUCKDB_V2_OPERATOR_RESULT_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_OPERATOR_RESULT; + +/* --- Struct forward declarations for operator --- */ + +/* --- Types for operator --- */ + +/*! + * An owned opaque handle to a custom streaming operator being built. Created with `duckdb_v2_operator_create()`, + * configured with the setter functions (e.g. `duckdb_v2_operator_set_execute_callback()`), handed to the object that + * runs it (e.g. with `duckdb_v2_table_function_set_operator()`), and destroyed with `duckdb_v2_operator_destroy()`. + * + * An operator transforms a stream of input chunks into a stream of output chunks. The engine may run it on several + * threads at once: every thread processes a part of the input with a "local state" of its own, next to a "global state" + * all threads share. + */ +typedef struct _duckdb_v2_operator { + void *internal_ptr; +} * duckdb_v2_operator_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an operator during the global state initialization "init + * global" phase. The "init global" callback receives this handle and can use it to set up the state shared by every + * thread running the operator, and to declare how many threads may run it. + */ +typedef struct _duckdb_v2_operator_init_global_info { + void *internal_ptr; +} * duckdb_v2_operator_init_global_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an operator during the local state initialization "init local" + * phase. The "init local" callback receives this handle and can use it to set up the state of one thread running the + * operator. + */ +typedef struct _duckdb_v2_operator_init_local_info { + void *internal_ptr; +} * duckdb_v2_operator_init_local_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an operator during the "execute" phase. The "execute" callback + * receives this handle and uses it to read the input chunk, write the output chunk, and report whether it is done with + * the input chunk. + */ +typedef struct _duckdb_v2_operator_execute_info { + void *internal_ptr; +} * duckdb_v2_operator_execute_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an operator during the "finalize" phase, after the thread's + * input is exhausted. The "finalize" callback receives this handle and uses it to write the output the operator held + * back, and to report whether it has more of it. + */ +typedef struct _duckdb_v2_operator_finalize_info { + void *internal_ptr; +} * duckdb_v2_operator_finalize_info_handle; + +/* --- Constants for operator --- */ + +/* --- Function pointer typedefs for operator --- */ + +typedef void (*duckdb_v2_operator_init_global_callback_fn)(duckdb_v2_operator_init_global_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_operator_init_local_callback_fn)(duckdb_v2_operator_init_local_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_operator_execute_callback_fn)(duckdb_v2_operator_execute_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_operator_finalize_callback_fn)(duckdb_v2_operator_finalize_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +/* --- Functions for operator --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a new operator through a factory. + * + * The operator starts out empty: configure it with the setter functions (e.g. + * `duckdb_v2_operator_set_execute_callback()`), then hand it to the object that runs it, e.g. with + * `duckdb_v2_table_function_set_operator()`. The caller owns the returned handle and must destroy it with + * `duckdb_v2_operator_destroy()`, also after handing it over. + * + * The operator can only be handed to objects created through a factory of the same database. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to create the operator through. + * @param op On success, receives the newly created operator. Owned by the caller. + * @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_operator_create(duckdb_v2_factory_handle factory, duckdb_v2_operator_handle *op, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets arbitrary user data on the operator. + * + * Associates an opaque pointer with the operator, retrievable from its callbacks via e.g. + * `duckdb_v2_operator_execute_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, + * invoked when the data is no longer needed. Calling this again replaces the previous user data. + * + * history: + * - unstable: v2.0.0 + * + * @param op The operator to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @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_operator_set_user_data(duckdb_v2_operator_handle op, duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the optional global init callback of the operator. + * + * The global init callback is invoked once per operator in a query plan, before any input reaches it. It can set + * "global state" shared by every thread running the operator, and declare how many threads may run it via + * `duckdb_v2_operator_init_global_set_max_threads()`. + * + * history: + * - unstable: v2.0.0 + * + * @param op The operator to set the global init callback of. + * @param callback The global init callback to set. + * @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_operator_set_init_global_callback( + duckdb_v2_operator_handle op, duckdb_v2_operator_init_global_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the optional local init callback of the operator. + * + * The local init callback is invoked once per thread that runs the operator, before any input reaches it on that + * thread. It can set worker-local "local state", retrievable from the execute and finalize callbacks. + * + * history: + * - unstable: v2.0.0 + * + * @param op The operator to set the local init callback of. + * @param callback The local init callback to set. + * @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_operator_set_init_local_callback( + duckdb_v2_operator_handle op, duckdb_v2_operator_init_local_callback_fn callback, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the execute callback of the operator. + * + * The execute callback implements the operator's logic. It is invoked with an input chunk and an empty output chunk, + * writes the rows it produces for the input into the output chunk, and reports with + * `duckdb_v2_operator_execute_set_result()` whether it is done with the input chunk. It may produce no rows for an + * input chunk, and it may produce rows for an input chunk over several invocations. An execute callback must be set + * before the operator is handed over. + * + * history: + * - unstable: v2.0.0 + * + * @param op The operator to set the execute callback of. + * @param callback The execute callback to set. + * @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_operator_set_execute_callback(duckdb_v2_operator_handle op, + duckdb_v2_operator_execute_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the optional finalize callback of the operator. + * + * The finalize callback is invoked on every thread running the operator once the thread's input is exhausted, or once + * the execute callback reported `OPERATOR_RESULT_FINISHED`. It writes the output the operator held back, e.g. the rows + * of a buffering operator, and is invoked again for as long as it reports more output with + * `duckdb_v2_operator_finalize_set_have_more_output()`. + * + * Not every way of running an operator supports it: e.g. a table function whose input is correlated with an outer query + * (`LATERAL`) runs the operator once per row of the outer query, and rejects a finalize callback. + * + * history: + * - unstable: v2.0.0 + * + * @param op The operator to set the finalize callback of. + * @param callback The finalize callback to set. + * @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_operator_set_finalize_callback(duckdb_v2_operator_handle op, + duckdb_v2_operator_finalize_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the user data set via `duckdb_v2_operator_set_user_data()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The global init info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_operator_init_global_get_user_data( + duckdb_v2_operator_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the bind data of the call the operator runs for, e.g. the bind data set by the bind callback of the table + * function the operator was handed to. + * + * history: + * - unstable: v2.0.0 + * + * @param info The global init info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_operator_init_global_get_bind_data( + duckdb_v2_operator_init_global_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the operator's "global state" from the global init callback. + * + * The global state lives as long as the operator runs and is retrievable from the local init, execute and finalize + * callbacks. Every thread running the operator shares it, so the operator must synchronize its own access to it. The + * opaque handle bundles the pointer with an optional destructor, invoked when the operator is done with the state. + * + * history: + * - unstable: v2.0.0 + * + * @param info The global init info handle. + * @param data Opaque handle bundling the global state pointer plus an optional destructor. + * @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_operator_init_global_set_global_state( + duckdb_v2_operator_init_global_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets how many threads may run the operator in parallel. + * + * By default the operator runs on as many threads as the operators feeding it. This sets an upper bound, e.g. 1 for an + * operator that must see its whole input on a single thread; it is not a request, and the engine may use fewer threads. + * Some ways of running an operator always use a single thread: e.g. a table function called with constant arguments. + * + * history: + * - unstable: v2.0.0 + * + * @param info The global init info handle. + * @param max_threads The maximum number of threads. Must be at least 1. + * @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_operator_init_global_set_max_threads( + duckdb_v2_operator_init_global_info_handle info, idx_t max_threads, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the user data set via `duckdb_v2_operator_set_user_data()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The local init info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_operator_init_local_get_user_data(duckdb_v2_operator_init_local_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the bind data of the call the operator runs for (see `duckdb_v2_operator_init_global_get_bind_data()`). + * + * history: + * - unstable: v2.0.0 + * + * @param info The local init info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_operator_init_local_get_bind_data(duckdb_v2_operator_init_local_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the global state set via `duckdb_v2_operator_init_global_set_global_state()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The local init info handle. + * @param data Receives the global state pointer, or null if none was set. + * @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_operator_init_local_get_global_state( + duckdb_v2_operator_init_local_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the "local state" of the thread from the local init callback. + * + * The local state belongs to a single thread running the operator, so the operator need not synchronize access to it; + * it is retrievable from the execute and finalize callbacks on that thread. The opaque handle bundles the pointer with + * an optional destructor, invoked when the thread is done with the state. + * + * history: + * - unstable: v2.0.0 + * + * @param info The local init info handle. + * @param data Opaque handle bundling the local state pointer plus an optional destructor. + * @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_operator_init_local_set_local_state( + duckdb_v2_operator_init_local_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the user data set via `duckdb_v2_operator_set_user_data()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The execute info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_operator_execute_get_user_data(duckdb_v2_operator_execute_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the bind data of the call the operator runs for (see `duckdb_v2_operator_init_global_get_bind_data()`). + * + * history: + * - unstable: v2.0.0 + * + * @param info The execute info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_operator_execute_get_bind_data(duckdb_v2_operator_execute_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the global state set via `duckdb_v2_operator_init_global_set_global_state()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The execute info handle. + * @param data Receives the global state pointer, or null if none was set. + * @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_operator_execute_get_global_state(duckdb_v2_operator_execute_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the local state set via `duckdb_v2_operator_init_local_set_local_state()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The execute info handle. + * @param data Receives the local state pointer, or null if none was set. + * @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_operator_execute_get_local_state(duckdb_v2_operator_execute_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the input chunk the execute callback processes. + * + * Read its row count with `duckdb_v2_data_chunk_get_size()` and its columns with `duckdb_v2_data_chunk_get_vector()`. + * What the columns are depends on the object that runs the operator: for a table function, see + * `duckdb_v2_table_function_set_operator()`. When the previous invocation reported `OPERATOR_RESULT_HAVE_MORE_OUTPUT`, + * this is the same input chunk as before. The vectors may be in any representation, e.g. a range of numbers arrives as + * a sequence: call `duckdb_v2_vector_flatten()` on a vector before reading it through `duckdb_v2_vector_get_view()` if + * needed. Borrowed; other than flattening its vectors, the callback must not modify it. Valid only for the duration of + * the callback. + * + * history: + * - unstable: v2.0.0 + * + * @param info The execute info handle. + * @param chunk Receives the borrowed input chunk. + * @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_operator_execute_get_input_chunk(duckdb_v2_operator_execute_info_handle info, + duckdb_v2_data_chunk_handle *chunk, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the output chunk the execute callback writes the rows it produces into. + * + * The chunk holds one vector per output column of the operator, in order (for a table function: the columns declared + * with `duckdb_v2_table_function_bind_add_result_column()`), and starts out empty on every invocation. Write the rows, + * then declare how many there are with `duckdb_v2_vector_set_size()` on the first vector, which the engine takes as the + * chunk's row count and propagates to the other vectors. The chunk holds at most as many rows as the engine's vector + * size (2048 by default): report `OPERATOR_RESULT_HAVE_MORE_OUTPUT` to produce more rows for the same input. Borrowed; + * valid only for the duration of the callback. + * + * history: + * - unstable: v2.0.0 + * + * @param info The execute info handle. + * @param chunk Receives the borrowed output chunk to write into. + * @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_operator_execute_get_output_chunk(duckdb_v2_operator_execute_info_handle info, + duckdb_v2_data_chunk_handle *chunk, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Reports whether the execute callback is done with the input chunk. Defaults to `OPERATOR_RESULT_NEED_MORE_INPUT`; see + * `DUCKDB_V2_OPERATOR_RESULT` for what each result makes the engine do next. + * + * history: + * - unstable: v2.0.0 + * + * @param info The execute info handle. + * @param result The result of this invocation. + * @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_operator_execute_set_result(duckdb_v2_operator_execute_info_handle info, + DUCKDB_V2_OPERATOR_RESULT result, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the user data set via `duckdb_v2_operator_set_user_data()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The finalize info handle. + * @param data Receives the user data pointer, or null if none was set. + * @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_operator_finalize_get_user_data(duckdb_v2_operator_finalize_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the bind data of the call the operator runs for (see `duckdb_v2_operator_init_global_get_bind_data()`). + * + * history: + * - unstable: v2.0.0 + * + * @param info The finalize info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @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_operator_finalize_get_bind_data(duckdb_v2_operator_finalize_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the global state set via `duckdb_v2_operator_init_global_set_global_state()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The finalize info handle. + * @param data Receives the global state pointer, or null if none was set. + * @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_operator_finalize_get_global_state(duckdb_v2_operator_finalize_info_handle info, + void **data, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the local state set via `duckdb_v2_operator_init_local_set_local_state()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The finalize info handle. + * @param data Receives the local state pointer, or null if none was set. + * @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_operator_finalize_get_local_state(duckdb_v2_operator_finalize_info_handle info, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the output chunk the finalize callback writes the rows it produces into. It is laid out and sized like the + * output chunk of the execute callback (see `duckdb_v2_operator_execute_get_output_chunk()`). Borrowed; valid only for + * the duration of the callback. + * + * history: + * - unstable: v2.0.0 + * + * @param info The finalize info handle. + * @param chunk Receives the borrowed output chunk to write into. + * @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_operator_finalize_get_output_chunk(duckdb_v2_operator_finalize_info_handle info, + duckdb_v2_data_chunk_handle *chunk, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Reports whether the finalize callback has more output after this invocation. Defaults to false: the operator is done + * on this thread. With true, the engine calls the finalize callback again once it has consumed the output. + * + * history: + * - unstable: v2.0.0 + * + * @param info The finalize info handle. + * @param have_more_output Whether the callback has more output. + * @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_operator_finalize_set_have_more_output( + duckdb_v2_operator_finalize_info_handle info, bool have_more_output, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Destroys the operator, releasing its resources. + * + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after handing it over (e.g. with `duckdb_v2_table_function_set_operator()`) + * does not affect the object it was handed to. + * + * history: + * - unstable: v2.0.0 + * + * @param op The operator to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_operator_destroy(duckdb_v2_operator_handle *op); +#endif + +/* --- Struct definitions for operator --- */ + /* ============================================================================ * MODULE: qname * ============================================================================ */ @@ -13369,6 +14028,29 @@ typedef enum DUCKDB_V2_TABLE_VIRTUAL_COLUMN { DUCKDB_V2_TABLE_VIRTUAL_COLUMN_MAX_ENUM = 0x7FFFFFFF, } DUCKDB_V2_TABLE_VIRTUAL_COLUMN; +/*! + * Where the input of a table function's operator comes from: what the rows of the input chunks the operator receives + * are. Chosen with `duckdb_v2_table_function_set_operator()`. + */ +typedef enum DUCKDB_V2_TABLE_OPERATOR_INPUT { + /*! + * The positional arguments of a call of the function are the columns of the operator's input, one row per set of + * arguments. Called with constant arguments, e.g. `f(1, 'a')`, the operator receives a single input row. Called + * with arguments that reference the columns of a table that precedes the call in the `FROM` clause, e.g. `FROM t, + * f(t.x)` (an implicit `LATERAL` join), it receives one input row per row of that table, one at a time, and every + * row it produces is joined to the row of `t` it was produced for. + */ + DUCKDB_V2_TABLE_OPERATOR_INPUT_ARGUMENTS = 0, + + /*! + * The function takes a table as its first argument, written as a subquery, e.g. `f((SELECT * FROM t))`, and the + * operator receives the rows of that table as its input, chunk by chunk, possibly on several threads. The columns + * of its input are the columns of the table. + */ + DUCKDB_V2_TABLE_OPERATOR_INPUT_TABLE = 1, + DUCKDB_V2_TABLE_OPERATOR_INPUT_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_TABLE_OPERATOR_INPUT; + /* --- Struct forward declarations for table --- */ /* --- Types for table --- */ @@ -13577,6 +14259,32 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_signature(duckdb_v2_ta duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets a property on the table function. + * + * Only `FUNCTION_PROPERTY_STABILITY` is supported for table functions; any other key, a key that is not valid for table + * functions, or a value that does not belong to `key` results in an error. A table function defaults to + * `FUNCTION_PROPERTY_STABILITY_VOLATILE`. Declaring `FUNCTION_PROPERTY_STABILITY_CONSISTENT_WITHIN_QUERY` promises that + * repeated executions with the same bound data and input rows return equivalent rows within one query and have no + * observable side effects, which allows the optimizer to share identical scans. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the property of. + * @param key The property to set. + * @param value The value to set for the property. Must belong to `key`. + * @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_table_function_set_property(duckdb_v2_table_function_handle function, + DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Sets arbitrary user data on the table function. @@ -14080,6 +14788,78 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_set_partition duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the number of columns of the input of the function's operator (see + * `duckdb_v2_table_function_set_operator()`). + * + * These are the vectors of the input chunks the operator's execute callback receives: the positional arguments of the + * call for `TABLE_OPERATOR_INPUT_ARGUMENTS`, or the columns of the table argument for `TABLE_OPERATOR_INPUT_TABLE`. A + * bind callback typically derives the function's result columns from them. Unlike + * `duckdb_v2_function_bind_get_arg_value()`, this also describes arguments that are not constant. 0 for a function + * without an operator. + * + * history: + * - unstable: v2.0.0 + * + * @param info The bind info handle. + * @param count Receives the number of input columns. + * @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_table_function_bind_get_input_column_count( + duckdb_v2_table_function_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the type of the operator's input column at the given index (see + * `duckdb_v2_table_function_bind_get_input_column_count()`). + * + * Fails if the index is out of bounds. The returned type is owned by the caller and must be destroyed via + * `duckdb_v2_logical_type_destroy()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The bind info handle. + * @param index The index of the input column. + * @param type Receives the column type. Owned by the caller; destroy via `duckdb_v2_logical_type_destroy()`. + * @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_table_function_bind_get_input_column_type( + duckdb_v2_table_function_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the name of the operator's input column at the given index (see + * `duckdb_v2_table_function_bind_get_input_column_count()`). + * + * For `TABLE_OPERATOR_INPUT_TABLE` this is the name of the column of the table argument. The arguments of + * `TABLE_OPERATOR_INPUT_ARGUMENTS` have no names, and yield an empty name. Fails if the index is out of bounds. The + * name is borrowed and valid only for the duration of the callback. + * + * history: + * - unstable: v2.0.0 + * + * @param info The bind info handle. + * @param index The index of the input column. + * @param name Receives a borrowed pointer to the column name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. + * @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_table_function_bind_get_input_column_name( + duckdb_v2_table_function_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. @@ -14166,11 +14946,11 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_result_stats( * * The function is registered on the connection's database, visible to every connection, in the connection's * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. Registration requires a name, a bind callback and an exec callback, and rejects a signature - * that declares a return type, since a table function declares the columns it returns from its bind callback. The table - * function must have been created through a factory of the same database. The caller still owns the handle after - * registration and must destroy it with `duckdb_v2_table_function_destroy()`, which does not affect the registered - * function. + * a rollback undoes it. Registration requires a name, a bind callback and either a data source or an operator (see + * `duckdb_v2_table_function_set_operator()`), and rejects a signature that declares a return type, since a table + * function declares the columns it returns from its bind callback. The table function must have been created through a + * factory of the same database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_table_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 @@ -14191,11 +14971,11 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_table_function(duckdb * Registers the table function, making it available for use in SQL queries. * * The function is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. Registration requires a name, a bind callback and an exec callback, and rejects a - * signature that declares a return type, since a table function declares the columns it returns from its bind callback. - * The table function must have been created through a factory of the same database. The caller still owns the handle - * after registration and must destroy it with `duckdb_v2_table_function_destroy()`, which does not affect the - * registered function. + * extension's load callback. Registration requires a name, a bind callback and either a data source or an operator (see + * `duckdb_v2_table_function_set_operator()`), and rejects a signature that declares a return type, since a table + * function declares the columns it returns from its bind callback. The table function must have been created through a + * factory of the same database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_table_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 @@ -14435,6 +15215,45 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_set(duckdb_v2_ta duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Makes the table function a table in-out function, whose rows the given operator produces from an input. + * + * Instead of producing its rows from nothing by scanning a data source, the function then transforms an input into its + * rows: the operator's execute callback receives the input chunk by chunk, and writes the function's rows into its + * output chunk, which holds the columns declared by the bind callback. Where the input comes from is set by `input`, + * see `DUCKDB_V2_TABLE_OPERATOR_INPUT`. The bind callback still runs first, declares the result columns, and can + * inspect the input columns with `duckdb_v2_table_function_bind_get_input_column_count()` and its siblings; the + * operator reaches the bind data via e.g. `duckdb_v2_operator_execute_get_bind_data()`. + * + * The operator's configuration is copied, so the caller still owns `op` and must destroy it with + * `duckdb_v2_operator_destroy()`; it may be handed to several functions. Calling this again replaces the operator. + * + * Registration rejects a function with an operator that also has a data source, or a callback that is part of scanning: + * init global, init local, progress, metrics, filter pushdown, partition data, partitioning and claim batch callbacks, + * projection pushdown and virtual columns. The operator itself carries the init and finalize callbacks. For + * `TABLE_OPERATOR_INPUT_TABLE`, the signature must not declare positional parameters, since the table is the only + * positional argument; registration adds it. It may declare named parameters, which are constant arguments of the call + * as usual. Such a function cannot be overloaded, and its operator cannot have a finalize callback when it is called + * with a table that is correlated with an outer query. For `TABLE_OPERATOR_INPUT_ARGUMENTS`, the operator cannot have a + * finalize callback. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the operator of. + * @param op The operator producing the function's rows. Borrowed; its configuration is copied. + * @param input Where the operator's input comes from. + * @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_table_function_set_operator(duckdb_v2_table_function_handle function, + duckdb_v2_operator_handle op, + DUCKDB_V2_TABLE_OPERATOR_INPUT input, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Creates a new multi-file function through a factory. diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func.cpp index e0aecec15..d21e156ce 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func.cpp @@ -36,14 +36,21 @@ CV2ConstantBindInfo::CV2ConstantBindInfo(const BoundSimpleFunction &function, co void *user_data, const vector &positional, const named_argument_map_t &named) : CV2FunctionBindInfo(function, signature, user_data), positional(positional), named(named) { - D_ASSERT(function.GetPositionalArgumentCount() == positional.size()); + // a table in-out function that takes its input from its arguments receives them as input rows, not here + D_ASSERT(positional.empty() || function.GetPositionalArgumentCount() == positional.size()); } const Value &CV2ConstantBindInfo::GetArg(idx_t index) const { - if (index < positional.size()) { + const auto positional_count = function.GetPositionalArgumentCount(); + if (index < positional_count) { + if (index >= positional.size()) { + throw InvalidInputException( + "Argument %llu of %s is an input row of the function, it has no value when the function is bound", + index, function.GetName().GetIdentifierName()); + } return positional[index]; } - const auto &name = function.GetNamedArguments()[index - positional.size()]; + const auto &name = function.GetNamedArguments()[index - positional_count]; auto entry = named.find(name); if (entry == named.end()) { throw InternalException("Named argument %s of a function call has no value", name); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_properties.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_properties.cpp index 1319a2ad1..de505c5b7 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_properties.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_properties.cpp @@ -150,6 +150,17 @@ void SetScalarFunctionProperty(FunctionProperties &props, DUCKDB_V2_FUNCTION_PRO SetCommonProperty(props, key, value); } +void SetTableFunctionProperty(FunctionStability &stability, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value) { + ValidateValueMatchesKey(key, value); + if (key != DUCKDB_V2_FUNCTION_PROPERTY_STABILITY) { + throw InvalidInputException("Function property key " + ToHex(AsU32(key)) + " is not valid for table functions"); + } + FunctionProperties props; + SetCommonProperty(props, key, value); + stability = props.GetStability(); +} + void SetAggregateFunctionProperty(AggregateFunctionProperties &props, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, DUCKDB_V2_FUNCTION_PROPERTY_VALUE value) { ValidateValueMatchesKey(key, value); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp index 7612aeaa9..37a163df3 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp @@ -6,6 +6,7 @@ #include "duckdb/common/multi_file/base_file_reader.hpp" #include "duckdb/common/multi_file/multi_file_data.hpp" #include "duckdb/common/multi_file/multi_file_reader.hpp" +#include "duckdb/main/capi/capi_function_signature.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/operator/logical_get.hpp" @@ -31,6 +32,10 @@ class CV2TableFunctionData final : public CV2DataSourceBindData { vector column_names; + //! For a function with an operator: whether the operator receives its input from a child of the plan, rather than + //! once from the constant arguments of the call + bool streaming_input = false; + auto Copy() const -> unique_ptr override { auto copy = make_uniq(); CopyTo(*copy); @@ -39,12 +44,17 @@ class CV2TableFunctionData final : public CV2DataSourceBindData { copy->cardinality_is_exact = cardinality_is_exact; copy->cardinality_set = cardinality_set; copy->column_names = column_names; + copy->streaming_input = streaming_input; return std::move(copy); } }; class CV2TableBindInfo { public: + //! The columns of the input of the function's operator + optional_ptr> in_input_types; + optional_ptr> in_input_names; + vector out_column_types; vector out_column_names; idx_t out_cardinality = 0; @@ -107,6 +117,10 @@ class CV2TableFunctionInfo : public TableFunctionInfo { CV2ScanOptions scan; //! The data source the function scans with. The bind data of a call refers to it, which the function outlives. CV2DataSourceInfo source; + //! The operator producing the rows of a table in-out function + shared_ptr op; + //! Whether the operator's input is a table argument, rather than the positional arguments + bool table_input = false; Identifier name; }; @@ -204,6 +218,8 @@ static auto CV2TableBind(ClientContext &context, TableFunctionBindInput &input, info.user_data ? info.user_data->GetData() : nullptr, input.inputs, input.named_parameters); CV2TableBindInfo args = {}; + args.in_input_types = &input.input_table_types; + args.in_input_names = &input.input_table_names; CV2ErrorInfo err = {}; auto err_ptr = Convert(&err); @@ -219,6 +235,8 @@ static auto CV2TableBind(ClientContext &context, TableFunctionBindInput &input, result->cardinality = args.out_cardinality; result->cardinality_is_exact = args.out_cardinality_is_exact; result->cardinality_set = args.out_cardinality_set; + // Without a child plan, the scan hands the operator the constant arguments as its only input + result->streaming_input = input.input_plan && *input.input_plan; if (err.HasError()) { err.ThrowAsException(); @@ -239,6 +257,231 @@ static auto CV2TableBind(ClientContext &context, TableFunctionBindInput &input, return std::move(result); } +//---------------------------------------------------------------------------------------------------------------------- +// Operators +//---------------------------------------------------------------------------------------------------------------------- +class CV2OperatorGlobalState final : public GlobalTableFunctionState { +public: + auto MaxThreads() const -> idx_t override { + return max_threads; + } + + CV2UserData handle; + idx_t max_threads = GlobalTableFunctionState::MAX_THREADS; +}; + +class CV2OperatorLocalState final : public LocalTableFunctionState { +public: + CV2UserData handle; + //! Whether the operator is done with the constant arguments the scan keeps handing it + bool arguments_consumed = false; + //! Whether the operator reported that it is finished along with its last rows + bool finished = false; + //! Written into when the engine requests no columns, as the operator produces its rows through its first column + unique_ptr row_chunk; +}; + +static auto CV2OperatorOf(const CV2TableFunctionData &bind_data) -> const CV2OperatorInfo & { + D_ASSERT(bind_data.info && bind_data.info->op); + return *bind_data.info->op; +} + +static auto CV2OperatorInitGlobal(ClientContext &context, TableFunctionInitInput &input) + -> unique_ptr { + const auto &bind_data = input.bind_data->Cast(); + const auto &op = CV2OperatorOf(bind_data); + + auto result = make_uniq(); + if (!bind_data.streaming_input) { + // every thread of the scan would be handed the same arguments + result->max_threads = 1; + } + if (!op.init_global_cb) { + return std::move(result); + } + + CV2OperatorInitGlobalInfo args = {}; + args.in_user_data = op.GetUserData(); + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context); + op.init_global_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (args.out_global_state.ptr) { + result->handle = + CV2UserData(args.out_global_state.ptr, args.out_global_state.destroy, args.out_global_state.equals); + } + if (args.out_max_threads.IsValid() && bind_data.streaming_input) { + result->max_threads = args.out_max_threads.GetIndex(); + } + + // Throw after taking ownership of the state, so that it is destroyed even if we error. + if (err.HasError()) { + err.ThrowAsException(); + } + return std::move(result); +} + +static auto CV2OperatorInitLocal(ExecutionContext &context, TableFunctionInitInput &input, + GlobalTableFunctionState *global_state) -> unique_ptr { + const auto &bind_data = input.bind_data->Cast(); + const auto &op = CV2OperatorOf(bind_data); + + auto result = make_uniq(); + if (!op.init_local_cb) { + return std::move(result); + } + + CV2OperatorInitLocalInfo args = {}; + args.in_user_data = op.GetUserData(); + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + if (global_state) { + args.in_global_state = global_state->Cast().handle.GetData(); + } + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context.client); + op.init_local_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (args.out_local_state.ptr) { + result->handle = + CV2UserData(args.out_local_state.ptr, args.out_local_state.destroy, args.out_local_state.equals); + } + + // Throw after taking ownership of the state, so that it is destroyed even if we error. + if (err.HasError()) { + err.ThrowAsException(); + } + return std::move(result); +} + +//! The chunk the operator writes into: the output chunk, or the local row chunk when the engine requests no columns +static auto CV2OperatorTarget(ClientContext &context, const CV2TableFunctionData &bind_data, + CV2OperatorLocalState &local_state, DataChunk &output) -> DataChunk & { + if (output.ColumnCount() > 0) { + return output; + } + if (!local_state.row_chunk) { + local_state.row_chunk = make_uniq(); + local_state.row_chunk->Initialize(context, {bind_data.column_types[0]}); + } + local_state.row_chunk->Reset(); + return *local_state.row_chunk; +} + +//! Takes the row count of what the operator wrote from its first vector, as the exec callback does +static auto CV2OperatorSetCardinality(const CV2TableFunctionData &bind_data, DataChunk &target, DataChunk &output) + -> void { + auto row_count = target.data[0].size(); + if (row_count > target.GetCapacity()) { + throw InvalidInputException("The operator of table function %s produced %llu rows, more than the %llu rows " + "an output chunk holds.", + bind_data.info->name, row_count, target.GetCapacity()); + } + if (output.ColumnCount() == 0) { + output.SetCardinalityUnsafe(row_count); + return; + } + output.SetChildCardinality(row_count); +} + +static auto CV2OperatorCallExecute(ExecutionContext &context, TableFunctionInput &data, DataChunk &input, + DataChunk &output) -> OperatorResultType { + const auto &bind_data = data.bind_data->Cast(); + const auto &op = CV2OperatorOf(bind_data); + auto &local_state = data.local_state->Cast(); + + CV2OperatorExecuteInfo args = {}; + args.in_user_data = op.GetUserData(); + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + if (data.global_state) { + args.in_global_state = data.global_state->Cast().handle.GetData(); + } + args.in_local_state = local_state.handle.GetData(); + auto &target = CV2OperatorTarget(context.client, bind_data, local_state, output); + args.input = &input; + args.output = ⌖ + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context.client); + op.execute_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (err.HasError()) { + err.ThrowAsException(); + } + CV2OperatorSetCardinality(bind_data, target, output); + return args.out_result; +} + +//! Runs the operator for the in-out function. Called with constant arguments, the table scan hands the operator the +//! same input chunk until it produces no rows, so the operator only sees it until it is done with it. +static auto CV2OperatorExecute(ExecutionContext &context, TableFunctionInput &data, DataChunk &input, DataChunk &output) + -> OperatorResultType { + const auto &bind_data = data.bind_data->Cast(); + auto &local_state = data.local_state->Cast(); + if (bind_data.streaming_input) { + if (local_state.finished) { + return OperatorResultType::FINISHED; + } + auto result = CV2OperatorCallExecute(context, data, input, output); + if (result == OperatorResultType::FINISHED && output.size() > 0) { + // the engine drops the output of an operator that reports it is finished + local_state.finished = true; + return OperatorResultType::HAVE_MORE_OUTPUT; + } + return result; + } + if (input.ColumnCount() == 0) { + // a call without arguments is a single row without columns + input.SetCardinalityUnsafe(1); + } + while (!local_state.arguments_consumed) { + output.Reset(); + auto result = CV2OperatorCallExecute(context, data, input, output); + if (result != OperatorResultType::HAVE_MORE_OUTPUT) { + local_state.arguments_consumed = true; + } + if (output.size() > 0) { + break; + } + context.client.FastInterruptCheck(); + } + return local_state.arguments_consumed ? OperatorResultType::FINISHED : OperatorResultType::HAVE_MORE_OUTPUT; +} + +static auto CV2OperatorFinalize(ExecutionContext &context, TableFunctionInput &data, DataChunk &output) + -> OperatorFinalizeResultType { + const auto &bind_data = data.bind_data->Cast(); + const auto &op = CV2OperatorOf(bind_data); + auto &local_state = data.local_state->Cast(); + + CV2OperatorFinalizeInfo args = {}; + args.in_user_data = op.GetUserData(); + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + if (data.global_state) { + args.in_global_state = data.global_state->Cast().handle.GetData(); + } + args.in_local_state = local_state.handle.GetData(); + auto &target = CV2OperatorTarget(context.client, bind_data, local_state, output); + args.output = ⌖ + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context.client); + op.finalize_cb(Convert(&args), Convert(&callback_context), &err_ptr); + + if (err.HasError()) { + err.ThrowAsException(); + } + CV2OperatorSetCardinality(bind_data, target, output); + return args.out_have_more_output ? OperatorFinalizeResultType::HAVE_MORE_OUTPUT + : OperatorFinalizeResultType::FINISHED; +} + //! An exact estimate also pins the maximum; otherwise only the estimate is known. static auto CV2TableMakeStatistics(idx_t cardinality, bool is_exact) -> unique_ptr { if (is_exact) { @@ -410,11 +653,15 @@ class CV2TableFunction { throw InvalidInputException("A table function signature cannot set a return type."); } - info.source.Verify(); - // The engine calls get_partition_data without a null check once get_partition_info claims partitions. - if (info.partitioning_cb && !info.source.partition_data_cb) { - throw InvalidInputException( - "The data source must have a partition data callback when the partitioning callback is set."); + if (info.op) { + CheckOperator(); + } else { + info.source.Verify(); + // The engine calls get_partition_data without a null check once get_partition_info claims partitions. + if (info.partitioning_cb && !info.source.partition_data_cb) { + throw InvalidInputException( + "The data source must have a partition data callback when the partitioning callback is set."); + } } // Virtual columns are told apart from the declared columns by their place among the columns the scan was asked // for @@ -422,12 +669,21 @@ class CV2TableFunction { throw InvalidInputException( "A table function that produces a virtual column requires projection pushdown."); } - signature.Verify(); + + auto function_signature = BuildSignature(); + function_signature.Verify(); // A table function holds a signature of its own, so the declared one is handed over as-is TableFunction function(name, {}, CV2DataSourceExec, CV2TableBind, CV2DataSourceInitGlobal, CV2DataSourceInitLocal); - function.GetSignature() = signature; + if (info.op) { + function = TableFunction(name, {}, nullptr, CV2TableBind, CV2OperatorInitGlobal, CV2OperatorInitLocal); + function.in_out_function = CV2OperatorExecute; + if (info.op->finalize_cb) { + function.in_out_function_final = CV2OperatorFinalize; + } + } + function.GetSignature() = std::move(function_signature); // Always wired: it serves the estimate a bind callback may set, which is not known at registration. It // reports no estimate when the bind callback sets none. @@ -442,7 +698,9 @@ class CV2TableFunction { if (info.to_string_cb) { function.to_string = CV2TableToString; } - info.source.ConfigureScan(function); + if (!info.op) { + info.source.ConfigureScan(function); + } if (info.scan.filter_pushdown_cb) { function.pushdown_complex_filter = CV2TableFilterPushdown; } @@ -472,6 +730,55 @@ class CV2TableFunction { return function; } +private: + //! The signature of the registered function: the declared one, preceded by the table input of an operator + FunctionSignature BuildSignature() const { + if (!info.op || !info.table_input) { + return signature; + } + // the declared parameters are all named, so the table input goes first + auto result = signature; + CAPIFunctionSignature::AddParameter(result, FunctionParameter(Identifier("input"), LogicalType::TABLE, {}, + FunctionParameterKind::POSITIONAL_ONLY)); + return result; + } + + //! A function with an operator transforms an input instead of scanning: the scanning callbacks do not apply + void CheckOperator() const { + auto reject = [](bool set, const char *what) { + if (set) { + throw InvalidInputException("A table function with an operator cannot have %s.", what); + } + }; + reject(info.source.exec_cb, "an exec callback"); + reject(info.source.init_global_cb, "an init global callback"); + reject(info.source.init_local_cb, "an init local callback"); + reject(info.source.progress_cb, "a progress callback"); + reject(info.source.metrics_cb, "a metrics callback"); + reject(info.scan.filter_pushdown_cb, "a filter pushdown callback"); + reject(info.source.partition_data_cb, "a partition data callback"); + reject(info.partitioning_cb, "a partitioning callback"); + reject(info.source.claim_batch_cb, "a claim batch callback"); + reject(info.scan.projection_pushdown, "projection pushdown"); + reject(info.file_row_number, "virtual columns"); + if (!info.op->execute_cb) { + throw InvalidInputException("Execute callback must be set for the operator of the function."); + } + if (info.table_input) { + for (idx_t i = 0; i < signature.GetParameterCount(); i++) { + auto ¶meter = signature.GetParameter(i); + if (parameter.AcceptsPosition() || parameter.GetKind() == FunctionParameterKind::VAR_POSITIONAL) { + throw InvalidInputException( + "A table function whose operator takes a table input cannot declare positional parameters."); + } + } + } else if (info.op->finalize_cb) { + throw InvalidInputException( + "The operator of a table function that takes its input from its arguments cannot have a finalize " + "callback."); + } + } + public: //! The database it was created for: the only one it can be registered on. DatabaseInstance &db; @@ -539,6 +846,10 @@ class CV2MultiFileFunction { single_file_function); } for (auto &function : overloads->functions) { + if (!function->function) { + // an in-out function transforms an input rather than reading a file + continue; + } auto &signature = function->GetSignature(); if (signature.GetRequiredParameterCount() != 1 || !signature.GetParameter(0).AcceptsPosition()) { continue; @@ -598,6 +909,14 @@ DUCKDB_V2_ERROR duckdb_v2_table_function_set_name(duckdb_v2_table_function_handl err, [&]() { Convert(function)->name = duckdb::Identifier(ConvertIdentifierName(name, name_length)); }); } +DUCKDB_V2_ERROR duckdb_v2_table_function_set_property(duckdb_v2_table_function_handle function, + DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { SetTableFunctionProperty(Convert(function)->stability, key, value); }); +} + DUCKDB_V2_ERROR duckdb_v2_table_function_get_docs(duckdb_v2_table_function_handle function, duckdb_v2_function_docs_handle *docs, duckdb_v2_error_info_handle *err) { @@ -757,6 +1076,45 @@ DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_result_stats(duckdb_v2_table_ return WithErrorHandler(err, [&]() { *stats = Convert(&Convert(info)->result_stats); }); } +DUCKDB_V2_ERROR duckdb_v2_table_function_bind_get_input_column_count(duckdb_v2_table_function_bind_info_handle info, + idx_t *count, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(count); + return WithErrorHandler(err, [&]() { *count = Convert(info)->in_input_types->size(); }); +} + +DUCKDB_V2_ERROR duckdb_v2_table_function_bind_get_input_column_type(duckdb_v2_table_function_bind_info_handle info, + idx_t index, duckdb_v2_logical_type_handle *type, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(type); + *type = nullptr; + return WithErrorHandler(err, [&]() { + const auto &types = *Convert(info)->in_input_types; + if (index >= types.size()) { + throw duckdb::InvalidInputException( + "Index out of bounds in duckdb_v2_table_function_bind_get_input_column_type"); + } + *type = Convert(types[index]); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_table_function_bind_get_input_column_name(duckdb_v2_table_function_bind_info_handle info, + idx_t index, const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(name); + DUCKDB_CHECK_ARG(name_length); + return WithErrorHandler(err, [&]() { + const auto &names = *Convert(info)->in_input_names; + if (index >= names.size()) { + throw duckdb::InvalidInputException( + "Index out of bounds in duckdb_v2_table_function_bind_get_input_column_name"); + } + SetStringOut(name, name_length, names[index]); + }); +} + DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_user_data(duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err) { @@ -885,6 +1243,24 @@ duckdb_v2_table_function_partitioning_set_partition_info(duckdb_v2_table_functio [&]() { Convert(info)->out_partition_info = CV2ConvertPartitionInfo(partition_info); }); } +DUCKDB_V2_ERROR duckdb_v2_table_function_set_operator(duckdb_v2_table_function_handle function, + duckdb_v2_operator_handle op, + DUCKDB_V2_TABLE_OPERATOR_INPUT input, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_ARG(op); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(function); + auto &source = *Convert(op); + CheckRegistrationTarget(source.db, self.db, "operator"); + if (static_cast(input) > DUCKDB_V2_TABLE_OPERATOR_INPUT_TABLE) { + throw duckdb::InvalidInputException("Invalid value in duckdb_v2_table_function_set_operator"); + } + self.info.op = duckdb::make_shared_ptr(source.info); + self.info.table_input = input == DUCKDB_V2_TABLE_OPERATOR_INPUT_TABLE; + }); +} + DUCKDB_V2_ERROR duckdb_v2_connection_register_table_function(duckdb_v2_connection_handle conn, duckdb_v2_table_function_handle function, duckdb_v2_error_info_handle *err) { @@ -894,8 +1270,10 @@ DUCKDB_V2_ERROR duckdb_v2_connection_register_table_function(duckdb_v2_connectio auto &context = *Convert(conn)->context; context.RunFunctionInTransaction([&]() { auto &self = *Convert(function); - auto info = duckdb::CreateTableFunctionInfo(self.Build(*context.db)); - self.docs.AddTo(self.signature, info); + auto function = self.Build(*context.db); + auto signature = function.GetSignature(); + auto info = duckdb::CreateTableFunctionInfo(std::move(function)); + self.docs.AddTo(signature, info); info.on_conflict = duckdb::OnCreateConflict::ALTER_ON_CONFLICT; auto &catalog = duckdb::Catalog::GetSystemCatalog(context); // CreateFunction, unlike CreateTableFunction, adds the overloads to an existing function. @@ -912,8 +1290,10 @@ DUCKDB_V2_ERROR duckdb_v2_extension_register_table_function(duckdb_v2_extension_ return WithErrorHandler(err, [&]() { auto &self = *Convert(function); auto &loader = GetExtensionLoader(extension); - duckdb::CreateTableFunctionInfo info(self.Build(loader.GetDatabaseInstance())); - self.docs.AddTo(self.signature, info); + auto function = self.Build(loader.GetDatabaseInstance()); + auto signature = function.GetSignature(); + duckdb::CreateTableFunctionInfo info(std::move(function)); + self.docs.AddTo(signature, info); info.on_conflict = duckdb::OnCreateConflict::ALTER_ON_CONFLICT; loader.RegisterFunction(std::move(info)); }); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_operator.cpp b/src/duckdb/src/main/capi/v2/capi_v2_operator.cpp new file mode 100644 index 000000000..57ac69718 --- /dev/null +++ b/src/duckdb/src/main/capi/v2/capi_v2_operator.cpp @@ -0,0 +1,243 @@ +#include "duckdb/main/capi_v2/capi_v2_internal.hpp" +#include "duckdb/main/capi_v2/capi_v2_function_internal.hpp" + +namespace duckdb::capiv2 { + +static_assert(static_cast(OperatorResultType::NEED_MORE_INPUT) == DUCKDB_V2_OPERATOR_RESULT_NEED_MORE_INPUT, + "OperatorResultType::NEED_MORE_INPUT mismatch"); +static_assert(static_cast(OperatorResultType::HAVE_MORE_OUTPUT) == DUCKDB_V2_OPERATOR_RESULT_HAVE_MORE_OUTPUT, + "OperatorResultType::HAVE_MORE_OUTPUT mismatch"); +static_assert(static_cast(OperatorResultType::FINISHED) == DUCKDB_V2_OPERATOR_RESULT_FINISHED, + "OperatorResultType::FINISHED mismatch"); + +//! BLOCKED is not part of the C API: it needs the engine's interrupt machinery +static auto CV2ConvertOperatorResult(DUCKDB_V2_OPERATOR_RESULT value) -> OperatorResultType { + if (static_cast(value) > DUCKDB_V2_OPERATOR_RESULT_FINISHED) { + throw InvalidInputException("Invalid value in duckdb_v2_operator_execute_set_result"); + } + return static_cast(value); +} + +} // namespace duckdb::capiv2 + +//---------------------------------------------------------------------------------------------------------------------- +// Public Functions +//---------------------------------------------------------------------------------------------------------------------- + +using namespace duckdb::capiv2; + +DUCKDB_V2_ERROR duckdb_v2_operator_create(duckdb_v2_factory_handle factory, duckdb_v2_operator_handle *op, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(factory); + DUCKDB_CHECK_ARG(op); + *op = nullptr; + return WithErrorHandler(err, [&]() { + auto result = duckdb::make_uniq(Convert(factory)->GetDatabase()); + *op = Convert(result.release()); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_set_user_data(duckdb_v2_operator_handle op, duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(op); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { + Convert(op)->info.user_data = duckdb::make_shared_ptr(data->ptr, data->destroy, data->equals); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_set_init_global_callback(duckdb_v2_operator_handle op, + duckdb_v2_operator_init_global_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(op); + return WithErrorHandler(err, [&]() { Convert(op)->info.init_global_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_set_init_local_callback(duckdb_v2_operator_handle op, + duckdb_v2_operator_init_local_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(op); + return WithErrorHandler(err, [&]() { Convert(op)->info.init_local_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_set_execute_callback(duckdb_v2_operator_handle op, + duckdb_v2_operator_execute_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(op); + return WithErrorHandler(err, [&]() { Convert(op)->info.execute_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_set_finalize_callback(duckdb_v2_operator_handle op, + duckdb_v2_operator_finalize_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(op); + return WithErrorHandler(err, [&]() { Convert(op)->info.finalize_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_init_global_get_user_data(duckdb_v2_operator_init_global_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_init_global_get_bind_data(duckdb_v2_operator_init_global_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_init_global_set_global_state(duckdb_v2_operator_init_global_info_handle info, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { Convert(info)->out_global_state = *data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_init_global_set_max_threads(duckdb_v2_operator_init_global_info_handle info, + idx_t max_threads, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + return WithErrorHandler(err, [&]() { + if (max_threads == 0) { + throw duckdb::InvalidInputException("The maximum number of threads must be at least 1"); + } + Convert(info)->out_max_threads = max_threads; + }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_init_local_get_user_data(duckdb_v2_operator_init_local_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_init_local_get_bind_data(duckdb_v2_operator_init_local_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_init_local_get_global_state(duckdb_v2_operator_init_local_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_init_local_set_local_state(duckdb_v2_operator_init_local_info_handle info, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { Convert(info)->out_local_state = *data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_execute_get_user_data(duckdb_v2_operator_execute_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_execute_get_bind_data(duckdb_v2_operator_execute_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_execute_get_global_state(duckdb_v2_operator_execute_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_execute_get_local_state(duckdb_v2_operator_execute_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_local_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_execute_get_input_chunk(duckdb_v2_operator_execute_info_handle info, + duckdb_v2_data_chunk_handle *chunk, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(chunk); + return WithErrorHandler(err, [&]() { *chunk = Convert(Convert(info)->input.get()); }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_execute_get_output_chunk(duckdb_v2_operator_execute_info_handle info, + duckdb_v2_data_chunk_handle *chunk, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(chunk); + return WithErrorHandler(err, [&]() { *chunk = Convert(Convert(info)->output.get()); }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_execute_set_result(duckdb_v2_operator_execute_info_handle info, + DUCKDB_V2_OPERATOR_RESULT result, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + return WithErrorHandler(err, [&]() { Convert(info)->out_result = CV2ConvertOperatorResult(result); }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_finalize_get_user_data(duckdb_v2_operator_finalize_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_finalize_get_bind_data(duckdb_v2_operator_finalize_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_finalize_get_global_state(duckdb_v2_operator_finalize_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_global_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_finalize_get_local_state(duckdb_v2_operator_finalize_info_handle info, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_local_state; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_finalize_get_output_chunk(duckdb_v2_operator_finalize_info_handle info, + duckdb_v2_data_chunk_handle *chunk, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(chunk); + return WithErrorHandler(err, [&]() { *chunk = Convert(Convert(info)->output.get()); }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_finalize_set_have_more_output(duckdb_v2_operator_finalize_info_handle info, + bool have_more_output, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + return WithErrorHandler(err, [&]() { Convert(info)->out_have_more_output = have_more_output; }); +} + +DUCKDB_V2_ERROR duckdb_v2_operator_destroy(duckdb_v2_operator_handle *op) { + return WithErrorHandler(nullptr, [&]() { + if (!op) { + return; + } + if (*op) { + delete Convert(*op); + *op = nullptr; + } + }); +} diff --git a/src/duckdb/src/main/connection.cpp b/src/duckdb/src/main/connection.cpp index 36dc226e5..a671b995d 100644 --- a/src/duckdb/src/main/connection.cpp +++ b/src/duckdb/src/main/connection.cpp @@ -1,8 +1,10 @@ #include "duckdb/main/connection.hpp" +#include "duckdb/catalog/catalog_search_path.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/main/appender.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/client_data.hpp" #include "duckdb/main/connection_manager.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/query_profiler.hpp" @@ -44,6 +46,10 @@ Connection Connection::CreateInTransaction(ClientContext &context) { new_context.base_context = context.base_context ? context.base_context : context.shared_from_this(); new_context.internal_depth = context.internal_depth + 1; new_context.transaction.InheritTransaction(context); + // names resolve as they do for the context: through the same search path + auto &search_path = *ClientData::Get(context).catalog_search_path; + ClientData::Get(new_context).catalog_search_path = + make_uniq(new_context, search_path.GetSetPaths()); return con; } diff --git a/src/duckdb/src/main/secret/secret.cpp b/src/duckdb/src/main/secret/secret.cpp index a38364347..2bda1d123 100644 --- a/src/duckdb/src/main/secret/secret.cpp +++ b/src/duckdb/src/main/secret/secret.cpp @@ -74,7 +74,9 @@ string KeyValueSecret::ToString(SecretDisplayType mode) const { for (auto it = secret_map.begin(); it != secret_map.end(); it++) { result.append(it->first.GetIdentifierName()); result.append("="); - if (mode == SecretDisplayType::REDACTED && redact_keys.find(it->first) != redact_keys.end()) { + // Refresh metadata can contain credentials even when the stored redaction list omits it. + if (mode == SecretDisplayType::REDACTED && + (it->first == "refresh_info" || redact_keys.find(it->first) != redact_keys.end())) { result.append("redacted"); } else { result.append(it->second.ToString()); diff --git a/src/duckdb/src/optimizer/filter_combiner.cpp b/src/duckdb/src/optimizer/filter_combiner.cpp index 4927d8150..4b652c6ba 100644 --- a/src/duckdb/src/optimizer/filter_combiner.cpp +++ b/src/duckdb/src/optimizer/filter_combiner.cpp @@ -224,12 +224,34 @@ static optional_ptr GetConstraintKey(const Expression &filter) return key; } -void FilterCombiner::GenerateProjectionFilters(ClientContext &context, const vector> &filters, - const std::function &can_project, - const std::function)> &callback) { - FilterCombiner combiner(context); - auto &groups = combiner.equivalence_map; - auto &group_ids = combiner.equivalence_set_map; +static unique_ptr +ProjectConstraintKey(const Expression &key, + const std::function(const Expression &)> &lookup_output) { + bool valid = true; + auto project_column = [&](const BoundColumnRefExpression &column) -> unique_ptr { + auto output = lookup_output(column); + valid &= bool(output); + return std::move(output); + }; + // Preserve the formula when its inputs are available, so enclosing joins can use it. + auto projected = ExpressionIterator::PreorderReplace(key.Copy(), project_column); + if (valid) { + return projected; + } + valid = true; + projected = ExpressionIterator::PreorderReplace(key.Copy(), [&](const Expression &expr) -> unique_ptr { + auto output = lookup_output(expr); + if (!output && expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + valid = false; + } + return std::move(output); + }); + return valid ? std::move(projected) : nullptr; +} + +void FilterCombiner::AddProjectionEqualities(const vector> &filters) { + auto &groups = equivalence_map; + auto &group_ids = equivalence_set_map; for (auto &filter : filters) { if (filter->GetExpressionType() != ExpressionType::COMPARE_EQUAL || !CanCopyFilter(*filter)) { continue; @@ -239,8 +261,8 @@ void FilterCombiner::GenerateProjectionFilters(ClientContext &context, const vec BoundComparisonExpression::Right(comparison).IsScalar()) { continue; } - auto left = combiner.GetEquivalenceSet(combiner.GetNode(*BoundComparisonExpression::LeftMutable(comparison))); - auto right = combiner.GetEquivalenceSet(combiner.GetNode(*BoundComparisonExpression::RightMutable(comparison))); + auto left = GetEquivalenceSet(GetNode(*BoundComparisonExpression::LeftMutable(comparison))); + auto right = GetEquivalenceSet(GetNode(*BoundComparisonExpression::RightMutable(comparison))); if (left == right) { continue; } @@ -254,36 +276,115 @@ void FilterCombiner::GenerateProjectionFilters(ClientContext &context, const vec target.push_back(member); } groups.erase(right); - combiner.constant_values.erase(right); + constant_values.erase(right); } - unordered_map> representatives; +} + +namespace { + +struct ProjectedRepresentative { + unique_ptr key; + unique_ptr input; +}; + +static void AddProjectedKey(unique_ptr key, unique_ptr &representative, + vector> &result) { + if (!key) { + return; + } + if (!representative) { + representative = std::move(key); + } else if (!representative->Equals(*key)) { + // Connect formulas and output columns in one linear equality star. + result.push_back( + BoundComparisonExpression::Create(ExpressionType::COMPARE_EQUAL, representative->Copy(), std::move(key))); + } +} + +static unordered_map +ProjectEquivalenceSets(const map>> &groups, + const std::function(const Expression &)> &lookup_output, + vector> &result) { + unordered_map representatives; for (auto &entry : groups) { + ProjectedRepresentative representative; for (auto &member : entry.second) { - if (!can_project(member)) { - continue; - } - auto representative = representatives.find(entry.first); - if (representative == representatives.end()) { - representatives.emplace(entry.first, member.get()); - } else { - // A star connects the visible members without generating pairs involving hidden keys. - callback(BoundComparisonExpression::Create(ExpressionType::COMPARE_EQUAL, - representative->second.get().Copy(), member.get().Copy())); + auto input = lookup_output(member); + auto key = ProjectConstraintKey(member, lookup_output); + const bool same_output = input && key && input->Equals(*key); + AddProjectedKey(std::move(key), representative.key, result); + if (input) { + if (!same_output) { + AddProjectedKey(input->Copy(), representative.key, result); + } + if (!representative.input) { + representative.input = std::move(input); + } } } + if (representative.key) { + representatives.emplace(entry.first, std::move(representative)); + } } - for (auto &filter : filters) { - auto key = GetConstraintKey(*filter); - if (!key || !IsKeyConstraint(*filter, {*key})) { - continue; + return representatives; +} + +static unique_ptr RewriteProjectionConstraint( + const Expression &filter, const expression_map_t &group_ids, + const unordered_map &representatives, + const std::function(const Expression &)> &lookup_output) { + auto key = GetConstraintKey(filter); + if (!key || !FilterCombiner::IsKeyConstraint(filter, {*key})) { + return nullptr; + } + auto entry = group_ids.find(*key); + if (entry != group_ids.end()) { + auto representative = representatives.find(entry->second); + if (representative != representatives.end()) { + return ExpressionIterator::ReplaceExpression(filter, *key, *representative->second.key); } - auto entry = group_ids.find(*key); - if (entry == group_ids.end()) { - continue; + } + + optional_ptr hidden; + bool valid = true; + auto rewrite_input = [&](const Expression &expr) -> unique_ptr { + auto output = lookup_output(expr); + if (output || expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return std::move(output); + } + auto source = group_ids.find(expr); + if (source == group_ids.end() || !expr.GetReturnType().EqualValuesAreIdentical() || + (hidden && !hidden->Equals(expr))) { + valid = false; + return nullptr; } - auto representative = representatives.find(entry->second); - if (representative != representatives.end() && !key->Equals(representative->second)) { - callback(ExpressionIterator::ReplaceExpression(*filter, *key, representative->second)); + hidden = source->first.get(); + auto representative = representatives.find(source->second); + if (representative == representatives.end() || !representative->second.input) { + valid = false; + return nullptr; + } + // Existing output columns cannot grow expressions through successive projections. + return representative->second.input->Copy(); + }; + auto projected = ExpressionIterator::PreorderReplace(key->Copy(), rewrite_input); + return valid && hidden ? ExpressionIterator::ReplaceExpression(filter, *key, *projected) : nullptr; +} + +} // namespace + +void FilterCombiner::GenerateProjectionFilters( + ClientContext &context, const vector> &filters, + const std::function(const Expression &)> &lookup_output, + vector> &result) { + FilterCombiner combiner(context); + combiner.AddProjectionEqualities(filters); + auto representatives = ProjectEquivalenceSets(combiner.equivalence_map, lookup_output, result); + for (auto &filter : filters) { + auto projected = + RewriteProjectionConstraint(*filter, combiner.equivalence_set_map, representatives, lookup_output); + if (projected) { + result.push_back(std::move(projected)); } } } diff --git a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp index e1de2aaa7..a494b0454 100644 --- a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp +++ b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp @@ -220,6 +220,13 @@ struct ResidualFilterStats { static CardinalityValue GetResidualOnSelectivity(const Expression &expression); +enum class JoinSelectivityModel { + //! Estimate relation subgraphs, retaining composite-key heuristics and unknown-domain fallbacks. + RELATION_GRAPH, + //! Count distinct equality connections using reliable column domains. + INDEPENDENT_EQUALITIES +}; + struct CardinalityEstimatorState { void InitializeEdgeIndex(); bool TryGetCandidateEdges(const JoinRelationSet &set, vector &candidates) const; @@ -238,6 +245,8 @@ struct CardinalityEstimatorState { reference_map_t> projected_columns; vector residual_filters; unordered_set leaf_filters; + //! Select once so every memoized subset of the region uses the same model. + JoinSelectivityModel selectivity_model = JoinSelectivityModel::RELATION_GRAPH; }; CardinalityEstimator::CardinalityEstimator(JoinRelationSetManager &set_manager, @@ -846,29 +855,78 @@ void CardinalityEstimator::MergeDisconnectedSelectivitySubgraphs(SelectivityStat state.subgraphs.push_back(final_subgraph); } -CardinalityValue CardinalityEstimator::GetSelectivity(JoinRelationSet &set) { - SelectivityState selectivity_state(*this); - auto process_edge = [&](FilterInfoWithTotalDomains &edge) { - auto &filter = edge.GetFilter(); - if (edge.GetPredicate().GetJoinType() == JoinType::INNER && filter.left_set != filter.right_set && - IsFilterApplicable(filter, set) && !edge.residual) { - ProcessSelectivityEdge(edge, set, selectivity_state); +JoinSelectivityModel CardinalityEstimator::ChooseSelectivityModel() { + for (auto &edge : state->edges) { + if (edge.GetPredicate().GetJoinType() != JoinType::INNER || edge.residual || + edge.GetFilter().left_set == edge.GetFilter().right_set) { + continue; } - }; - vector candidates; - if (state->TryGetCandidateEdges(set, candidates)) { - for (auto index : candidates) { - process_edge(state->edges[index]); + auto pair = GetEqualityJoinPair(edge, set_manager); + if (!pair || !edge.HasReliableDistinctCount()) { + return JoinSelectivityModel::RELATION_GRAPH; } - } else { - for (auto &edge : state->edges) { - process_edge(edge); + // Marginal distinct counts do not establish independent matching of composite tuples. + if (predicate_model.HasDirectCompositeEquality(*pair)) { + return JoinSelectivityModel::RELATION_GRAPH; } } - MergeDisconnectedSelectivitySubgraphs(selectivity_state); - auto result = - selectivity_state.subgraphs.empty() ? CardinalityValue(1) : selectivity_state.subgraphs[0].selectivity; - return result / CardinalityValue(1.0 + static_cast(selectivity_state.unused_edge_tdoms.size())); + return JoinSelectivityModel::INDEPENDENT_EQUALITIES; +} + +static bool ConnectEquality(JoinEqualityGroups &groups, FilterInfoWithTotalDomains &edge) { + auto &predicate = edge.GetPredicate(); + auto &left = predicate.GetEqualityBinding(true); + auto &right = predicate.GetEqualityBinding(false); + groups.AddEquality(left, left); + groups.AddEquality(right, right); + if (groups.GetGroup(left) == groups.GetGroup(right)) { + return false; + } + groups.AddEquality(left, right); + return true; +} + +CardinalityValue CardinalityEstimator::GetSelectivity(JoinRelationSet &set) { + auto for_each_edge = [&](auto &&callback) { + auto process_edge = [&](FilterInfoWithTotalDomains &edge) { + auto &filter = edge.GetFilter(); + if (edge.GetPredicate().GetJoinType() == JoinType::INNER && filter.left_set != filter.right_set && + IsFilterApplicable(filter, set) && !edge.residual) { + callback(edge); + } + }; + 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); + } + } + }; + switch (state->selectivity_model) { + case JoinSelectivityModel::INDEPENDENT_EQUALITIES: { + JoinEqualityGroups groups; + CardinalityValue selectivity(1); + for_each_edge([&](FilterInfoWithTotalDomains &edge) { + if (ConnectEquality(groups, edge)) { + selectivity = selectivity / GetEffectiveDistinctCount(edge.GetDistinctCount()); + } + }); + return selectivity; + } + case JoinSelectivityModel::RELATION_GRAPH: { + SelectivityState selectivity_state(*this); + for_each_edge([&](FilterInfoWithTotalDomains &edge) { ProcessSelectivityEdge(edge, set, selectivity_state); }); + MergeDisconnectedSelectivitySubgraphs(selectivity_state); + auto result = + selectivity_state.subgraphs.empty() ? CardinalityValue(1) : selectivity_state.subgraphs[0].selectivity; + return result / CardinalityValue(1.0 + static_cast(selectivity_state.unused_edge_tdoms.size())); + } + } + throw InternalException("Unknown join selectivity model"); } CardinalityValue CardinalityEstimator::GetInnerSelectivity(JoinRelationSet &set) { @@ -1375,6 +1433,7 @@ void CardinalityEstimator::Initialize(vector relations, } std::stable_sort(state->edges.begin(), state->edges.end(), SortEdges); state->InitializeEdgeIndex(); + state->selectivity_model = ChooseSelectivityModel(); for (auto &op : operators) { D_ASSERT(op->index == state->operators.size()); state->operators.push_back(*op); diff --git a/src/duckdb/src/optimizer/pullup/pullup_projection.cpp b/src/duckdb/src/optimizer/pullup/pullup_projection.cpp index 7a6a8bcb8..ff4083bf7 100644 --- a/src/duckdb/src/optimizer/pullup/pullup_projection.cpp +++ b/src/duckdb/src/optimizer/pullup/pullup_projection.cpp @@ -23,20 +23,29 @@ static bool CanRewrite(const Expression &expr, const expression_map_t LookupOutput(const Expression &expr, const LogicalProjection &proj, + const expression_map_t &projections) { + auto entry = projections.find(expr); + if (entry == projections.end()) { + return nullptr; + } + const auto binding = ColumnBinding(proj.table_index, entry->second); + if (expr.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { + return unique_ptr_cast( + expr.Cast().WithBinding(binding)); + } + return make_uniq(expr.GetAlias(), expr.GetReturnType(), binding); +} + static unique_ptr RewritePredicate(unique_ptr expr, LogicalProjection &proj, expression_map_t &projections, bool match_computed) { return ExpressionIterator::PreorderReplace(std::move(expr), [&](const Expression &child) -> unique_ptr { if (!match_computed && child.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { return nullptr; } - auto entry = projections.find(child); - if (entry != projections.end()) { - if (child.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { - return child.Cast().WithBinding( - ColumnBinding(proj.table_index, entry->second)); - } - return make_uniq(child.GetAlias(), child.GetReturnType(), - ColumnBinding(proj.table_index, entry->second)); + auto output = LookupOutput(child, proj, projections); + if (output) { + return std::move(output); } if (child.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { return nullptr; @@ -125,8 +134,8 @@ unique_ptr FilterPullup::PullupProjection(unique_ptr derived) { export_filter(*derived); }); + *context, filters_expr_pullup, + [&](const Expression &expr) { return LookupOutput(expr, proj, projections); }, exported); } // Retain the full batch: its predicates can guard fallible operators above this projection. proj.children[0] = GeneratePullupFilter(std::move(proj.children[0]), filters_expr_pullup); diff --git a/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp b/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp index 9094868b6..c57bd5dfb 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp @@ -97,7 +97,7 @@ static TableFunctionBindType GetTableFunctionBindType(TableFunctionCatalogEntry } if (has_table_parameter) { if (table_function.functions.Size() != 1) { - throw InternalException( + throw BinderException( "Function %s has a TABLE parameter, and multiple function overloads - this is not supported", table_function.name); } diff --git a/src/duckdb/src/planner/filter/expression_filter.cpp b/src/duckdb/src/planner/filter/expression_filter.cpp index 1512f4d8b..df1aa24df 100644 --- a/src/duckdb/src/planner/filter/expression_filter.cpp +++ b/src/duckdb/src/planner/filter/expression_filter.cpp @@ -857,6 +857,19 @@ static FilterPropagateResult CheckNotOperatorStatistics(optional_ptrCast().GetValue().IsNull()) { return FilterPropagateResult::FILTER_FALSE_OR_NULL; } + if (children.size() > 2 && ExpressionFilter::IsSimpleFilterColumnRef(*children[0])) { + bool has_null = false; + for (idx_t i = 1; i < children.size(); i++) { + if (children[i]->GetExpressionType() != ExpressionType::VALUE_CONSTANT) { + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } + has_null |= children[i]->Cast().GetValue().IsNull(); + } + if (has_null) { + // A match is false and a non-match is NULL after NOT; neither passes a filter. + return FilterPropagateResult::FILTER_FALSE_OR_NULL; + } + } } auto bool_ref = CheckBoolRefStatistics(child, input_stats, true); if (bool_ref != FilterPropagateResult::NO_PRUNING_POSSIBLE) { diff --git a/src/duckdb/ub_src_main_capi_v2.cpp b/src/duckdb/ub_src_main_capi_v2.cpp index 4081b4153..3e5427e28 100644 --- a/src/duckdb/ub_src_main_capi_v2.cpp +++ b/src/duckdb/ub_src_main_capi_v2.cpp @@ -68,6 +68,8 @@ #include "src/main/capi/v2/capi_v2_object_cache.cpp" +#include "src/main/capi/v2/capi_v2_operator.cpp" + #include "src/main/capi/v2/capi_v2_option.cpp" #include "src/main/capi/v2/capi_v2_prepared_statement.cpp" From 44754acf922de995b4dd1371a4b551e112077226 Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Mon, 30 Nov 2026 04:39:10 +0000 Subject: [PATCH 4/8] Update vendored DuckDB sources to 9345a4d95c1 --- .../extension/json/include/json_reader.hpp | 6 +- src/duckdb/extension/json/json_reader.cpp | 7 +- .../parquet/include/parquet_reader.hpp | 3 + .../parquet/include/parquet_writer.hpp | 1 - .../parquet/include/thrift_tools.hpp | 4 +- .../parquet/include/zstd_file_system.hpp | 2 +- .../parquet/parquet_multi_file_info.cpp | 7 + .../extension/parquet/parquet_reader.cpp | 2 +- .../parquet/read_single_parquet_file.cpp | 1 + .../extension/parquet/zstd_file_system.cpp | 13 +- ...nerated_extension_loader_package_build.cpp | 8 +- .../catalog_entry/duck_table_entry.cpp | 4 +- .../catalog_entry/table_catalog_entry.cpp | 4 +- src/duckdb/src/common/base_file_system.cpp | 209 ++++---- .../src/common/compressed_file_system.cpp | 12 +- src/duckdb/src/common/csv_writer.cpp | 8 +- src/duckdb/src/common/file_buffer.cpp | 8 +- src/duckdb/src/common/file_system.cpp | 73 ++- src/duckdb/src/common/gzip_file_system.cpp | 19 +- src/duckdb/src/common/local_file_system.cpp | 322 ++++++------ src/duckdb/src/common/memory_mapped_file.cpp | 4 +- .../multi_file/table_function_multi_file.cpp | 4 + .../table_function_multi_file_list.cpp | 10 + .../table_function_query_filter.cpp | 304 +++++++++++ src/duckdb/src/common/pipe_file_system.cpp | 6 +- src/duckdb/src/common/query_context.cpp | 17 - src/duckdb/src/common/radix_partitioning.cpp | 2 +- .../serializer/buffered_file_reader.cpp | 4 - .../serializer/buffered_file_writer.cpp | 4 +- .../src/common/serializer/memory_stream.cpp | 4 - .../row/integer_partitioned_tuple_data.cpp | 2 +- .../types/row/partitioned_tuple_data.cpp | 2 +- .../common/types/row/tuple_data_allocator.cpp | 3 +- .../types/row/tuple_data_collection.cpp | 3 +- src/duckdb/src/common/virtual_file_system.cpp | 43 +- .../src/execution/index/fixed_size_buffer.cpp | 5 +- .../buffer_manager/csv_file_handle.cpp | 2 +- .../csv_scanner/encode/csv_encoder.cpp | 2 +- .../persistent/physical_copy_to_file.cpp | 1 - .../operator/persistent/physical_delete.cpp | 2 +- .../operator/persistent/physical_insert.cpp | 2 +- .../operator/persistent/physical_update.cpp | 2 +- src/duckdb/src/function/copy_blob.cpp | 6 +- .../src/function/scalar/system/write_log.cpp | 9 +- .../src/function/table/direct_file_reader.cpp | 2 +- .../table/system/duckdb_extensions.cpp | 3 +- .../table/system/pragma_storage_info.cpp | 2 +- src/duckdb/src/function/table/table_scan.cpp | 6 +- .../function/table/version/pragma_version.cpp | 6 +- .../src/include/duckdb/catalog/catalog.hpp | 2 +- .../catalog_entry/duck_table_entry.hpp | 4 +- .../catalog_entry/table_catalog_entry.hpp | 4 +- .../duckdb/common/base_file_system.hpp | 91 ++-- .../duckdb/common/compressed_file_system.hpp | 10 +- .../src/include/duckdb/common/csv_writer.hpp | 5 +- .../src/include/duckdb/common/file_buffer.hpp | 10 +- .../duckdb/common/file_lookup_info.hpp | 29 ++ .../src/include/duckdb/common/file_opener.hpp | 81 --- .../src/include/duckdb/common/file_system.hpp | 18 +- .../duckdb/common/gzip_file_system.hpp | 2 +- .../duckdb/common/local_file_system.hpp | 50 +- .../common/multi_file/base_file_reader.hpp | 4 + .../common/multi_file/multi_file_function.hpp | 10 +- .../multi_file/table_function_multi_file.hpp | 3 + .../table_function_multi_file_list.hpp | 11 + .../table_function_query_filter.hpp | 70 +++ .../duckdb/common/pipe_file_system.hpp | 4 +- .../include/duckdb/common/query_context.hpp | 48 -- .../duckdb/common/radix_partitioning.hpp | 2 +- .../common/serializer/async_file_writer.hpp | 2 +- .../serializer/buffered_file_reader.hpp | 1 - .../serializer/buffered_file_writer.hpp | 11 +- .../common/serializer/memory_stream.hpp | 1 - .../duckdb/common/serializer/read_stream.hpp | 13 +- .../row/integer_partitioned_tuple_data.hpp | 3 +- .../types/row/partitioned_tuple_data.hpp | 6 +- .../common/types/row/tuple_data_allocator.hpp | 10 +- .../types/row/tuple_data_collection.hpp | 2 +- .../duckdb/common/virtual_file_system.hpp | 15 +- .../operator/csv_scanner/csv_file_handle.hpp | 2 +- .../csv_scanner/encode/csv_encoder.hpp | 2 +- .../duckdb/function/compression_function.hpp | 6 +- .../src/include/duckdb/logging/logger.hpp | 4 +- .../include/duckdb/main/attached_database.hpp | 3 + .../duckdb/main/capi_v2/capi_v2_internal.hpp | 8 +- .../duckdb/main/capi_v2/extension_api_v2.hpp | 70 ++- .../include/duckdb/main/client_context.hpp | 7 +- .../main/client_context_file_opener.hpp | 38 -- .../duckdb/main/client_context_state.hpp | 61 ++- .../src/include/duckdb/main/client_data.hpp | 1 - src/duckdb/src/include/duckdb/main/config.hpp | 16 +- .../src/include/duckdb/main/context.hpp | 10 +- .../src/include/duckdb/main/database.hpp | 12 +- ...le_opener.hpp => database_file_system.hpp} | 52 +- .../duckdb/main/database_path_and_type.hpp | 6 +- .../duckdb/main/extension_install_info.hpp | 4 +- .../main/http/http_transport_manager.hpp | 3 +- .../http/http_transport_manager_state.hpp | 34 ++ .../include/duckdb/main/http/http_util.hpp | 9 +- .../src/include/duckdb/main/secret/secret.hpp | 9 +- .../include/duckdb/storage/block_manager.hpp | 16 +- .../duckdb/storage/buffer/block_handle.hpp | 8 +- .../duckdb/storage/buffer/buffer_pool.hpp | 6 +- .../include/duckdb/storage/buffer_manager.hpp | 14 +- .../duckdb/storage/checkpoint_manager.hpp | 5 +- .../storage/compression/alp/alp_scan.hpp | 2 +- .../storage/compression/alprd/alprd_scan.hpp | 2 +- .../storage/compression/chimp/chimp_scan.hpp | 2 +- .../storage/compression/empty_validity.hpp | 2 +- .../storage/compression/patas/patas_scan.hpp | 2 +- .../storage/compression/roaring/roaring.hpp | 2 +- .../src/include/duckdb/storage/data_table.hpp | 9 +- .../duckdb/storage/database_handle.hpp | 12 +- .../caching_file_system.hpp | 24 +- .../caching_file_system_wrapper.hpp | 55 +- .../storage/in_memory_block_manager.hpp | 8 +- .../include/duckdb/storage/magic_bytes.hpp | 4 +- .../storage/metadata/metadata_manager.hpp | 5 +- .../storage/metadata/metadata_reader.hpp | 4 +- .../duckdb/storage/partial_block_manager.hpp | 9 +- .../storage/single_file_block_manager.hpp | 22 +- .../storage/standard_buffer_manager.hpp | 25 +- .../include/duckdb/storage/storage_info.hpp | 6 +- .../duckdb/storage/storage_manager.hpp | 12 +- .../duckdb/storage/string_uncompressed.hpp | 8 +- .../storage/table/array_column_data.hpp | 4 +- .../duckdb/storage/table/column_data.hpp | 6 +- .../duckdb/storage/table/geo_column_data.hpp | 2 +- .../storage/table/in_memory_checkpoint.hpp | 2 +- .../duckdb/storage/table/list_column_data.hpp | 4 +- .../duckdb/storage/table/row_group.hpp | 2 +- .../storage/table/row_group_collection.hpp | 14 +- .../duckdb/storage/table/scan_state.hpp | 27 +- .../storage/table/standard_column_data.hpp | 4 +- .../storage/table/struct_column_data.hpp | 4 +- .../storage/table/variant_column_data.hpp | 4 +- .../duckdb/storage/temporary_file_manager.hpp | 10 +- .../duckdb/storage/write_ahead_log.hpp | 5 +- .../duckdb/transaction/commit_state.hpp | 4 +- .../duckdb/transaction/local_storage.hpp | 6 +- src/duckdb/src/include/duckdb_extension_v2.h | 104 +++- src/duckdb/src/include/duckdb_v2.h | 483 +++++++++++++++++- src/duckdb/src/logging/log_sink.cpp | 4 +- src/duckdb/src/logging/log_types.cpp | 1 - src/duckdb/src/logging/logger.cpp | 5 - src/duckdb/src/main/attached_database.cpp | 9 +- .../main/capi/v2/capi_v2_context_state.cpp | 318 ++++++++++++ .../src/main/capi/v2/capi_v2_data_source.cpp | 179 ++++++- .../src/main/capi/v2/capi_v2_file_system.cpp | 14 +- .../src/main/capi/v2/capi_v2_instance.cpp | 6 +- src/duckdb/src/main/client_context.cpp | 5 +- .../src/main/client_context_execution.cpp | 24 +- .../src/main/client_context_file_opener.cpp | 89 ---- src/duckdb/src/main/client_data.cpp | 3 +- src/duckdb/src/main/config.cpp | 37 +- src/duckdb/src/main/context.cpp | 34 +- src/duckdb/src/main/database.cpp | 24 +- .../src/main/database_path_and_type.cpp | 6 +- src/duckdb/src/main/db_instance_cache.cpp | 14 +- .../src/main/extension/extension_helper.cpp | 5 +- .../src/main/extension/extension_install.cpp | 2 +- .../extension/extension_install_dynamic.cpp | 39 +- .../src/main/extension/extension_load.cpp | 3 +- .../extension_repository_manager.cpp | 2 +- .../src/main/extension_install_info.cpp | 2 +- .../src/main/http/http_transport_manager.cpp | 31 +- src/duckdb/src/main/http/http_util.cpp | 61 +-- src/duckdb/src/main/secret/secret.cpp | 18 +- src/duckdb/src/main/secret/secret_manager.cpp | 4 +- src/duckdb/src/main/secret/secret_storage.cpp | 14 +- .../src/main/settings/custom_settings.cpp | 20 +- src/duckdb/src/storage/block_allocator.cpp | 19 +- .../src/storage/buffer/block_handle.cpp | 15 +- .../src/storage/buffer/block_manager.cpp | 6 +- src/duckdb/src/storage/buffer/buffer_pool.cpp | 10 +- src/duckdb/src/storage/buffer_manager.cpp | 11 +- .../write_overflow_strings_to_disk.cpp | 2 +- src/duckdb/src/storage/checkpoint_manager.cpp | 16 +- .../src/storage/compression/bitpacking.cpp | 4 +- .../src/storage/compression/dict_fsst.cpp | 7 +- .../compression/dictionary_compression.cpp | 5 +- .../compression/fixed_size_uncompressed.cpp | 2 +- src/duckdb/src/storage/compression/fsst.cpp | 4 +- .../storage/compression/numeric_constant.cpp | 2 +- src/duckdb/src/storage/compression/rle.cpp | 2 +- .../storage/compression/roaring/common.cpp | 2 +- .../src/storage/compression/roaring/scan.cpp | 2 +- .../compression/string_uncompressed.cpp | 7 +- .../compression/validity_uncompressed.cpp | 2 +- src/duckdb/src/storage/compression/zstd.cpp | 18 +- src/duckdb/src/storage/data_table.cpp | 20 +- src/duckdb/src/storage/database_handle.cpp | 23 +- .../caching_file_system.cpp | 55 +- .../caching_file_system_wrapper.cpp | 66 ++- src/duckdb/src/storage/local_storage.cpp | 4 +- src/duckdb/src/storage/magic_bytes.cpp | 2 +- .../src/storage/metadata/metadata_manager.cpp | 11 +- .../src/storage/metadata/metadata_reader.cpp | 9 +- .../src/storage/partial_block_manager.cpp | 25 +- .../src/storage/single_file_block_manager.cpp | 26 +- .../src/storage/standard_buffer_manager.cpp | 46 +- src/duckdb/src/storage/storage_manager.cpp | 16 +- .../src/storage/table/array_column_data.cpp | 6 +- src/duckdb/src/storage/table/column_data.cpp | 19 +- .../table/column_data_checkpointer.cpp | 2 +- .../src/storage/table/geo_column_data.cpp | 7 +- .../storage/table/in_memory_checkpoint.cpp | 2 +- .../src/storage/table/list_column_data.cpp | 9 +- src/duckdb/src/storage/table/row_group.cpp | 35 +- .../storage/table/row_group_collection.cpp | 25 +- src/duckdb/src/storage/table/scan_state.cpp | 9 +- .../storage/table/standard_column_data.cpp | 4 +- .../src/storage/table/struct_column_data.cpp | 6 +- .../src/storage/table/variant_column_data.cpp | 16 +- .../src/storage/temporary_file_manager.cpp | 8 +- src/duckdb/src/storage/wal_replay.cpp | 12 +- src/duckdb/src/storage/write_ahead_log.cpp | 2 +- src/duckdb/src/transaction/cleanup_state.cpp | 5 +- src/duckdb/src/transaction/commit_state.cpp | 6 +- .../src/transaction/transaction_context.cpp | 21 +- src/duckdb/ub_src_common.cpp | 2 - src/duckdb/ub_src_common_multi_file.cpp | 2 + src/duckdb/ub_src_main.cpp | 2 - src/duckdb/ub_src_main_capi_v2.cpp | 2 + 224 files changed, 2972 insertions(+), 1645 deletions(-) create mode 100644 src/duckdb/src/common/multi_file/table_function_query_filter.cpp delete mode 100644 src/duckdb/src/common/query_context.cpp create mode 100644 src/duckdb/src/include/duckdb/common/file_lookup_info.hpp delete mode 100644 src/duckdb/src/include/duckdb/common/file_opener.hpp create mode 100644 src/duckdb/src/include/duckdb/common/multi_file/table_function_query_filter.hpp delete mode 100644 src/duckdb/src/include/duckdb/common/query_context.hpp delete mode 100644 src/duckdb/src/include/duckdb/main/client_context_file_opener.hpp rename src/duckdb/src/include/duckdb/main/{database_file_opener.hpp => database_file_system.hpp} (55%) create mode 100644 src/duckdb/src/include/duckdb/main/http/http_transport_manager_state.hpp create mode 100644 src/duckdb/src/main/capi/v2/capi_v2_context_state.cpp delete mode 100644 src/duckdb/src/main/client_context_file_opener.cpp diff --git a/src/duckdb/extension/json/include/json_reader.hpp b/src/duckdb/extension/json/include/json_reader.hpp index e1d0c365a..adf60f565 100644 --- a/src/duckdb/extension/json/include/json_reader.hpp +++ b/src/duckdb/extension/json/include/json_reader.hpp @@ -15,7 +15,7 @@ #include "duckdb/common/open_file_info.hpp" #include "json_reader_options.hpp" #include "duckdb/common/mutex.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" #include "json_common.hpp" #include "json_enums.hpp" #include "yyjson_memory.hpp" @@ -49,7 +49,7 @@ struct JSONBufferHandle { struct JSONFileHandle { public: - JSONFileHandle(QueryContext context, unique_ptr file_handle, Allocator &allocator); + JSONFileHandle(Context &context, unique_ptr file_handle, Allocator &allocator); bool IsOpen() const; void Close(); @@ -82,7 +82,7 @@ struct JSONFileHandle { idx_t ReadFromCache(char *&pointer, idx_t &size, atomic &position); private: - QueryContext context; + Context &context; //! The JSON file handle unique_ptr file_handle; diff --git a/src/duckdb/extension/json/json_reader.cpp b/src/duckdb/extension/json/json_reader.cpp index def1a669e..7cda39d0c 100644 --- a/src/duckdb/extension/json/json_reader.cpp +++ b/src/duckdb/extension/json/json_reader.cpp @@ -4,7 +4,6 @@ #include -#include "duckdb/common/file_opener.hpp" #include "duckdb/common/file_open_flags.hpp" #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/common/serializer/serializer.hpp" @@ -19,7 +18,7 @@ JSONBufferHandle::JSONBufferHandle(JSONReader &reader, idx_t buffer_index_p, idx buffer_size(buffer_size_p), buffer_start(buffer_start_p), remainder_start(DConstants::INVALID_INDEX) { } -JSONFileHandle::JSONFileHandle(QueryContext context_p, unique_ptr file_handle_p, Allocator &allocator_p) +JSONFileHandle::JSONFileHandle(Context &context_p, unique_ptr file_handle_p, Allocator &allocator_p) : context(context_p), file_handle(std::move(file_handle_p)), allocator(allocator_p), can_seek(file_handle->CanSeek()), file_size(file_handle->GetFileSize()), compressed(file_handle->GetFileCompressionType() != FileCompressionType::UNCOMPRESSED), read_position(0), @@ -31,7 +30,7 @@ bool JSONFileHandle::IsOpen() const { } void JSONFileHandle::Close() { - if (IsOpen() && !file_handle->IsPipe()) { + if (IsOpen() && !file_handle->IsPipe(context)) { file_handle->Close(); file_handle = nullptr; } @@ -89,7 +88,7 @@ bool JSONFileHandle::CanSeek() const { } bool JSONFileHandle::IsPipe() const { - return file_handle->IsPipe(); + return file_handle->IsPipe(context); } FileHandle &JSONFileHandle::GetHandle() { diff --git a/src/duckdb/extension/parquet/include/parquet_reader.hpp b/src/duckdb/extension/parquet/include/parquet_reader.hpp index 25766dab8..acfe69451 100644 --- a/src/duckdb/extension/parquet/include/parquet_reader.hpp +++ b/src/duckdb/extension/parquet/include/parquet_reader.hpp @@ -409,6 +409,9 @@ class ParquetReader : public BaseFileReader { string GetReaderType() const override { return "Parquet"; } + bool SupportsDeletionFilter() const override { + return true; + } shared_ptr GetUnionData(idx_t file_idx) override; unique_ptr GetStatistics(ClientContext &context, const Identifier &name) override; diff --git a/src/duckdb/extension/parquet/include/parquet_writer.hpp b/src/duckdb/extension/parquet/include/parquet_writer.hpp index 1cf2e95cf..4826056b3 100644 --- a/src/duckdb/extension/parquet/include/parquet_writer.hpp +++ b/src/duckdb/extension/parquet/include/parquet_writer.hpp @@ -57,7 +57,6 @@ class TProtocol; namespace duckdb { class FileSystem; -class FileOpener; class ParquetEncryptionConfig; class ParquetStatsAccumulator; class Serializer; diff --git a/src/duckdb/extension/parquet/include/thrift_tools.hpp b/src/duckdb/extension/parquet/include/thrift_tools.hpp index 4412248a6..3fc8ffdfc 100644 --- a/src/duckdb/extension/parquet/include/thrift_tools.hpp +++ b/src/duckdb/extension/parquet/include/thrift_tools.hpp @@ -188,7 +188,7 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra public: static constexpr uint64_t PREFETCH_FALLBACK_BUFFERSIZE = 1000000; - ThriftFileTransport(QueryContext context_p, CachingFileHandle &file_handle_p, bool prefetch_mode_p, + ThriftFileTransport(Context &context_p, CachingFileHandle &file_handle_p, bool prefetch_mode_p, uint64_t accepted_column_gap = ReadHeadComparator::DEFAULT_ACCEPTED_COLUMN_GAP) : context(context_p), file_handle(file_handle_p), location(0), size(file_handle.GetFileSize()), ra_buffer(ReadAheadBuffer(file_handle, accepted_column_gap)), prefetch_mode(prefetch_mode_p) { @@ -309,7 +309,7 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra } private: - QueryContext context; + Context &context; CachingFileHandle &file_handle; idx_t location; diff --git a/src/duckdb/extension/parquet/include/zstd_file_system.hpp b/src/duckdb/extension/parquet/include/zstd_file_system.hpp index 8c43d4968..ddf3890ea 100644 --- a/src/duckdb/extension/parquet/include/zstd_file_system.hpp +++ b/src/duckdb/extension/parquet/include/zstd_file_system.hpp @@ -21,7 +21,7 @@ namespace duckdb { class ZStdFileSystem : public CompressedFileSystem { public: - unique_ptr OpenCompressedFile(QueryContext context, unique_ptr handle, bool write) override; + unique_ptr OpenCompressedFile(Context &context, unique_ptr handle, bool write) override; std::string GetName() const override { return "ZStdFileSystem"; diff --git a/src/duckdb/extension/parquet/parquet_multi_file_info.cpp b/src/duckdb/extension/parquet/parquet_multi_file_info.cpp index 3bc0807a2..519b5c3bd 100644 --- a/src/duckdb/extension/parquet/parquet_multi_file_info.cpp +++ b/src/duckdb/extension/parquet/parquet_multi_file_info.cpp @@ -1,4 +1,5 @@ #include "parquet_multi_file_info.hpp" +#include "duckdb/common/multi_file/table_function_query_filter.hpp" #include "duckdb/common/multi_file/table_function_multi_file.hpp" #include "duckdb/main/client_context.hpp" @@ -159,6 +160,8 @@ static vector LoadMetadataCaches(ClientContext &conte if (file.extended_info) { file.extended_info->TryGetOption("has_deletes", has_deletes); } + // the filter query of a file decides which of its rows are scanned + has_deletes = has_deletes || TableFunctionQueryFilter::HasFilterQuery(file); // check if the cache is valid based ONLY on the OpenFileInfo (do not do any file system requests here) const auto is_valid = metadata_entry->IsValid(file, context); @@ -223,6 +226,10 @@ static vector ParquetMultiFileGetPartitionStats(ClientConte GetPartitionStatsInput &input) { auto &bind_data = input.bind_data->Cast(); if (bind_data.file_list->GetExpandResult() == FileExpandResult::SINGLE_FILE) { + if (TableFunctionQueryFilter::HasFilterQuery(bind_data.file_list->GetFirstFile())) { + // the filter query decides which rows are scanned - the metadata does not tell how many the scan produces + return vector(); + } auto result = TableFunctionMultiFileWrapper::GetPartitionStats(context, input); // Column accessors address physical ordinals and types, not the mapped output or generated roles. bool identity = false; diff --git a/src/duckdb/extension/parquet/parquet_reader.cpp b/src/duckdb/extension/parquet/parquet_reader.cpp index 39d03c1a8..232c144e0 100644 --- a/src/duckdb/extension/parquet/parquet_reader.cpp +++ b/src/duckdb/extension/parquet/parquet_reader.cpp @@ -246,7 +246,7 @@ using duckdb_parquet::Statistics; using duckdb_parquet::Type; static unique_ptr -CreateThriftFileProtocol(QueryContext context, CachingFileHandle &file_handle, bool prefetch_mode, +CreateThriftFileProtocol(Context &context, CachingFileHandle &file_handle, bool prefetch_mode, uint64_t accepted_column_gap = ReadHeadComparator::DEFAULT_ACCEPTED_COLUMN_GAP) { auto transport = duckdb_base_std::make_shared(context, file_handle, prefetch_mode, accepted_column_gap); diff --git a/src/duckdb/extension/parquet/read_single_parquet_file.cpp b/src/duckdb/extension/parquet/read_single_parquet_file.cpp index 1b904ef04..86c258bd1 100644 --- a/src/duckdb/extension/parquet/read_single_parquet_file.cpp +++ b/src/duckdb/extension/parquet/read_single_parquet_file.cpp @@ -597,6 +597,7 @@ TableFunctionMultiFileSettings ParquetScanFunction::GetMultiFileSettings() { // the order the filters are best applied in is learned while reading, and carries over to the next file settings.reuses_local_state = true; settings.reports_bytes_scanned = true; + settings.supports_deletion_filter = true; return settings; } diff --git a/src/duckdb/extension/parquet/zstd_file_system.cpp b/src/duckdb/extension/parquet/zstd_file_system.cpp index 4f347516b..7520a3c82 100644 --- a/src/duckdb/extension/parquet/zstd_file_system.cpp +++ b/src/duckdb/extension/parquet/zstd_file_system.cpp @@ -27,7 +27,7 @@ struct ZstdStreamWrapper : public StreamWrapper { bool writing = false; public: - void Initialize(QueryContext context, CompressedFile &file, bool write) override; + void Initialize(Context &context, CompressedFile &file, bool write) override; bool Read(StreamData &stream_data) override; void Write(CompressedFile &file, StreamData &stream_data, data_ptr_t buffer, int64_t nr_bytes) override; @@ -59,7 +59,7 @@ ZstdStreamWrapper::~ZstdStreamWrapper() { } } -void ZstdStreamWrapper::Initialize(QueryContext context, CompressedFile &file, bool write) { +void ZstdStreamWrapper::Initialize(Context &context, CompressedFile &file, bool write) { D_ASSERT(!zstd_stream_ptr && !zstd_compress_ptr); this->file = &file; this->writing = write; @@ -124,7 +124,7 @@ void ZstdStreamWrapper::Write(CompressedFile &file, StreamData &sd, data_ptr_t u sd.out_buff_start += written_to_output; if (sd.out_buff_start == sd.out_buff.get() + sd.out_buf_size) { // no more output buffer available: flush - file.child_handle->Write(file.context, sd.out_buff.get(), sd.out_buff_start - sd.out_buff.get()); + file.child_handle->Write(*file.context, sd.out_buff.get(), sd.out_buff_start - sd.out_buff.get()); sd.out_buff_start = sd.out_buff.get(); } uncompressed_data += input_consumed; @@ -155,7 +155,7 @@ void ZstdStreamWrapper::FlushStream() { idx_t written_to_output = out_buffer.pos; sd.out_buff_start += written_to_output; if (sd.out_buff_start > sd.out_buff.get()) { - file->child_handle->Write(file->context, sd.out_buff.get(), sd.out_buff_start - sd.out_buff.get()); + file->child_handle->Write(*file->context, sd.out_buff.get(), sd.out_buff_start - sd.out_buff.get()); sd.out_buff_start = sd.out_buff.get(); } if (res == 0) { @@ -191,7 +191,7 @@ struct ZStdFileSystemHolder { class ZStdFile : private ZStdFileSystemHolder, public CompressedFile { public: - ZStdFile(QueryContext context, unique_ptr child_handle_p, const string &path, bool write) + ZStdFile(Context &context, unique_ptr child_handle_p, const string &path, bool write) : CompressedFile(zstd_fs, std::move(child_handle_p), path) { Initialize(context, write); } @@ -203,8 +203,7 @@ class ZStdFile : private ZStdFileSystemHolder, public CompressedFile { } // namespace -unique_ptr ZStdFileSystem::OpenCompressedFile(QueryContext context, unique_ptr handle, - bool write) { +unique_ptr ZStdFileSystem::OpenCompressedFile(Context &context, unique_ptr handle, bool write) { try { auto path = handle->path; return make_uniq(context, std::move(handle), path, write); diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index e2a92527b..86e6a25f1 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-alpha58157"; + descriptor->api_version = "v2.1.0-alpha58282"; 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-alpha58157"; + descriptor->api_version = "v2.1.0-alpha58282"; 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-alpha58157"; + descriptor->api_version = "v2.1.0-alpha58282"; 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-alpha58157"; + descriptor->api_version = "v2.1.0-alpha58282"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp b/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp index 87da4b915..6e3ba1053 100644 --- a/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp @@ -1501,7 +1501,7 @@ TableFunction DuckTableEntry::GetScanFunction(ClientContext &context, unique_ptr return TableScanFunction::GetFunction(); } -vector DuckTableEntry::GetColumnSegmentInfo(const QueryContext &context, +vector DuckTableEntry::GetColumnSegmentInfo(Context &context, const ColumnSegmentInfoScanOptions &options) { return storage->GetColumnSegmentInfo(context, options); } @@ -1510,7 +1510,7 @@ void DuckTableEntry::InitializeColumnSegmentInfoScan(ColumnSegmentInfoScanState storage->InitializeColumnSegmentInfoScan(state); } -bool DuckTableEntry::ScanColumnSegmentInfo(const QueryContext &context, ColumnSegmentInfoScanState &state, +bool DuckTableEntry::ScanColumnSegmentInfo(Context &context, ColumnSegmentInfoScanState &state, vector &result) { return storage->ScanColumnSegmentInfo(context, state, result); } diff --git a/src/duckdb/src/catalog/catalog_entry/table_catalog_entry.cpp b/src/duckdb/src/catalog/catalog_entry/table_catalog_entry.cpp index 835c3c9c2..0a7354a8b 100644 --- a/src/duckdb/src/catalog/catalog_entry/table_catalog_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/table_catalog_entry.cpp @@ -292,7 +292,7 @@ void LogicalUpdate::BindAllColumns(TableCatalogEntry &table, LogicalGet &get, Lo BindExtraColumns(table, get, proj, update, all_columns, reuse_projected_columns); } -vector TableCatalogEntry::GetColumnSegmentInfo(const QueryContext &context, +vector TableCatalogEntry::GetColumnSegmentInfo(Context &context, const ColumnSegmentInfoScanOptions &options) { return {}; } @@ -300,7 +300,7 @@ vector TableCatalogEntry::GetColumnSegmentInfo(const QueryCon void TableCatalogEntry::InitializeColumnSegmentInfoScan(ColumnSegmentInfoScanState &state) { } -bool TableCatalogEntry::ScanColumnSegmentInfo(const QueryContext &context, ColumnSegmentInfoScanState &state, +bool TableCatalogEntry::ScanColumnSegmentInfo(Context &context, ColumnSegmentInfoScanState &state, vector &result) { return false; } diff --git a/src/duckdb/src/common/base_file_system.cpp b/src/duckdb/src/common/base_file_system.cpp index 5d9d10416..5bb60f366 100644 --- a/src/duckdb/src/common/base_file_system.cpp +++ b/src/duckdb/src/common/base_file_system.cpp @@ -6,7 +6,7 @@ #include "duckdb/common/time_point.hpp" #include "duckdb/common/compressed_file_system.hpp" #include "duckdb/common/exception.hpp" -#include "duckdb/common/file_opener.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/helper.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/multi_file/multi_file_list.hpp" @@ -364,17 +364,7 @@ string BaseFileSystem::ExtractExtension(const string &path) { return vec.back(); } -string FileSystem::GetHomeDirectory(optional_ptr opener) { - // read the home_directory setting first, if it is set - if (opener) { - Value result; - if (opener->TryGetCurrentSetting("home_directory", result)) { - if (!result.IsNull() && !result.ToString().empty()) { - return result.ToString(); - } - } - } - // fallback to the default home directories for the specified system +string FileSystem::GetDefaultHomeDirectory() { #ifdef DUCKDB_WINDOWS return FileSystem::GetEnvVariable("USERPROFILE"); #else @@ -382,8 +372,20 @@ string FileSystem::GetHomeDirectory(optional_ptr opener) { #endif } +string FileSystem::GetHomeDirectory(Context &context) { + // read the home_directory setting first, if it is set + Value result; + if (context.TryGetCurrentSetting("home_directory", result)) { + if (!result.IsNull() && !result.ToString().empty()) { + return result.ToString(); + } + } + // fallback to the default home directories for the specified system + return GetDefaultHomeDirectory(); +} + string BaseFileSystem::GetHomeDirectory() { - return FileSystem::GetHomeDirectory(nullptr); + return FileSystem::GetDefaultHomeDirectory(); } // Helper function to handle file:/ URLs @@ -423,12 +425,19 @@ static idx_t GetFileUrlOffset(const string &path) { return 0; } -string FileSystem::ExpandPath(const string &path, optional_ptr opener) { +string FileSystem::ExpandPath(Context &context, const string &path) { + if (!path.empty() && path[0] == '~') { + return ExpandPathWithHome(path, GetHomeDirectory(context)); + } + return ExpandPathWithHome(path, string()); +} + +string FileSystem::ExpandPathWithHome(const string &path, const string &home_directory) { if (path.empty()) { return path; } if (path[0] == '~') { - return FileSystem::GetHomeDirectory(opener) + path.substr(1); + return home_directory + path.substr(1); } // handle file URIs auto file_offset = GetFileUrlOffset(path); @@ -439,35 +448,34 @@ string FileSystem::ExpandPath(const string &path, optional_ptr opene } string BaseFileSystem::ExpandPath(const string &path) { - return FileSystem::ExpandPath(path, nullptr); + return FileSystem::ExpandPathWithHome(path, GetHomeDirectory()); } // LCOV_EXCL_START -unique_ptr BaseFileSystem::OpenFileExtended(const OpenFileInfo &path, - FileOpenFlags flags, // NOLINT: virtual, overrides mutate flags - optional_ptr opener) { +unique_ptr +BaseFileSystem::OpenFileExtended(Context &context, const OpenFileInfo &path, + FileOpenFlags flags) { // NOLINT: virtual, overrides mutate flags throw NotImplementedException("%s: OpenFileExtended is not implemented!", GetName()); } -bool BaseFileSystem::ListFilesExtended(const string &directory, const std::function &callback, - optional_ptr opener) { +bool BaseFileSystem::ListFilesExtended(Context &context, const string &directory, + const std::function &callback) { throw NotImplementedException("%s: ListFilesExtended is not implemented!", GetName()); } -unique_ptr BaseFileSystem::OpenFile(const string &path, FileOpenFlags flags, - optional_ptr opener) { +unique_ptr BaseFileSystem::OpenFile(Context &context, const string &path, FileOpenFlags flags) { if (SupportsOpenFileExtended()) { - return OpenFileExtended(OpenFileInfo(path), std::move(flags), opener); + return OpenFileExtended(context, OpenFileInfo(path), std::move(flags)); } throw NotImplementedException("%s: OpenFile is not implemented!", GetName()); } -unique_ptr BaseFileSystem::OpenFile(const OpenFileInfo &file, const FileOpenFlags &flags, - optional_ptr opener) { +unique_ptr BaseFileSystem::OpenFile(Context &context, const OpenFileInfo &file, + const FileOpenFlags &flags) { if (SupportsOpenFileExtended()) { - return OpenFileExtended(file, flags, opener); + return OpenFileExtended(context, file, flags); } else { - return OpenFile(file.path, flags, opener); + return OpenFile(context, file.path, flags); } } @@ -535,8 +543,8 @@ FileMetadata BaseFileSystem::Stats(FileHandle &handle) { return metadata; } -optional BaseFileSystem::GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) { - auto handle = OpenFile(file, FileFlags::FILE_FLAGS_READ | FileFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS, opener); +optional BaseFileSystem::GetStatsIfExists(Context &context, const OpenFileInfo &file) { + auto handle = OpenFile(context, file, FileFlags::FILE_FLAGS_READ | FileFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS); if (!handle) { return nullopt; } @@ -547,36 +555,36 @@ void BaseFileSystem::Truncate(FileHandle &handle, int64_t new_size) { throw NotImplementedException("%s: Truncate is not implemented!", GetName()); } -bool BaseFileSystem::DirectoryExists(const string &directory, optional_ptr opener) { +bool BaseFileSystem::DirectoryExists(Context &context, const string &directory) { throw NotImplementedException("%s: DirectoryExists is not implemented!", GetName()); } -void BaseFileSystem::CreateDirectory(const string &directory, optional_ptr opener) { +void BaseFileSystem::CreateDirectory(Context &context, const string &directory) { throw NotImplementedException("%s: CreateDirectory is not implemented!", GetName()); } -bool BaseFileSystem::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener) { +bool BaseFileSystem::CreateDirectoryExtended(Context &context, const string &directory, + const CreateDirectoryOptions &options) { switch (options.mode) { case CreateDirectoryMode::SINGLE: - if (!DirectoryExists(directory, opener)) { - CreateDirectory(directory, opener); + if (!DirectoryExists(context, directory)) { + CreateDirectory(context, directory); } return false; case CreateDirectoryMode::RECURSIVE: { auto parsed = Path::FromString(directory); vector directories; - while (!parsed.GetPathSegments().empty() && !DirectoryExists(parsed.ToString(), opener)) { + while (!parsed.GetPathSegments().empty() && !DirectoryExists(context, parsed.ToString())) { directories.push_back(parsed.ToString()); parsed = parsed.Parent(); } - if (parsed.GetPathSegments().empty() && !DirectoryExists(parsed.ToString(), opener)) { + if (parsed.GetPathSegments().empty() && !DirectoryExists(context, parsed.ToString())) { directories.push_back(parsed.ToString()); } bool target_created = false; for (auto riter = directories.rbegin(); riter != directories.rend(); ++riter) { - auto created = CreateDirectoryExtended(*riter, {CreateDirectoryMode::SINGLE}, opener); + auto created = CreateDirectoryExtended(context, *riter, {CreateDirectoryMode::SINGLE}); if (*riter == directories.front()) { target_created = created; } @@ -588,21 +596,21 @@ bool BaseFileSystem::CreateDirectoryExtended(const string &directory, const Crea } } -void BaseFileSystem::CreateDirectoriesRecursive(const string &path, optional_ptr opener) { - CreateDirectoryExtended(path, {CreateDirectoryMode::RECURSIVE}, opener); +void BaseFileSystem::CreateDirectoriesRecursive(Context &context, const string &path) { + CreateDirectoryExtended(context, path, {CreateDirectoryMode::RECURSIVE}); } -void BaseFileSystem::RemoveDirectory(const string &directory, optional_ptr opener) { +void BaseFileSystem::RemoveDirectory(Context &context, const string &directory) { throw NotImplementedException("%s: RemoveDirectory is not implemented!", GetName()); } -bool BaseFileSystem::RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener) { +bool BaseFileSystem::RemoveDirectoryExtended(Context &context, const string &directory, + const RemoveDirectoryOptions &options) { switch (options.mode) { case RemoveDirectoryMode::SINGLE: return false; case RemoveDirectoryMode::RECURSIVE: - RemoveDirectory(directory, opener); + RemoveDirectory(context, directory); return false; default: throw InternalException("Unknown RemoveDirectoryMode"); @@ -620,66 +628,60 @@ bool FileSystem::IsDirectory(const OpenFileInfo &info) { return type == "directory"; } -bool BaseFileSystem::ListFiles(const string &directory, const std::function &callback, - FileOpener *opener) { +bool BaseFileSystem::ListFiles(Context &context, const string &directory, + const std::function &callback) { if (SupportsListFilesExtended()) { - return ListFilesExtended( - directory, - [&](const OpenFileInfo &info) { - bool is_dir = FileSystem::IsDirectory(info); - callback(info.path, is_dir); - }, - opener); + return ListFilesExtended(context, directory, [&](const OpenFileInfo &info) { + bool is_dir = FileSystem::IsDirectory(info); + callback(info.path, is_dir); + }); } throw NotImplementedException("%s: ListFiles is not implemented!", GetName()); } -bool BaseFileSystem::ListFiles(const string &directory, const std::function &callback, - optional_ptr opener) { +bool BaseFileSystem::ListFiles(Context &context, const string &directory, + const std::function &callback) { if (SupportsListFilesExtended()) { - return ListFilesExtended(directory, callback, opener); + return ListFilesExtended(context, directory, callback); } else { - return ListFiles( - directory, - [&](const string &path, bool is_dir) { - OpenFileInfo info(path); - if (is_dir) { - info.extended_info = make_shared_ptr(); - info.extended_info->options["type"] = "directory"; - } - callback(info); - }, - opener.get()); + return ListFiles(context, directory, [&](const string &path, bool is_dir) { + OpenFileInfo info(path); + if (is_dir) { + info.extended_info = make_shared_ptr(); + info.extended_info->options["type"] = "directory"; + } + callback(info); + }); } } -void BaseFileSystem::MoveFile(const string &source, const string &target, optional_ptr opener) { +void BaseFileSystem::MoveFile(Context &context, const string &source, const string &target) { throw NotImplementedException("%s: MoveFile is not implemented!", GetName()); } -bool BaseFileSystem::FileExists(const string &filename, optional_ptr opener) { +bool BaseFileSystem::FileExists(Context &context, const string &filename) { throw NotImplementedException("%s: FileExists is not implemented!", GetName()); } -bool BaseFileSystem::IsPipe(const string &filename, optional_ptr opener) { +bool BaseFileSystem::IsPipe(Context &context, const string &filename) { return false; } -void BaseFileSystem::RemoveFile(const string &filename, optional_ptr opener) { +void BaseFileSystem::RemoveFile(Context &context, const string &filename) { throw NotImplementedException("%s: RemoveFile is not implemented!", GetName()); } -bool BaseFileSystem::TryRemoveFile(const string &filename, optional_ptr opener) { - if (FileExists(filename, opener)) { - RemoveFile(filename, opener); +bool BaseFileSystem::TryRemoveFile(Context &context, const string &filename) { + if (FileExists(context, filename)) { + RemoveFile(context, filename); return true; } return false; } -void BaseFileSystem::RemoveFiles(const vector &filenames, optional_ptr opener) { +void BaseFileSystem::RemoveFiles(Context &context, const vector &filenames) { for (const auto &filename : filenames) { - TryRemoveFile(filename, opener); + TryRemoveFile(context, filename); } } @@ -705,26 +707,25 @@ bool FileSystem::HasGlob(const string &str) { return false; } -vector BaseFileSystem::Glob(const string &path, FileOpener *opener) { +vector BaseFileSystem::Glob(Context &context, const string &path) { if (SupportsGlobExtended()) { - auto result = GlobFilesExtended(path, FileGlobOptions::ALLOW_EMPTY, opener); + auto result = GlobFilesExtended(context, path, FileGlobOptions::ALLOW_EMPTY); return result->GetAllFiles(); } throw NotImplementedException("%s: Glob is not implemented!", GetName()); } -unique_ptr BaseFileSystem::Glob(const string &path, const FileGlobInput &input, - optional_ptr opener) { +unique_ptr BaseFileSystem::Glob(Context &context, const string &path, const FileGlobInput &input) { if (!SupportsGlobExtended()) { - auto result = Glob(path, opener.get()); + auto result = Glob(context, path); return make_uniq(std::move(result)); } else { - return GlobFilesExtended(path, input, opener); + return GlobFilesExtended(context, path, input); } } -unique_ptr BaseFileSystem::GlobFilesExtended(const string &path, const FileGlobInput &input, - optional_ptr opener) { +unique_ptr BaseFileSystem::GlobFilesExtended(Context &context, const string &path, + const FileGlobInput &input) { throw NotImplementedException("%s: GlobFilesExtended is not implemented!", GetName()); } @@ -756,8 +757,7 @@ FileWriteMode BaseFileSystem::GetWriteMode(FileHandle &handle) { return FileWriteMode::SEQUENTIAL; } -unique_ptr BaseFileSystem::OpenCompressedFile(QueryContext context, unique_ptr handle, - bool write) { +unique_ptr BaseFileSystem::OpenCompressedFile(Context &context, unique_ptr handle, bool write) { throw NotImplementedException("%s: OpenCompressedFile is not implemented!", GetName()); } @@ -785,14 +785,14 @@ int64_t FileHandle::Read(void *buffer, idx_t nr_bytes) { return file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes)); } -static optional_ptr GetTrackingProfiler(bool track_io, const QueryContext &context) { - if (!track_io || !context.Valid()) { +static optional_ptr GetTrackingProfiler(bool track_io, Context &context) { + if (!track_io) { return nullptr; } - return context.GetContext()->TryGetQueryProfiler(); + return context.TryGetQueryProfiler(); } -int64_t FileHandle::Read(QueryContext context, void *buffer, idx_t nr_bytes) { +int64_t FileHandle::Read(Context &context, void *buffer, idx_t nr_bytes) { auto profiler = GetTrackingProfiler(track_io, context); const bool track = profiler != nullptr; const auto start = track ? TimePoint::Tick() : TimePoint(); @@ -815,7 +815,7 @@ int64_t FileHandle::Write(void *buffer, idx_t nr_bytes) { return file_system.Write(*this, buffer, UnsafeNumericCast(nr_bytes)); } -int64_t FileHandle::Write(QueryContext context, void *buffer, idx_t nr_bytes) { +int64_t FileHandle::Write(Context &context, void *buffer, idx_t nr_bytes) { auto profiler = GetTrackingProfiler(track_io, context); const bool track = profiler != nullptr; const auto start = track ? TimePoint::Tick() : TimePoint(); @@ -832,7 +832,7 @@ void FileHandle::Read(void *buffer, idx_t nr_bytes, idx_t location) { file_system.Read(*this, buffer, UnsafeNumericCast(nr_bytes), location); } -void FileHandle::Read(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location) { +void FileHandle::Read(Context &context, void *buffer, idx_t nr_bytes, idx_t location) { auto profiler = GetTrackingProfiler(track_io, context); const bool track = profiler != nullptr; const auto start = track ? TimePoint::Tick() : TimePoint(); @@ -843,7 +843,7 @@ void FileHandle::Read(QueryContext context, void *buffer, idx_t nr_bytes, idx_t } } -void FileHandle::Write(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location) { +void FileHandle::Write(Context &context, void *buffer, idx_t nr_bytes, idx_t location) { auto profiler = GetTrackingProfiler(track_io, context); const bool track = profiler != nullptr; const auto start = track ? TimePoint::Tick() : TimePoint(); @@ -878,8 +878,8 @@ FileCompressionType FileHandle::GetFileCompressionType() { return FileCompressionType::UNCOMPRESSED; } -bool FileHandle::IsPipe() { - return file_system.IsPipe(path, nullptr); +bool FileHandle::IsPipe(Context &context) { + return file_system.IsPipe(context, path); } string FileHandle::ReadLine() { @@ -896,7 +896,7 @@ string FileHandle::ReadLine() { } } -string FileHandle::ReadLine(QueryContext context) { +string FileHandle::ReadLine(Context &context) { string result; char buffer[1]; while (true) { @@ -942,20 +942,19 @@ FileMetadata FileHandle::Stats() { return file_system.Stats(*this); } -void FileHandle::TryAddLogger(FileOpener &opener) { +void FileHandle::TryAddLogger(Context &context) { if (flags.DisableLogging()) { return; } - auto &context = opener.TryGetContext(); if (context.IsClient() && context.GetLogger().ShouldLog(FileSystemLogType::NAME, FileSystemLogType::LEVEL)) { logger = context.GetLoggerPtr(); return; } - auto database = opener.TryGetDatabase(); - if (database && Logger::Get(*database).ShouldLog(FileSystemLogType::NAME, FileSystemLogType::LEVEL)) { - logger = database->GetLogManager().GlobalLoggerReference(); + auto &database = context.GetDatabase(); + if (Logger::Get(database).ShouldLog(FileSystemLogType::NAME, FileSystemLogType::LEVEL)) { + logger = database.GetLogManager().GlobalLoggerReference(); } } @@ -978,7 +977,11 @@ bool FileSystem::IsRemoteFile(const string &path, string &extension) { return false; } -string BaseFileSystem::CanonicalizePath(const string &path_p, optional_ptr opener) { +string BaseFileSystem::CanonicalizePath(Context &context, const string &path_p) { + return GenericCanonicalizePath(path_p); +} + +string BaseFileSystem::GenericCanonicalizePath(const string &path_p) { // TODO: @benfleis - integrate this properly with Path (needs additional work) if (FileSystem::IsRemoteFile(path_p) || !Path::FromString(path_p).IsLocal()) { // don't canonicalize remote paths diff --git a/src/duckdb/src/common/compressed_file_system.cpp b/src/duckdb/src/common/compressed_file_system.cpp index ab3693df0..a804814b1 100644 --- a/src/duckdb/src/common/compressed_file_system.cpp +++ b/src/duckdb/src/common/compressed_file_system.cpp @@ -62,11 +62,11 @@ CompressedFile::~CompressedFile() { } } -void CompressedFile::Initialize(QueryContext context, bool write) { +void CompressedFile::Initialize(Context &context, bool write) { Clear(); initialized = false; - this->context = context; + this->context = &context; this->write = write; stream_data.in_buf_size = compressed_fs.InBufferSize(); if (!write && FileSystem::IsRemoteFile(child_handle->path)) { @@ -74,7 +74,7 @@ void CompressedFile::Initialize(QueryContext context, bool write) { stream_data.in_buf_size, MinValue(REMOTE_READ_IN_BUF_SIZE, child_handle->GetFileSize())); } stream_data.out_buf_size = compressed_fs.OutBufferSize(); - auto &allocator = context.Valid() ? BufferAllocator::Get(*context.GetContext()) : Allocator::DefaultAllocator(); + auto &allocator = BufferAllocator::Get(context); stream_data.in_buff = allocator.Allocate(stream_data.in_buf_size); stream_data.in_buff_start = stream_data.in_buff.get(); stream_data.in_buff_end = stream_data.in_buff.get(); @@ -133,7 +133,7 @@ int64_t CompressedFile::ReadData(void *buffer, int64_t remaining) { // empty input buffer: refill from the start stream_data.in_buff_start = stream_data.in_buff.get(); stream_data.in_buff_end = stream_data.in_buff_start; - auto sz = child_handle->Read(context, stream_data.in_buff.get(), stream_data.in_buf_size); + auto sz = child_handle->Read(*context, stream_data.in_buff.get(), stream_data.in_buf_size); if (sz <= 0) { stream_wrapper->FinalizeRead(stream_data); stream_wrapper.reset(); @@ -243,8 +243,8 @@ int64_t CompressedFileSystem::Write(FileHandle &handle, void *buffer, int64_t nr void CompressedFileSystem::Reset(FileHandle &handle) { auto &compressed_file = handle.Cast(); compressed_file.child_handle->Reset(); - // Preserve the query context across a reset so re-reads (e.g. the scan after the CSV sniffer) stay attributed. - compressed_file.Initialize(compressed_file.context, compressed_file.write); + // Preserve the context across a reset so re-reads (e.g. the scan after the CSV sniffer) stay attributed. + compressed_file.Initialize(*compressed_file.context, compressed_file.write); } int64_t CompressedFileSystem::GetFileSize(FileHandle &handle) { diff --git a/src/duckdb/src/common/csv_writer.cpp b/src/duckdb/src/common/csv_writer.cpp index ea7db5ea3..4621442cc 100644 --- a/src/duckdb/src/common/csv_writer.cpp +++ b/src/duckdb/src/common/csv_writer.cpp @@ -82,14 +82,14 @@ CSVWriter::CSVWriter(const CSVReaderOptions &options_p, AsyncFileWriter &file_wr } CSVWriter::CSVWriter(const CSVReaderOptions &options_p, FileSystem &fs, const string &file_path, - FileCompressionType compression, QueryContext context, bool shared) + FileCompressionType compression, Context &context, bool shared) + : options(options_p), writer_options(options.dialect_options.state_machine_options.delimiter.GetValue(), options.dialect_options.state_machine_options.quote.GetValue(), options.write_newline, GetWriteCommentChar(options)), - file_writer(make_uniq(fs, file_path, + file_writer(make_uniq(fs, context, file_path, FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE_NEW | - FileLockType::WRITE_LOCK | std::move(compression), - context)), + FileLockType::WRITE_LOCK | std::move(compression))), write_stream(*file_writer), should_initialize(true), shared(shared) { if (!shared) { global_write_state = make_uniq(); diff --git a/src/duckdb/src/common/file_buffer.cpp b/src/duckdb/src/common/file_buffer.cpp index 642adcb5a..3f74a3657 100644 --- a/src/duckdb/src/common/file_buffer.cpp +++ b/src/duckdb/src/common/file_buffer.cpp @@ -111,7 +111,7 @@ void FileBuffer::Resize(BlockManager &block_manager) { ResizeInternal(block_manager.GetBlockSize(), block_manager.GetBlockHeaderSize()); } -void FileBuffer::Read(QueryContext context, FileHandle &handle, uint64_t location) { +void FileBuffer::Read(Context &context, FileHandle &handle, uint64_t location) { D_ASSERT(type != FileBufferType::TINY_BUFFER); if (handle.file_system.IsLocalFileSystem()) { // Pre-fault local read buffers before the kernel fills them. @@ -127,7 +127,7 @@ void FileBuffer::ReadFromMemory(const_data_ptr_t source, uint64_t location) { memcpy(internal_buffer, source + location, internal_size); } -void FileBuffer::Read(QueryContext context, MemoryMappedFile &handle, uint64_t location) { +void FileBuffer::Read(Context &context, MemoryMappedFile &handle, uint64_t location) { D_ASSERT(type != FileBufferType::TINY_BUFFER); // Zero-copy: adopt a pointer into the mapping. auto src = handle.GetDataMutable(location, internal_size); @@ -140,12 +140,12 @@ void FileBuffer::Read(QueryContext context, MemoryMappedFile &handle, uint64_t l owns_internal_buffer = false; } -void FileBuffer::Write(QueryContext context, FileHandle &handle, const uint64_t location) { +void FileBuffer::Write(Context &context, FileHandle &handle, const uint64_t location) { D_ASSERT(type != FileBufferType::TINY_BUFFER); handle.Write(context, internal_buffer, internal_size, location); } -void FileBuffer::Write(QueryContext context, MemoryMappedFile &handle, uint64_t location) { +void FileBuffer::Write(Context &context, MemoryMappedFile &handle, uint64_t location) { D_ASSERT(type != FileBufferType::TINY_BUFFER); auto dst = handle.GetDataMutable(location, internal_size); memcpy(dst, internal_buffer, internal_size); diff --git a/src/duckdb/src/common/file_system.cpp b/src/duckdb/src/common/file_system.cpp index f235b73ba..2b32f0188 100644 --- a/src/duckdb/src/common/file_system.cpp +++ b/src/duckdb/src/common/file_system.cpp @@ -2,7 +2,7 @@ #include "duckdb/common/file_system.hpp" #include "duckdb/common/multi_file/multi_file_list.hpp" #include "duckdb/common/path.hpp" -#include "duckdb/common/file_opener.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/memory_mapped_file.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/config.hpp" @@ -25,10 +25,10 @@ unique_ptr FileSystem::OpenFile(const OpenFileInfo &file, const File } auto fixed_fs = GetFixedFileSystem(); if (fixed_fs) { - return fixed_fs->OpenFile(file, flags, GetOpener()); + return fixed_fs->OpenFile(GetContext(), file, flags); } if (flags.GetCachingMode() == CachingMode::NO_CACHING) { - return GetFileSystem().OpenFile(file, flags, GetOpener()); + return GetFileSystem().OpenFile(GetContext(), file, flags); } return OpenCachedFile(file, flags); } @@ -39,17 +39,14 @@ unique_ptr FileSystem::OpenCachedFile(const OpenFileInfo &file, cons raw_flags.SetCompression(FileCompressionType::UNCOMPRESSED); raw_flags.SetCachingMode(CachingMode::NO_CACHING); - auto opener = GetOpener(); - auto db = opener ? opener->TryGetDatabase() : nullptr; - if (!db) { - throw InvalidInputException("Cannot open \"%s\" through the external file cache without a database", file.path); - } - auto caching_file_system = make_shared_ptr(*this, *db, flags.GetCachingMode()); - auto handle = caching_file_system->OpenFile(file, raw_flags, GetOpener()); + auto &context = GetContext(); + auto caching_file_system = + make_shared_ptr(*this, context.GetDatabase(), flags.GetCachingMode()); + auto handle = caching_file_system->OpenFile(context, file, raw_flags); if (!handle) { return nullptr; } - return GetFileSystem().WrapOpenedFile(std::move(handle), file, flags, GetOpener()); + return GetFileSystem().WrapOpenedFile(GetContext(), std::move(handle), file, flags); } unique_ptr FileSystem::MemoryMapFile(const OpenFileInfo &path, const FileOpenFlags &flags, @@ -58,12 +55,12 @@ unique_ptr FileSystem::MemoryMapFile(const OpenFileInfo &path, if (IsDuckDBExtensionName(path.path)) { VerifyCanAccessExtension(path.path, flags); } - return FindFileSystem(path.path).MemoryMapFile(path, flags, options, GetOpener()); + return FindFileSystem(path.path).MemoryMapFile(GetContext(), path, flags, options); } bool FileSystem::DirectoryExists(const string &directory) { VerifyCanAccessDirectory(directory); - return FindFileSystem(directory).DirectoryExists(directory, GetOpener()); + return FindFileSystem(directory).DirectoryExists(GetContext(), directory); } void FileSystem::CreateDirectory(const string &directory) { @@ -73,7 +70,7 @@ void FileSystem::CreateDirectory(const string &directory) { bool FileSystem::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options) { if (options.mode != CreateDirectoryMode::RECURSIVE) { VerifyCanAccessDirectory(directory); - return FindFileSystem(directory).CreateDirectoryExtended(directory, options, GetOpener()); + return FindFileSystem(directory).CreateDirectoryExtended(GetContext(), directory, options); } // access is checked for every ancestor: walk up to the first existing directory, then create downwards auto parsed = Path::FromString(directory); @@ -105,7 +102,7 @@ void FileSystem::RemoveDirectory(const string &directory) { bool FileSystem::RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options) { VerifyCanAccessDirectory(directory); - return FindFileSystem(directory).RemoveDirectoryExtended(directory, options, GetOpener()); + return FindFileSystem(directory).RemoveDirectoryExtended(GetContext(), directory, options); } void FileSystem::MoveFile(const string &source, const string &target) { @@ -118,31 +115,31 @@ void FileSystem::MoveFile(const string &source, const string &target) { "extensions'", source, target); } - FindFileSystem(source).MoveFile(source, target, GetOpener()); + FindFileSystem(source).MoveFile(GetContext(), source, target); } bool FileSystem::FileExists(const string &filename) { VerifyCanAccessFile(filename); - return FindFileSystem(filename).FileExists(filename, GetOpener()); + return FindFileSystem(filename).FileExists(GetContext(), filename); } optional FileSystem::GetStatsIfExists(const OpenFileInfo &file) { VerifyCanAccessFile(file.path); - return FindFileSystem(file.path).GetStatsIfExists(file, GetOpener()); + return FindFileSystem(file.path).GetStatsIfExists(GetContext(), file); } bool FileSystem::IsPipe(const string &filename) { - return FindFileSystem(filename).IsPipe(filename, GetOpener()); + return FindFileSystem(filename).IsPipe(GetContext(), filename); } void FileSystem::RemoveFile(const string &filename) { VerifyCanAccessFile(filename); - FindFileSystem(filename).RemoveFile(filename, GetOpener()); + FindFileSystem(filename).RemoveFile(GetContext(), filename); } bool FileSystem::TryRemoveFile(const string &filename) { VerifyCanAccessFile(filename); - return FindFileSystem(filename).TryRemoveFile(filename, GetOpener()); + return FindFileSystem(filename).TryRemoveFile(GetContext(), filename); } void FileSystem::RemoveFiles(const vector &filenames) { @@ -152,28 +149,28 @@ void FileSystem::RemoveFiles(const vector &filenames) { files_by_fs[FindFileSystem(filename)].push_back(filename); } for (auto &entry : files_by_fs) { - entry.first.get().RemoveFiles(entry.second, GetOpener()); + entry.first.get().RemoveFiles(GetContext(), entry.second); } } bool FileSystem::ListFiles(const string &directory, const std::function &callback) { VerifyCanAccessDirectory(directory); - return FindFileSystem(directory).ListFiles(directory, callback, GetOpener().get()); + return FindFileSystem(directory).ListFiles(GetContext(), directory, callback); } bool FileSystem::ListFiles(const string &directory, const std::function &callback) { VerifyCanAccessDirectory(directory); - return FindFileSystem(directory).ListFiles(directory, callback, GetOpener()); + return FindFileSystem(directory).ListFiles(GetContext(), directory, callback); } vector FileSystem::Glob(const string &path) { VerifyCanAccessFile(path); - return FindFileSystem(path).Glob(path, GetOpener().get()); + return FindFileSystem(path).Glob(GetContext(), path); } unique_ptr FileSystem::Glob(const string &path, const FileGlobInput &input) { VerifyCanAccessFile(path); - return FindFileSystem(path).Glob(path, input, GetOpener()); + return FindFileSystem(path).Glob(GetContext(), path, input); } unique_ptr FileSystem::GlobFileList(const string &pattern, const FileGlobInput &input) { @@ -203,15 +200,16 @@ vector FileSystem::GlobFiles(const string &pattern, const FileGlob } string FileSystem::CanonicalizePath(const string &path) { - return FindFileSystem(path).CanonicalizePath(path, GetOpener()); + // canonicalizing does not need the file system extension of the path, so it is not autoloaded + return PathFileSystem(path).CanonicalizePath(GetContext(), path); } string FileSystem::GetHomeDirectory() { - return FileSystem::GetHomeDirectory(GetOpener()); + return FileSystem::GetHomeDirectory(GetContext()); } string FileSystem::ExpandPath(const string &path) { - return FileSystem::ExpandPath(path, GetOpener()); + return FileSystem::ExpandPath(GetContext(), path); } BaseFileSystem &FileSystem::FindFileSystem(const string &path) { @@ -219,7 +217,7 @@ BaseFileSystem &FileSystem::FindFileSystem(const string &path) { if (fixed_fs) { return *fixed_fs; } - return GetFileSystem().FindFileSystem(path, GetOpener()); + return GetFileSystem().FindFileSystem(GetContext(), path); } string FileSystem::JoinPath(const string &a, const string &path) { @@ -234,20 +232,13 @@ BaseFileSystem &FileSystem::PathFileSystem(const string &path) const { if (fixed_fs) { return *fixed_fs; } - return GetFileSystem().FindFileSystem(path, nullptr); + return GetFileSystem().FindFileSystem(path); } void FileSystem::VerifyCanAccessFileInternal(const string &path, FileType type) { - auto opener = GetOpener(); - if (!opener) { - return; - } - auto db = opener->TryGetDatabase(); - if (!db) { - return; - } - auto &config = db->config; - if (!config.CanAccessFile(path, type, opener)) { + auto &context = GetContext(); + auto &config = context.GetDatabase().config; + if (!config.CanAccessFile(context, path, type)) { throw PermissionException("Cannot access %s \"%s\" - file system operations are disabled by configuration", type == FileType::FILE_TYPE_DIR ? "directory" : "file", path); } diff --git a/src/duckdb/src/common/gzip_file_system.cpp b/src/duckdb/src/common/gzip_file_system.cpp index f7c21b941..abb9c7426 100644 --- a/src/duckdb/src/common/gzip_file_system.cpp +++ b/src/duckdb/src/common/gzip_file_system.cpp @@ -57,7 +57,7 @@ namespace { */ -idx_t GZipConsumeString(QueryContext context, FileHandle &input) { +idx_t GZipConsumeString(Context &context, FileHandle &input) { idx_t size = 1; // terminator char buffer[1]; while (input.Read(context, buffer, 1) == 1) { @@ -69,7 +69,7 @@ idx_t GZipConsumeString(QueryContext context, FileHandle &input) { return size; } -idx_t GZipReadExact(QueryContext context, FileHandle &input, data_ptr_t buffer, idx_t size) { +idx_t GZipReadExact(Context &context, FileHandle &input, data_ptr_t buffer, idx_t size) { idx_t total_read = 0; while (total_read < size) { auto read_count = input.Read(context, buffer + total_read, size - total_read); @@ -100,7 +100,7 @@ struct MiniZStreamWrapper : public StreamWrapper { uint8_t gzip_xlen[2]; public: - void Initialize(QueryContext context, CompressedFile &file, bool write) override; + void Initialize(Context &context, CompressedFile &file, bool write) override; bool Read(StreamData &stream_data) override; void FinalizeRead(StreamData &stream_data) override; @@ -137,7 +137,7 @@ MiniZStreamWrapper::~MiniZStreamWrapper() { } } -void MiniZStreamWrapper::Initialize(QueryContext context, CompressedFile &file, bool write) { +void MiniZStreamWrapper::Initialize(Context &context, CompressedFile &file, bool write) { D_ASSERT(mz_stream_ptr == nullptr); this->file = &file; mz_stream_ptr = make_uniq(); @@ -358,7 +358,7 @@ void MiniZStreamWrapper::Write(CompressedFile &file, StreamData &sd, data_ptr_t sd.out_buff_start += output_remaining - mz_stream_ptr->avail_out; if (mz_stream_ptr->avail_out == 0) { // no more output buffer available: flush - file.child_handle->Write(file.context, sd.out_buff.get(), + file.child_handle->Write(*file.context, sd.out_buff.get(), UnsafeNumericCast(sd.out_buff_start - sd.out_buff.get())); sd.out_buff_start = sd.out_buff.get(); } @@ -380,7 +380,7 @@ void MiniZStreamWrapper::FlushStream() const { auto res = mz_deflate(mz_stream_ptr.get(), duckdb_miniz::MZ_FINISH); sd.out_buff_start += (output_remaining - mz_stream_ptr->avail_out); if (sd.out_buff_start > sd.out_buff.get()) { - file->child_handle->Write(file->context, sd.out_buff.get(), + file->child_handle->Write(*file->context, sd.out_buff.get(), UnsafeNumericCast(sd.out_buff_start - sd.out_buff.get())); sd.out_buff_start = sd.out_buff.get(); } @@ -404,7 +404,7 @@ void MiniZStreamWrapper::Close() { // write the footer unsigned char gzip_footer[MiniZStream::GZIP_FOOTER_SIZE]; MiniZStream::InitializeGZIPFooter(gzip_footer, crc, total_size); - file->child_handle->Write(file->context, gzip_footer, MiniZStream::GZIP_FOOTER_SIZE); + file->child_handle->Write(*file->context, gzip_footer, MiniZStream::GZIP_FOOTER_SIZE); } AbortWrite(); } @@ -428,7 +428,7 @@ struct GZipFileSystemHolder { class GZipFile : private GZipFileSystemHolder, public CompressedFile { public: - GZipFile(QueryContext context, unique_ptr child_handle_p, const string &path, bool write) + GZipFile(Context &context, unique_ptr child_handle_p, const string &path, bool write) : CompressedFile(gzip_fs, std::move(child_handle_p), path) { Initialize(context, write); } @@ -542,8 +542,7 @@ string GZipFileSystem::UncompressGZIPString(const char *data, idx_t size) { return decompressed; } -unique_ptr GZipFileSystem::OpenCompressedFile(QueryContext context, unique_ptr handle, - bool write) { +unique_ptr GZipFileSystem::OpenCompressedFile(Context &context, unique_ptr handle, bool write) { try { auto path = handle->path; return make_uniq(context, std::move(handle), path, write); diff --git a/src/duckdb/src/common/local_file_system.cpp b/src/duckdb/src/common/local_file_system.cpp index d5ac19431..adaa09bd0 100644 --- a/src/duckdb/src/common/local_file_system.cpp +++ b/src/duckdb/src/common/local_file_system.cpp @@ -4,7 +4,6 @@ #include "duckdb/common/checksum.hpp" #include "duckdb/common/enums/file_sync_mode.hpp" #include "duckdb/common/exception.hpp" -#include "duckdb/common/file_opener.hpp" #include "duckdb/common/helper.hpp" #include "duckdb/common/memory_mapped_file.hpp" #include "duckdb/common/operator/add.hpp" @@ -64,9 +63,9 @@ extern "C" WINBASEAPI BOOL QueryFullProcessImageNameW(HANDLE, DWORD, LPWSTR, PDW namespace duckdb { #ifndef _WIN32 -bool LocalFileSystem::FileExists(const string &filename, optional_ptr opener) { +bool LocalFileSystem::FileExists(Context &context, const string &filename) { if (!filename.empty()) { - auto normalized_file = FileSystem::ExpandPath(filename, opener); + auto normalized_file = FileSystem::ExpandPath(context, filename); struct stat status; if (stat(normalized_file.c_str(), &status) == 0 && S_ISREG(status.st_mode)) { return true; @@ -76,9 +75,9 @@ bool LocalFileSystem::FileExists(const string &filename, optional_ptr opener) { +bool LocalFileSystem::IsPipe(Context &context, const string &filename) { if (!filename.empty()) { - auto normalized_file = FileSystem::ExpandPath(filename, opener); + auto normalized_file = FileSystem::ExpandPath(context, filename); struct stat status; if (stat(normalized_file.c_str(), &status) == 0 && (S_ISFIFO(status.st_mode) || S_ISCHR(status.st_mode))) { return true; @@ -127,9 +126,7 @@ static std::wstring ConvertPathToNormalizedAbsolute(const std::wstring &path) { return std::wstring(buf.data(), written); } -static std::wstring NormalizePathAndConvertToUnicode(BaseFileSystem &fs, const string &path, - optional_ptr opener) { - string normalized_path = FileSystem::ExpandPath(path, opener); +static std::wstring NormalizeExpandedPathToUnicode(const string &normalized_path) { std::wstring unicode_path = ConvertPathToUnicode(normalized_path); // We need to get absolute path to check the length. Normalizing it (removing "." and "..", @@ -157,8 +154,21 @@ static std::wstring NormalizePathAndConvertToUnicode(BaseFileSystem &fs, const s return WINDOWS_LOCAL_LONG_PATH_PREFIX + abs_path; } -bool LocalFileSystem::FileExists(const string &filename, optional_ptr opener) { - auto unicode_path = NormalizePathAndConvertToUnicode(*this, filename, opener); +static std::wstring NormalizePathAndConvertToUnicode(BaseFileSystem &fs, const string &path, Context &context) { + return NormalizeExpandedPathToUnicode(FileSystem::ExpandPath(context, path)); +} + +//! Removes a file whose path is already expanded (no Context needed): used when aborting a write +static void RemoveExpandedFile(const string &expanded_path) { + auto unicode_path = NormalizeExpandedPathToUnicode(expanded_path); + if (!DeleteFileW(unicode_path.c_str()) && GetLastError() != ERROR_FILE_NOT_FOUND) { + auto error = LocalFileSystem::GetLastErrorAsString(); + throw IOException("Failed to delete file \"%s\": %s", expanded_path, error); + } +} + +bool LocalFileSystem::FileExists(Context &context, const string &filename) { + auto unicode_path = NormalizePathAndConvertToUnicode(*this, filename, context); const wchar_t *wpath = unicode_path.c_str(); struct _stati64 status; // typos:ignore if (_wstati64(wpath, &status) == 0 && (status.st_mode & S_IFREG)) { @@ -166,8 +176,8 @@ bool LocalFileSystem::FileExists(const string &filename, optional_ptr opener) { - auto unicode_path = NormalizePathAndConvertToUnicode(*this, filename, opener); +bool LocalFileSystem::IsPipe(Context &context, const string &filename) { + auto unicode_path = NormalizePathAndConvertToUnicode(*this, filename, context); const wchar_t *wpath = unicode_path.c_str(); struct _stati64 status; // typos:ignore if (_wstati64(wpath, &status) == 0 && (status.st_mode & _S_IFCHR)) { @@ -204,8 +214,16 @@ static void ApplyLocalFileSystemDelay(optional_ptr db) { #endif } -static void ApplyLocalFileSystemDelay(optional_ptr opener) { - ApplyLocalFileSystemDelay(FileOpener::TryGetDatabase(opener)); +static void ApplyLocalFileSystemDelay(Context &context) { + ApplyLocalFileSystemDelay(&context.GetDatabase()); +} + +//! Removes a file whose path is already expanded (no Context needed): used when aborting a write +static void RemoveExpandedFile(const string &expanded_path) { + if (std::remove(expanded_path.c_str()) != 0 && errno != ENOENT) { + throw IOException({{"errno", std::to_string(errno)}}, "Could not remove file \"%s\": %s", expanded_path, + strerror(errno)); + } } struct UnixFileHandle : public FileHandle { @@ -359,8 +377,8 @@ static void TryAcquireFileLock(BaseFileSystem &fs, int fd, const string &path, F extended_error); } -bool LocalFileSystem::IsPrivateFile(const string &path_p, FileOpener *opener) { - auto path = FileSystem::ExpandPath(path_p, opener); +bool LocalFileSystem::IsPrivateFile(const string &path_p) { + auto path = FileSystem::ExpandPathWithHome(path_p, FileSystem::GetDefaultHomeDirectory()); struct stat st; @@ -378,9 +396,8 @@ bool LocalFileSystem::IsPrivateFile(const string &path_p, FileOpener *opener) { return true; } -unique_ptr LocalFileSystem::OpenFile(const string &path_p, FileOpenFlags flags, - optional_ptr opener) { - auto path = FileSystem::ExpandPath(path_p, opener); +unique_ptr LocalFileSystem::OpenFile(Context &context, const string &path_p, FileOpenFlags flags) { + auto path = FileSystem::ExpandPath(context, path_p); if (flags.Compression() != FileCompressionType::UNCOMPRESSED) { throw NotImplementedException("Unsupported compression type for default file system"); } @@ -435,7 +452,7 @@ unique_ptr LocalFileSystem::OpenFile(const string &path_p, FileOpenF } // Open the file - ApplyLocalFileSystemDelay(opener); + ApplyLocalFileSystemDelay(context); int fd = open(path.c_str(), open_flags, filesec); if (fd == -1) { @@ -464,14 +481,12 @@ unique_ptr LocalFileSystem::OpenFile(const string &path_p, FileOpenF TryAcquireFileLock(*this, fd, path, flags); - auto file_handle = make_uniq(*this, path, fd, flags, FileOpener::TryGetDatabase(opener)); + auto file_handle = make_uniq(*this, path, fd, flags, &context.GetDatabase()); if (flags.OverwriteExistingFile() && StatsInternal(fd, path).file_type == FileType::FILE_TYPE_REGULAR) { Truncate(*file_handle, 0); } - if (opener) { - file_handle->TryAddLogger(*opener); - DUCKDB_LOG_FILE_SYSTEM_OPEN((*file_handle)); - } + file_handle->TryAddLogger(context); + DUCKDB_LOG_FILE_SYSTEM_OPEN((*file_handle)); return std::move(file_handle); } @@ -634,12 +649,12 @@ FileMetadata LocalFileSystem::Stats(FileHandle &handle) { return file_metadata; } -optional LocalFileSystem::GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) { +optional LocalFileSystem::GetStatsIfExists(Context &context, const OpenFileInfo &file) { const auto &path_p = file.path; if (path_p.empty()) { return nullopt; } - auto path = FileSystem::ExpandPath(path_p, opener); + auto path = FileSystem::ExpandPath(context, path_p); struct stat status; if (stat(path.c_str(), &status) != 0) { auto retained_errno = errno; @@ -662,11 +677,11 @@ void LocalFileSystem::Truncate(FileHandle &handle, int64_t new_size) { } } -bool LocalFileSystem::DirectoryExists(const string &directory, optional_ptr opener) { - ApplyLocalFileSystemDelay(opener); +bool LocalFileSystem::DirectoryExists(Context &context, const string &directory) { + ApplyLocalFileSystemDelay(context); if (!directory.empty()) { - auto normalized_dir = FileSystem::ExpandPath(directory, opener); + auto normalized_dir = FileSystem::ExpandPath(context, directory); struct stat status; if (stat(normalized_dir.c_str(), &status) == 0 && S_ISDIR(status.st_mode)) { return true; @@ -676,24 +691,24 @@ bool LocalFileSystem::DirectoryExists(const string &directory, optional_ptr opener) { - CreateDirectoryExtended(directory, {CreateDirectoryMode::SINGLE}, opener); +void LocalFileSystem::CreateDirectory(Context &context, const string &directory) { + CreateDirectoryExtended(context, directory, {CreateDirectoryMode::SINGLE}); } -void LocalFileSystem::CreateDirectoriesRecursive(const string &path, optional_ptr opener) { - CreateDirectoryExtended(path, {CreateDirectoryMode::RECURSIVE}, opener); +void LocalFileSystem::CreateDirectoriesRecursive(Context &context, const string &path) { + CreateDirectoryExtended(context, path, {CreateDirectoryMode::RECURSIVE}); } -bool LocalFileSystem::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener) { +bool LocalFileSystem::CreateDirectoryExtended(Context &context, const string &directory, + const CreateDirectoryOptions &options) { if (options.mode == CreateDirectoryMode::RECURSIVE) { - return BaseFileSystem::CreateDirectoryExtended(directory, options, opener); + return BaseFileSystem::CreateDirectoryExtended(context, directory, options); } if (options.mode != CreateDirectoryMode::SINGLE) { throw InternalException("Unknown CreateDirectoryMode"); } - ApplyLocalFileSystemDelay(opener); - auto normalized_dir = FileSystem::ExpandPath(directory, opener); + ApplyLocalFileSystemDelay(context); + auto normalized_dir = FileSystem::ExpandPath(context, directory); if (mkdir(normalized_dir.c_str(), 0755) == 0) { return true; } @@ -748,20 +763,20 @@ int RemoveDirectoryRecursive(const char *path) { return r; } -void LocalFileSystem::RemoveDirectory(const string &directory, optional_ptr opener) { - RemoveDirectoryExtended(directory, {RemoveDirectoryMode::RECURSIVE}, opener); +void LocalFileSystem::RemoveDirectory(Context &context, const string &directory) { + RemoveDirectoryExtended(context, directory, {RemoveDirectoryMode::RECURSIVE}); } -bool LocalFileSystem::RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener) { +bool LocalFileSystem::RemoveDirectoryExtended(Context &context, const string &directory, + const RemoveDirectoryOptions &options) { if (options.mode == RemoveDirectoryMode::RECURSIVE) { - auto normalized_dir = FileSystem::ExpandPath(directory, opener); + auto normalized_dir = FileSystem::ExpandPath(context, directory); return RemoveDirectoryRecursive(normalized_dir.c_str()) == 0; } if (options.mode != RemoveDirectoryMode::SINGLE) { throw InternalException("Unknown RemoveDirectoryMode"); } - auto normalized_dir = FileSystem::ExpandPath(directory, opener); + auto normalized_dir = FileSystem::ExpandPath(context, directory); if (rmdir(normalized_dir.c_str()) == 0) { return true; } @@ -772,18 +787,17 @@ bool LocalFileSystem::RemoveDirectoryExtended(const string &directory, const Rem strerror(errno)); } -void LocalFileSystem::RemoveFile(const string &filename, optional_ptr opener) { - auto normalized_file = FileSystem::ExpandPath(filename, opener); +void LocalFileSystem::RemoveFile(Context &context, const string &filename) { + auto normalized_file = FileSystem::ExpandPath(context, filename); if (std::remove(normalized_file.c_str()) != 0) { throw IOException({{"errno", std::to_string(errno)}}, "Could not remove file \"%s\": %s", filename, strerror(errno)); } } -bool LocalFileSystem::ListFilesExtended(const string &directory, - const std::function &callback, - optional_ptr opener) { - auto normalized_dir = FileSystem::ExpandPath(directory, opener); +bool LocalFileSystem::ListFilesExtended(Context &context, const string &directory, + const std::function &callback) { + auto normalized_dir = FileSystem::ExpandPath(context, directory); auto dir = opendir(normalized_dir.c_str()); if (!dir) { return false; @@ -864,9 +878,9 @@ void LocalFileSystem::FileSync(FileHandle &handle) { throw IOException("Could not fsync file \"%s\": %s", handle.GetPath(), strerror(errno)); } -void LocalFileSystem::MoveFile(const string &source, const string &target, optional_ptr opener) { - auto normalized_source = FileSystem::ExpandPath(source, opener); - auto normalized_target = FileSystem::ExpandPath(target, opener); +void LocalFileSystem::MoveFile(Context &context, const string &source, const string &target) { + auto normalized_source = FileSystem::ExpandPath(context, source); + auto normalized_target = FileSystem::ExpandPath(context, target); //! FIXME: rename does not guarantee atomicity or overwriting target file if it exists if (rename(normalized_source.c_str(), normalized_target.c_str()) != 0) { throw IOException({{"errno", to_string(errno)}}, "Could not rename file \"%s\" to \"%s\": %s", source, target, @@ -937,8 +951,8 @@ bool LocalFileSystem::IsPathAbsolute(const string &path) { return BaseFileSystem::IsPathAbsolute(path); } -string LocalFileSystem::MakePathAbsolute(const string &path_p, optional_ptr opener) { - auto parsed = Path::FromString(FileSystem::ExpandPath(path_p, opener)); +string LocalFileSystem::MakePathAbsolute(const string &path_p, const string &home_directory) { + auto parsed = Path::FromString(FileSystem::ExpandPathWithHome(path_p, home_directory)); return (parsed.IsAbsolute() ? parsed : Path::FromString(FileSystem::GetWorkingDirectory()).Join(parsed)).ToString(); } @@ -1004,10 +1018,9 @@ void UnixMemoryMappedFile::Close() { } } -unique_ptr LocalFileSystem::MemoryMapFile(const OpenFileInfo &path_info, FileOpenFlags flags, - const MMapOptions &options, - optional_ptr opener) { - auto path = FileSystem::ExpandPath(path_info.path, opener); +unique_ptr LocalFileSystem::MemoryMapFile(Context &context, const OpenFileInfo &path_info, + FileOpenFlags flags, const MMapOptions &options) { + auto path = FileSystem::ExpandPath(context, path_info.path); flags.Verify(); bool open_read = flags.OpenForReading(); @@ -1279,15 +1292,14 @@ static string AdditionalLockInfo(const std::wstring path) { return "File is already open in " + conflict_string; } -bool LocalFileSystem::IsPrivateFile(const string &path_p, FileOpener *opener) { +bool LocalFileSystem::IsPrivateFile(const string &path_p) { // TODO: detect if file is shared in windows return true; } -unique_ptr LocalFileSystem::OpenFile(const string &path_p, FileOpenFlags flags, - optional_ptr opener) { - auto path = FileSystem::ExpandPath(path_p, opener); - auto unicode_path = NormalizePathAndConvertToUnicode(*this, path, opener); +unique_ptr LocalFileSystem::OpenFile(Context &context, const string &path_p, FileOpenFlags flags) { + auto path = FileSystem::ExpandPath(context, path_p); + auto unicode_path = NormalizePathAndConvertToUnicode(*this, path, context); if (flags.Compression() != FileCompressionType::UNCOMPRESSED) { throw NotImplementedException("Unsupported compression type for default file system"); } @@ -1358,13 +1370,13 @@ unique_ptr LocalFileSystem::OpenFile(const string &path_p, FileOpenF auto abs_path = WindowsUtil::UnicodeToUTF8(unicode_path.c_str()); throw IOException("Cannot open file \"%s\": %s%s", abs_path, error, extended_error); } - auto handle = make_uniq(*this, path.c_str(), hFile, flags, FileOpener::TryGetDatabase(opener)); + auto handle = make_uniq(*this, path.c_str(), hFile, flags, &context.GetDatabase()); if (flags.OpenForAppending()) { auto file_size = GetFileSize(*handle); SetFilePointer(*handle, file_size); } - if (opener) { - handle->TryAddLogger(*opener); + { + handle->TryAddLogger(context); DUCKDB_LOG_FILE_SYSTEM_OPEN((*handle)); } return std::move(handle); @@ -1498,8 +1510,8 @@ void LocalFileSystem::Truncate(FileHandle &handle, int64_t new_size) { } } -static DWORD WindowsGetFileAttributes(LocalFileSystem &fs, const string &filename, optional_ptr opener) { - auto unicode_path = NormalizePathAndConvertToUnicode(fs, filename, opener); +static DWORD WindowsGetFileAttributes(LocalFileSystem &fs, const string &filename, Context &context) { + auto unicode_path = NormalizePathAndConvertToUnicode(fs, filename, context); return GetFileAttributesW(unicode_path.c_str()); } @@ -1507,28 +1519,28 @@ static DWORD WindowsGetFileAttributes(const std::wstring &filename) { return GetFileAttributesW(filename.c_str()); } -bool LocalFileSystem::DirectoryExists(const string &directory, optional_ptr opener) { - DWORD attrs = WindowsGetFileAttributes(*this, directory, opener); +bool LocalFileSystem::DirectoryExists(Context &context, const string &directory) { + DWORD attrs = WindowsGetFileAttributes(*this, directory, context); return (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)); } -void LocalFileSystem::CreateDirectory(const string &directory, optional_ptr opener) { - CreateDirectoryExtended(directory, {CreateDirectoryMode::SINGLE}, opener); +void LocalFileSystem::CreateDirectory(Context &context, const string &directory) { + CreateDirectoryExtended(context, directory, {CreateDirectoryMode::SINGLE}); } -void LocalFileSystem::CreateDirectoriesRecursive(const string &path, optional_ptr opener) { - CreateDirectoryExtended(path, {CreateDirectoryMode::RECURSIVE}, opener); +void LocalFileSystem::CreateDirectoriesRecursive(Context &context, const string &path) { + CreateDirectoryExtended(context, path, {CreateDirectoryMode::RECURSIVE}); } -bool LocalFileSystem::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener) { +bool LocalFileSystem::CreateDirectoryExtended(Context &context, const string &directory, + const CreateDirectoryOptions &options) { if (options.mode == CreateDirectoryMode::RECURSIVE) { - return BaseFileSystem::CreateDirectoryExtended(directory, options, opener); + return BaseFileSystem::CreateDirectoryExtended(context, directory, options); } if (options.mode != CreateDirectoryMode::SINGLE) { throw InternalException("Unknown CreateDirectoryMode"); } - auto unicode_path = NormalizePathAndConvertToUnicode(*this, directory, opener); + auto unicode_path = NormalizePathAndConvertToUnicode(*this, directory, context); if (!directory.empty() && CreateDirectoryW(unicode_path.c_str(), NULL)) { return true; } @@ -1545,18 +1557,15 @@ bool LocalFileSystem::CreateDirectoryExtended(const string &directory, const Cre throw IOException("Failed to create directory \"%s\": %s", abs_path, error); } -static void DeleteDirectoryRecursive(BaseFileSystem &fs, string directory, optional_ptr opener) { - fs.ListFiles( - directory, - [&](const string &fname, bool is_directory) { - if (is_directory) { - DeleteDirectoryRecursive(fs, fs.JoinPath(directory, fname), opener); - } else { - fs.RemoveFile(fs.JoinPath(directory, fname), opener); - } - }, - opener.get()); - auto unicode_path = NormalizePathAndConvertToUnicode(fs, directory, opener); +static void DeleteDirectoryRecursive(BaseFileSystem &fs, string directory, Context &context) { + fs.ListFiles(context, directory, [&](const string &fname, bool is_directory) { + if (is_directory) { + DeleteDirectoryRecursive(fs, fs.JoinPath(directory, fname), context); + } else { + fs.RemoveFile(context, fs.JoinPath(directory, fname)); + } + }); + auto unicode_path = NormalizePathAndConvertToUnicode(fs, directory, context); if (!RemoveDirectoryW(unicode_path.c_str())) { auto error = LocalFileSystem::GetLastErrorAsString(); auto abs_path = WindowsUtil::UnicodeToUTF8(unicode_path.c_str()); @@ -1564,27 +1573,27 @@ static void DeleteDirectoryRecursive(BaseFileSystem &fs, string directory, optio } } -void LocalFileSystem::RemoveDirectory(const string &directory, optional_ptr opener) { - RemoveDirectoryExtended(directory, {RemoveDirectoryMode::RECURSIVE}, opener); +void LocalFileSystem::RemoveDirectory(Context &context, const string &directory) { + RemoveDirectoryExtended(context, directory, {RemoveDirectoryMode::RECURSIVE}); } -bool LocalFileSystem::RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener) { +bool LocalFileSystem::RemoveDirectoryExtended(Context &context, const string &directory, + const RemoveDirectoryOptions &options) { if (options.mode == RemoveDirectoryMode::RECURSIVE) { - if (FileExists(directory, opener)) { + if (FileExists(context, directory)) { throw IOException("Attempting to delete directory \"%s\", but it is a file and not a directory!", directory); } - if (!DirectoryExists(directory, opener)) { + if (!DirectoryExists(context, directory)) { return false; } - DeleteDirectoryRecursive(*this, directory, opener); + DeleteDirectoryRecursive(*this, directory, context); return true; } if (options.mode != RemoveDirectoryMode::SINGLE) { throw InternalException("Unknown RemoveDirectoryMode"); } - auto unicode_path = NormalizePathAndConvertToUnicode(*this, directory, opener); + auto unicode_path = NormalizePathAndConvertToUnicode(*this, directory, context); if (RemoveDirectoryW(unicode_path.c_str())) { return true; } @@ -1596,8 +1605,8 @@ bool LocalFileSystem::RemoveDirectoryExtended(const string &directory, const Rem throw IOException("Failed to remove empty directory \"%s\": %s", abs_path, GetLastErrorAsString()); } -void LocalFileSystem::RemoveFile(const string &filename, optional_ptr opener) { - auto unicode_path = NormalizePathAndConvertToUnicode(*this, filename, opener); +void LocalFileSystem::RemoveFile(Context &context, const string &filename) { + auto unicode_path = NormalizePathAndConvertToUnicode(*this, filename, context); if (!DeleteFileW(unicode_path.c_str())) { auto error = LocalFileSystem::GetLastErrorAsString(); auto abs_path = WindowsUtil::UnicodeToUTF8(unicode_path.c_str()); @@ -1605,10 +1614,9 @@ void LocalFileSystem::RemoveFile(const string &filename, optional_ptr &callback, - optional_ptr opener) { - auto unicode_path = NormalizePathAndConvertToUnicode(*this, directory, opener); +bool LocalFileSystem::ListFilesExtended(Context &context, const string &directory, + const std::function &callback) { + auto unicode_path = NormalizePathAndConvertToUnicode(*this, directory, context); // Open a handle to the directory itself so we can use GetFileInformationByHandleEx, // which returns FILE_ID_BOTH_DIR_INFO entries that include the per-file FileId @@ -1700,9 +1708,9 @@ static bool TryMoveFileWithPosixSemantics(HANDLE source_handle, const std::wstri return SetFileInformationByHandle(source_handle, file_rename_info_ex, rename_info, rename_info_size_dw); } -void LocalFileSystem::MoveFile(const string &source, const string &target, optional_ptr opener) { - auto source_unicode = NormalizePathAndConvertToUnicode(*this, source, opener); - auto target_unicode = NormalizePathAndConvertToUnicode(*this, target, opener); +void LocalFileSystem::MoveFile(Context &context, const string &source, const string &target) { + auto source_unicode = NormalizePathAndConvertToUnicode(*this, source, context); + auto target_unicode = NormalizePathAndConvertToUnicode(*this, target, context); // FileRenameInfoEx renames the file identified by a handle opened with DELETE access. // See https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_rename_info @@ -1747,12 +1755,12 @@ FileMetadata LocalFileSystem::Stats(FileHandle &handle) { return file_metadata; } -optional LocalFileSystem::GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) { +optional LocalFileSystem::GetStatsIfExists(Context &context, const OpenFileInfo &file) { const auto &path_p = file.path; if (path_p.empty()) { return nullopt; } - auto unicode_path = NormalizePathAndConvertToUnicode(*this, path_p, opener); + auto unicode_path = NormalizePathAndConvertToUnicode(*this, path_p, context); auto raw_handle = CreateFileW(unicode_path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (raw_handle == INVALID_HANDLE_VALUE) { @@ -1818,8 +1826,8 @@ bool LocalFileSystem::IsPathAbsolute(const string &path) { return false; } -string LocalFileSystem::MakePathAbsolute(const string &path_p, optional_ptr opener) { - auto path = FileSystem::ExpandPath(path_p, opener); +string LocalFileSystem::MakePathAbsolute(const string &path_p, const string &home_directory) { + auto path = FileSystem::ExpandPathWithHome(path_p, home_directory); auto parsed = Path::FromString(path); if (parsed.IsAbsolute()) { // already absolute - nothing to do @@ -1904,10 +1912,9 @@ void WindowsMemoryMappedFile::Close() { } } -unique_ptr LocalFileSystem::MemoryMapFile(const OpenFileInfo &path_info, FileOpenFlags flags, - const MMapOptions &options, - optional_ptr opener) { - auto path = FileSystem::ExpandPath(path_info.path, opener); +unique_ptr LocalFileSystem::MemoryMapFile(Context &context, const OpenFileInfo &path_info, + FileOpenFlags flags, const MMapOptions &options) { + auto path = FileSystem::ExpandPath(context, path_info.path); flags.Verify(); bool open_read = flags.OpenForReading(); @@ -2020,7 +2027,7 @@ void LocalFileSystem::AbortFileWrite(FileHandle &handle) { auto path = handle.GetPath(); handle.Close(); if (remove_path) { - TryRemoveFile(path, nullptr); + RemoveExpandedFile(path); } } @@ -2040,13 +2047,17 @@ bool LocalFileSystem::OnDiskFile(FileHandle &handle) { return true; } -string LocalFileSystem::CanonicalizePath(const string &input, optional_ptr opener) { +string LocalFileSystem::CanonicalizePath(Context &context, const string &input) { + return CanonicalizePathWithHome(input, FileSystem::GetHomeDirectory(context)); +} + +string LocalFileSystem::CanonicalizePathWithHome(const string &input, const string &home_directory) { auto path_sep = PathSeparator(input); if (path_sep.size() != 1) { throw InternalException("path separator can only be a single byte for local file systems"); } // make the path absolute - string path = MakePathAbsolute(input, opener); + string path = MakePathAbsolute(input, home_directory); string current = path; string remainder; @@ -2067,7 +2078,7 @@ string LocalFileSystem::CanonicalizePath(const string &input, optional_ptr LocalFileSystem::FetchFileWithoutGlob(const string &path, optional_ptr opener, - bool absolute_path) { +vector LocalFileSystem::FetchFileWithoutGlob(const string &path, Context &context, bool absolute_path) { vector result; // a regular file comes with its type, size, modification time and version tag, as from a glob auto add_file = [&](const string &file_path) { OpenFileInfo info(file_path); - auto file_metadata = GetStatsIfExists(info, opener); + auto file_metadata = GetStatsIfExists(context, info); if (file_metadata) { info.extended_info = make_shared_ptr(); auto &options = info.extended_info->options; @@ -2187,20 +2197,20 @@ vector LocalFileSystem::FetchFileWithoutGlob(const string &path, o } result.push_back(std::move(info)); }; - if (FileExists(path, opener)) { + if (FileExists(context, path)) { add_file(path); - } else if (IsPipe(path, opener)) { + } else if (IsPipe(context, path)) { result.emplace_back(path); } else if (!absolute_path) { Value value; - if (opener && opener->TryGetCurrentSetting("file_search_path", value)) { + if (context.TryGetCurrentSetting("file_search_path", value)) { auto search_paths_str = value.ToString(); vector search_paths = StringUtil::Split(search_paths_str, ','); for (const auto &search_path : search_paths) { auto joined_path = JoinPath(search_path, path); - if (FileExists(joined_path, opener)) { + if (FileExists(context, joined_path)) { add_file(joined_path); - } else if (IsPipe(joined_path, opener)) { + } else if (IsPipe(context, joined_path)) { result.emplace_back(joined_path); } } @@ -2241,10 +2251,10 @@ struct ExpandDirectory { } }; -static void CrawlDirectoryLevel(LocalFileSystem &fs, optional_ptr opener, const string &path, +static void CrawlDirectoryLevel(Context &context, LocalFileSystem &fs, const string &path, optional_ptr> files, std::priority_queue &directories, idx_t split_index) { - auto callback = [&](OpenFileInfo &info) { + fs.ListFiles(context, path, [&](OpenFileInfo &info) { info.path = fs.JoinPath(path, info.path); if (IsSymbolicLink(info.path)) { return; @@ -2255,13 +2265,12 @@ static void CrawlDirectoryLevel(LocalFileSystem &fs, optional_ptr op } else if (files) { files->push_back(std::move(info)); } - }; - fs.ListFiles(path, callback, opener); + }); } -static void GlobFilesInternal(LocalFileSystem &fs, optional_ptr opener, const string &path, - const string &glob, bool match_directory, vector &result) { - auto callback = [&](OpenFileInfo &info) { +static void GlobFilesInternal(Context &context, LocalFileSystem &fs, const string &path, const string &glob, + bool match_directory, vector &result) { + fs.ListFiles(context, path, [&](OpenFileInfo &info) { bool is_directory = FileSystem::IsDirectory(info); if (is_directory != match_directory) { return; @@ -2270,13 +2279,12 @@ static void GlobFilesInternal(LocalFileSystem &fs, optional_ptr open info.path = fs.JoinPath(path, info.path); result.push_back(std::move(info)); } - }; - fs.ListFiles(path, callback, opener); + }); } struct LocalGlobResult : public LazyMultiFileList { public: - LocalGlobResult(LocalFileSystem &fs, const string &path, FileGlobOptions options, optional_ptr opener); + LocalGlobResult(LocalFileSystem &fs, const string &path, FileGlobOptions options, Context &context); protected: bool ExpandNextPath() const override; @@ -2284,17 +2292,15 @@ struct LocalGlobResult : public LazyMultiFileList { private: LocalFileSystem &fs; string path; - optional_ptr opener; + Context &context; vector splits; bool absolute_path = false; mutable std::priority_queue expand_directories; mutable bool finished = false; }; -LocalGlobResult::LocalGlobResult(LocalFileSystem &fs, const string &path_p, FileGlobOptions options_p, - optional_ptr opener) - : LazyMultiFileList(FileOpener::TryGetContext(opener)), fs(fs), path(FileSystem::ExpandPath(path_p, opener)), - opener(opener) { +LocalGlobResult::LocalGlobResult(LocalFileSystem &fs, const string &path_p, FileGlobOptions options_p, Context &context) + : LazyMultiFileList(context), fs(fs), path(FileSystem::ExpandPath(context, path_p)), context(context) { if (path.empty()) { finished = true; return; @@ -2317,13 +2323,13 @@ LocalGlobResult::LocalGlobResult(LocalFileSystem &fs, const string &path_p, File } if (!splits.empty() && splits[0].path == "~") { // starts with home directory - auto home_directory = FileSystem::GetHomeDirectory(opener); + auto home_directory = FileSystem::GetHomeDirectory(context); if (!home_directory.empty()) { absolute_path = true; splits[0].path = home_directory; D_ASSERT(path[0] == '~'); if (!FileSystem::HasGlob(path)) { - expanded_files = fs.FetchFileWithoutGlob(home_directory + path.substr(1), opener, absolute_path); + expanded_files = fs.FetchFileWithoutGlob(home_directory + path.substr(1), context, absolute_path); finished = true; return; } @@ -2332,7 +2338,7 @@ LocalGlobResult::LocalGlobResult(LocalFileSystem &fs, const string &path_p, File // Check if the path has a glob at all if (!FileSystem::HasGlob(path)) { // no glob: return only the file (if it exists or is a pipe) - expanded_files = fs.FetchFileWithoutGlob(path, opener, absolute_path); + expanded_files = fs.FetchFileWithoutGlob(path, context, absolute_path); finished = true; return; } @@ -2345,7 +2351,7 @@ LocalGlobResult::LocalGlobResult(LocalFileSystem &fs, const string &path_p, File } else { // If file_search_path is set, use those paths as the first glob elements Value value; - if (opener && opener->TryGetCurrentSetting("file_search_path", value)) { + if (context.TryGetCurrentSetting("file_search_path", value)) { auto search_paths_str = value.ToString(); auto search_paths = StringUtil::Split(search_paths_str, ','); for (const auto &search_path : search_paths) { @@ -2370,7 +2376,7 @@ bool LocalGlobResult::ExpandNextPath() const { if (expanded_files.empty()) { // no result found that matches the glob // last ditch effort: search the path as a string literal - expanded_files = fs.FetchFileWithoutGlob(path, opener, absolute_path); + expanded_files = fs.FetchFileWithoutGlob(path, context, absolute_path); } finished = true; return false; @@ -2400,7 +2406,7 @@ bool LocalGlobResult::ExpandNextPath() const { if (is_last_component) { // last component - we are emitting a result here auto filename = fs.JoinPath(current_path, next_component); - if (fs.FileExists(filename, opener) || fs.DirectoryExists(filename, opener)) { + if (fs.FileExists(context, filename) || fs.DirectoryExists(context, filename)) { expanded_files.emplace_back(std::move(filename)); } } else { @@ -2414,23 +2420,23 @@ bool LocalGlobResult::ExpandNextPath() const { if (is_last_component) { // the crawl is the last component - we are looking for files in this directory // any directories we encounter are added to the expand directories - CrawlDirectoryLevel(fs, opener, current_path, expanded_files, expand_directories, split_index); + CrawlDirectoryLevel(context, fs, current_path, expanded_files, expand_directories, split_index); } else { // not the last crawl // ** also matches the current directory (i.e. dir/**/file.parquet also matches dir/file.parquet) expand_directories.emplace(current_path, split_index + 1); // now crawl the contents of this directory - but don't add any files we find - CrawlDirectoryLevel(fs, opener, current_path, nullptr, expand_directories, split_index); + CrawlDirectoryLevel(context, fs, current_path, nullptr, expand_directories, split_index); } } else { // glob this directory according to the next component if (is_last_component) { // last component - match files and place them in the result - GlobFilesInternal(fs, opener, current_path, next_component, false, expanded_files); + GlobFilesInternal(context, fs, current_path, next_component, false, expanded_files); } else { // not the last component - match directories and add to expansion list vector child_directories; - GlobFilesInternal(fs, opener, current_path, next_component, true, child_directories); + GlobFilesInternal(context, fs, current_path, next_component, true, child_directories); for (auto &file : child_directories) { expand_directories.emplace(std::move(file.path), split_index + 1); } @@ -2440,9 +2446,9 @@ bool LocalGlobResult::ExpandNextPath() const { return true; } -unique_ptr LocalFileSystem::GlobFilesExtended(const string &path, const FileGlobInput &input, - optional_ptr opener) { - return make_uniq(*this, path, FileGlobOptions::ALLOW_EMPTY, opener); +unique_ptr LocalFileSystem::GlobFilesExtended(Context &context, const string &path, + const FileGlobInput &input) { + return make_uniq(*this, path, FileGlobOptions::ALLOW_EMPTY, context); } } // namespace duckdb diff --git a/src/duckdb/src/common/memory_mapped_file.cpp b/src/duckdb/src/common/memory_mapped_file.cpp index 24f2ebf1a..bb67de8be 100644 --- a/src/duckdb/src/common/memory_mapped_file.cpp +++ b/src/duckdb/src/common/memory_mapped_file.cpp @@ -33,9 +33,9 @@ data_ptr_t MemoryMappedFile::GetDataMutable(idx_t location, idx_t nr_bytes) { } unique_ptr -BaseFileSystem::MemoryMapFile(const OpenFileInfo &path, +BaseFileSystem::MemoryMapFile(Context &context, const OpenFileInfo &path, FileOpenFlags flags, // NOLINT: signature fixed by virtual API - const MMapOptions &options, optional_ptr opener) { + const MMapOptions &options) { throw NotImplementedException("Memory-mapped file access is not supported by this file system (%s) for path \"%s\"", GetName(), path.path); } diff --git a/src/duckdb/src/common/multi_file/table_function_multi_file.cpp b/src/duckdb/src/common/multi_file/table_function_multi_file.cpp index 7884d177b..6559eef88 100644 --- a/src/duckdb/src/common/multi_file/table_function_multi_file.cpp +++ b/src/duckdb/src/common/multi_file/table_function_multi_file.cpp @@ -76,6 +76,10 @@ bool TableFunctionFileReader::UseCastMap() const { return settings.supports_cast_map; } +bool TableFunctionFileReader::SupportsDeletionFilter() const { + return settings.supports_deletion_filter; +} + void TableFunctionFileReader::BindFunction(ClientContext &context, const TableFunctionFileReaderOptions &options, const MultiFileOptions &file_options, bool schema_only, optional_ptr file_bind_data) { 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 index 98f79dd5b..0afbcffe6 100644 --- 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 @@ -83,6 +83,16 @@ TableFunctionMultiFileList::TableFunctionMultiFileList(ClientContext &context_p, } } +TableFunctionMultiFileList::TableFunctionMultiFileList(ClientContext &context_p, TableFunction function_p, + unique_ptr bind_data_p, + vector return_types_p) + : LazyMultiFileList(&context_p.GetContext()), context(context_p), function(std::move(function_p)), + bind_data(std::move(bind_data_p)), return_types(std::move(return_types_p)) { + if (!function.function) { + throw BinderException("Table function %s cannot provide a file list", function.name); + } +} + TableFunctionMultiFileList::~TableFunctionMultiFileList() { } diff --git a/src/duckdb/src/common/multi_file/table_function_query_filter.cpp b/src/duckdb/src/common/multi_file/table_function_query_filter.cpp new file mode 100644 index 000000000..d9821d683 --- /dev/null +++ b/src/duckdb/src/common/multi_file/table_function_query_filter.cpp @@ -0,0 +1,304 @@ +#include "duckdb/common/multi_file/table_function_query_filter.hpp" + +#include "duckdb/catalog/catalog_search_path.hpp" +#include "duckdb/common/algorithm.hpp" +#include "duckdb/common/multi_file/base_file_reader.hpp" +#include "duckdb/common/bit_utils.hpp" +#include "duckdb/common/exception.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/common/types/data_chunk.hpp" +#include "duckdb/common/types/selection_vector.hpp" +#include "duckdb/common/types/value.hpp" +#include "duckdb/common/vector/vector_iterator.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/client_data.hpp" +#include "duckdb/main/connection.hpp" +#include "duckdb/main/database.hpp" +#include "duckdb/main/prepared_statement.hpp" +#include "duckdb/main/query_result_stream.hpp" +#include "duckdb/main/valid_checker.hpp" +#include "duckdb/transaction/meta_transaction.hpp" + +#include + +namespace duckdb { + +constexpr const char *TableFunctionQueryFilter::FILTER_QUERY_OPTION; + +//! A filter query can scan files with filter queries of their own - bound the nesting before it exhausts the stack +static constexpr idx_t MAX_FILTER_QUERY_DEPTH = 8; + +unique_ptr TableFunctionQueryFilter::TryCreate(ClientContext &context, BaseFileReader &reader) { + auto &file = reader.file; + if (!HasFilterQuery(file)) { + return nullptr; + } + auto &query = file.extended_info->options.at(FILTER_QUERY_OPTION); + if (query.type().id() != LogicalTypeId::VARCHAR) { + throw InvalidInputException("The %s option of file %s must be a VARCHAR, not %s", FILTER_QUERY_OPTION, + file.path, query.type().ToString()); + } + if (!reader.SupportsDeletionFilter()) { + throw NotImplementedException("The %s option of file %s is not supported by the %s reader", FILTER_QUERY_OPTION, + file.path, reader.GetReaderType()); + } + auto result = make_uniq(); + result->ReadFilterQuery(context, StringValue::Get(query), file.path); + return std::move(result); +} + +//! Leaves the transaction of the caller that a filter query joined - without a vote to roll it back, the filter query +//! only reads +static void LeaveCallerTransaction(ClientContext &inner) { + inner.Destroy(); + if (!inner.transaction.HasActiveTransaction()) { + return; + } + if (ValidChecker::IsInvalidated(inner.transaction.ActiveTransaction())) { + inner.transaction.Rollback(nullptr); + } else { + inner.transaction.Commit(); + } +} + +void TableFunctionQueryFilter::ReadFilterQuery(ClientContext &context, const string &query, const string &path) { + if (context.internal_depth + 1 > MAX_FILTER_QUERY_DEPTH) { + throw InvalidInputException("Filter queries are nested too deeply (maximum depth %llu) - does the filter query " + "of file %s scan the file itself?", + MAX_FILTER_QUERY_DEPTH, path); + } + if (!context.transaction.HasActiveTransaction()) { + throw InternalException("The filter query of file %s is read outside of a transaction", path); + } + // the scan holds the lock of its context: run the query on an internal connection that is interrupted with the + // caller, and that joins the transaction of the caller so that it sees what the caller sees + auto connection = Connection::CreateInternal(context); + auto &inner = *connection.context; + // resolve names as the caller does (USE, SET schema, SET search_path), unqualified entries included + auto &caller_paths = ClientData::Get(context).catalog_search_path->GetSetPaths(); + ClientData::Get(inner).catalog_search_path = make_uniq(inner, caller_paths); + ErrorData error; + try { + auto statements = connection.ExtractStatements(query); + if (statements.size() != 1 || statements[0]->type != StatementType::SELECT_STATEMENT) { + throw InvalidInputException("The filter query must be a single SELECT statement"); + } + // a failing filter query affects the transaction of the caller as a failing statement of the caller would + inner.transaction.InheritTransaction(context); + auto prepared = connection.Prepare(std::move(statements[0])); + if (prepared->HasError()) { + prepared->GetErrorObject().Throw(); + } + if (!prepared->GetStatementProperties().IsReadOnly()) { + throw InvalidInputException("The filter query must not modify a database"); + } + vector values; + QueryResultStream<> stream(prepared->Submit(values)); + if (stream.HasError()) { + stream.GetErrorObject().Throw(); + } + auto &types = stream.GetTypes(); + if (types.size() != 3 || types[0].id() != LogicalTypeId::BIGINT || types[1].id() != LogicalTypeId::BIGINT || + types[2].id() != LogicalTypeId::BIT) { + throw InvalidInputException("The filter query must return (row_start BIGINT, row_end BIGINT, bits BIT)"); + } + while (auto chunk = stream.Fetch()) { + if (chunk->size() == 0) { + break; + } + AddRows(*chunk); + } + if (stream.HasError()) { + stream.GetErrorObject().Throw(); + } + } catch (std::exception &ex) { + error = ErrorData(ex); + } + LeaveCallerTransaction(inner); + if (error.HasError()) { + error.Throw(StringUtil::Format("Failed to read the filter query of file %s: ", path)); + } + Finalize(); +} + +static uint8_t ReverseBits(uint8_t value) { + value = static_cast(((value & 0xF0) >> 4) | ((value & 0x0F) << 4)); + value = static_cast(((value & 0xCC) >> 2) | ((value & 0x33) << 2)); + value = static_cast(((value & 0xAA) >> 1) | ((value & 0x55) << 1)); + return value; +} + +void TableFunctionQueryFilter::AddRows(DataChunk &chunk) { + auto starts = chunk.data[0].Values(); + auto ends = chunk.data[1].Values(); + auto bitmaps = chunk.data[2].Values(); + for (idx_t i = 0; i < chunk.size(); i++) { + auto row_start = starts[i]; + auto row_end = ends[i]; + auto bitmap = bitmaps[i]; + if (bitmap.IsValid()) { + if (row_start.IsValid() && row_start.GetValue() < 0) { + throw InvalidInputException("The filter query returns a bitmap that starts before the file"); + } + auto bits = bitmap.GetValue(); + auto window_start = row_start.IsValid() ? NumericCast(row_start.GetValue()) : 0; + AddWindow(window_start, bits.GetData(), bits.GetSize()); + continue; + } + idx_t range_start = 0; + idx_t range_end = NumericLimits::Maximum(); + if (row_start.IsValid() && row_start.GetValue() > 0) { + range_start = NumericCast(row_start.GetValue()); + } + if (row_end.IsValid()) { + if (row_end.GetValue() <= 0) { + continue; + } + range_end = NumericCast(row_end.GetValue()); + } + if (range_start < range_end) { + scan_ranges.emplace_back(range_start, range_end); + } + } +} + +void TableFunctionQueryFilter::AddWindowBits(idx_t row_start, uint64_t bits, idx_t bit_count) { + auto word_index = row_start / 64; + auto shift = row_start % 64; + auto add_to_word = [&](idx_t index, uint64_t word_bits) { + if (!scan_words.empty() && scan_words.back().index == index) { + scan_words.back().bits |= word_bits; + } else { + scan_words.push_back(ScanWord {index, word_bits}); + } + }; + add_to_word(word_index, bits << shift); + if (shift + bit_count > 64) { + add_to_word(word_index + 1, bits >> (64 - shift)); + } +} + +void TableFunctionQueryFilter::AddWindow(idx_t window_start, const char *data, idx_t size) { + if (size < 2) { + return; + } + auto bytes = reinterpret_cast(data); + // the first byte is the number of padding bits - the most significant bits of the first byte that follows + auto padding = idx_t(bytes[0]); + idx_t byte_idx = 0; + if (padding == 0 && window_start % 64 == 0) { + // the bytes are 8 words of rows when they start at a word: reverse the bits of every byte + for (; byte_idx + 8 < size; byte_idx += 8) { + uint64_t word; + memcpy(&word, bytes + 1 + byte_idx, sizeof(word)); + word = ((word & 0xF0F0F0F0F0F0F0F0ULL) >> 4) | ((word & 0x0F0F0F0F0F0F0F0FULL) << 4); + word = ((word & 0xCCCCCCCCCCCCCCCCULL) >> 2) | ((word & 0x3333333333333333ULL) << 2); + word = ((word & 0xAAAAAAAAAAAAAAAAULL) >> 1) | ((word & 0x5555555555555555ULL) << 1); + if (word != 0) { + scan_words.push_back(ScanWord {window_start / 64 + byte_idx / 8, word}); + } + } + } + for (; byte_idx + 1 < size; byte_idx++) { + auto value = bytes[1 + byte_idx]; + if (byte_idx == 0) { + value = static_cast(value & (0xFF >> padding)); + } + if (value == 0) { + continue; + } + // the bit of the highest significance is the first row of the byte + uint64_t bits = ReverseBits(value); + if (byte_idx == 0) { + AddWindowBits(window_start, bits >> padding, 8 - padding); + } else { + AddWindowBits(window_start + byte_idx * 8 - padding, bits, 8); + } + } +} + +void TableFunctionQueryFilter::Finalize() { + sort(scan_ranges.begin(), scan_ranges.end()); + vector> merged_ranges; + for (auto &range : scan_ranges) { + if (!merged_ranges.empty() && range.first <= merged_ranges.back().second) { + merged_ranges.back().second = MaxValue(merged_ranges.back().second, range.second); + continue; + } + merged_ranges.push_back(range); + } + scan_ranges = std::move(merged_ranges); + + sort(scan_words.begin(), scan_words.end(), + [](const ScanWord &lhs, const ScanWord &rhs) { return lhs.index < rhs.index; }); + vector merged_words; + for (auto &word : scan_words) { + if (!merged_words.empty() && merged_words.back().index == word.index) { + merged_words.back().bits |= word.bits; + } else if (word.bits != 0) { + merged_words.push_back(word); + } + } + scan_words = std::move(merged_words); +} + +//! The bits [begin, end) of a word, where begin < end <= 64 +static uint64_t BitRange(idx_t begin, idx_t end) { + auto upper = end == 64 ? ~uint64_t(0) : ((uint64_t(1) << end) - 1); + return upper & ~((uint64_t(1) << begin) - 1); +} + +idx_t TableFunctionQueryFilter::Filter(row_t start_row_index, idx_t count, SelectionVector &result_sel) { + auto start = NumericCast(start_row_index); + auto end = start + count; + auto range = std::upper_bound(scan_ranges.begin(), scan_ranges.end(), start, + [](idx_t row, const pair &r) { return row < r.second; }); + if (range != scan_ranges.end() && range->first <= start && range->second >= end) { + // one range scans all of the rows + return count; + } + // the rows that are scanned, as a bitmap of the rows of this vector + static constexpr idx_t MAX_WORDS = STANDARD_VECTOR_SIZE / 64 + 2; + uint64_t scanned[MAX_WORDS] = {}; + auto first_word = start / 64; + auto last_word = (end - 1) / 64; + D_ASSERT(last_word - first_word < MAX_WORDS); + auto base = first_word * 64; + for (; range != scan_ranges.end() && range->first < end; ++range) { + auto range_start = MaxValue(range->first, start) - base; + auto range_end = MinValue(range->second, end) - base; + for (auto word = range_start / 64; word <= (range_end - 1) / 64; word++) { + scanned[word] |= BitRange(MaxValue(range_start, word * 64) - word * 64, + MinValue(range_end, (word + 1) * 64) - word * 64); + } + } + auto scan_word = std::lower_bound(scan_words.begin(), scan_words.end(), first_word, + [](const ScanWord &word, idx_t index) { return word.index < index; }); + for (; scan_word != scan_words.end() && scan_word->index <= last_word; ++scan_word) { + scanned[scan_word->index - first_word] |= scan_word->bits; + } + // only the rows of this vector + idx_t scan_count = 0; + for (auto word = first_word; word <= last_word; word++) { + auto &bits = scanned[word - first_word]; + bits &= + BitRange(MaxValue(start, word * 64) - word * 64, MinValue(end, (word + 1) * 64) - word * 64); + scan_count += std::bitset<64>(bits).count(); + } + if (scan_count == count || scan_count == 0) { + return scan_count; + } + result_sel.Initialize(STANDARD_VECTOR_SIZE); + idx_t result_count = 0; + for (auto word = first_word; word <= last_word; word++) { + auto bits = scanned[word - first_word]; + while (bits) { + auto bit = CountZeros::Trailing(bits); + result_sel.set_index(result_count++, word * 64 + bit - start); + bits &= bits - 1; + } + } + return result_count; +} + +} // namespace duckdb diff --git a/src/duckdb/src/common/pipe_file_system.cpp b/src/duckdb/src/common/pipe_file_system.cpp index b78955848..ddf602341 100644 --- a/src/duckdb/src/common/pipe_file_system.cpp +++ b/src/duckdb/src/common/pipe_file_system.cpp @@ -15,7 +15,7 @@ struct PipeFileSystemHolder { class PipeFile : private PipeFileSystemHolder, public FileHandle { public: - explicit PipeFile(QueryContext context_p, unique_ptr child_handle_p) + explicit PipeFile(Context &context_p, unique_ptr child_handle_p) : FileHandle(pipe_fs, child_handle_p->path, child_handle_p->GetFlags()), child_handle(std::move(child_handle_p)), context(context_p) { } @@ -30,7 +30,7 @@ class PipeFile : private PipeFileSystemHolder, public FileHandle { } private: - QueryContext context; + Context &context; }; int64_t PipeFile::ReadChunk(void *buffer, int64_t nr_bytes) { @@ -67,7 +67,7 @@ timestamp_t PipeFileSystem::GetLastModifiedTime(FileHandle &handle) { void PipeFileSystem::FileSync(FileHandle &handle) { } -unique_ptr PipeFileSystem::OpenPipe(QueryContext context, unique_ptr handle) { +unique_ptr PipeFileSystem::OpenPipe(Context &context, unique_ptr handle) { return make_uniq(context, std::move(handle)); } diff --git a/src/duckdb/src/common/query_context.cpp b/src/duckdb/src/common/query_context.cpp deleted file mode 100644 index 1f1ba6b1d..000000000 --- a/src/duckdb/src/common/query_context.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include "duckdb/common/query_context.hpp" - -#include "duckdb/main/client_context.hpp" - -namespace duckdb { - -QueryContext::QueryContext(optional_ptr client_context_p) : client_context(client_context_p) { - if (client_context) { - context = &client_context->GetContext(); - } -} - -QueryContext::QueryContext(ClientContext &client_context_p) - : context(&client_context_p.GetContext()), client_context(&client_context_p) { -} - -} // namespace duckdb diff --git a/src/duckdb/src/common/radix_partitioning.cpp b/src/duckdb/src/common/radix_partitioning.cpp index 6dcd52d05..3d61d5d6f 100644 --- a/src/duckdb/src/common/radix_partitioning.cpp +++ b/src/duckdb/src/common/radix_partitioning.cpp @@ -152,7 +152,7 @@ void RadixPartitionedColumnData::ComputePartitionIndices(PartitionedColumnDataAp RadixPartitionedTupleData::RadixPartitionedTupleData(BufferManager &buffer_manager, shared_ptr layout_ptr, const MemoryTag tag, const idx_t radix_bits_p, const idx_t hash_col_idx_p, - QueryContext context) + Context &context) : PartitionedTupleData(PartitionedTupleDataType::RADIX, buffer_manager, layout_ptr, tag, context), radix_bits(radix_bits_p), hash_col_idx(hash_col_idx_p) { D_ASSERT(radix_bits <= RadixPartitioning::MAX_RADIX_BITS); diff --git a/src/duckdb/src/common/serializer/buffered_file_reader.cpp b/src/duckdb/src/common/serializer/buffered_file_reader.cpp index 271ab0195..95ee7111c 100644 --- a/src/duckdb/src/common/serializer/buffered_file_reader.cpp +++ b/src/duckdb/src/common/serializer/buffered_file_reader.cpp @@ -22,10 +22,6 @@ BufferedFileReader::BufferedFileReader(FileSystem &fs, unique_ptr ha } void BufferedFileReader::ReadData(data_ptr_t target_buffer, uint64_t read_size) { - ReadData(QueryContext(), target_buffer, read_size); -} - -void BufferedFileReader::ReadData(QueryContext context, data_ptr_t target_buffer, uint64_t read_size) { // first copy anything we can from the buffer data_ptr_t end_ptr = target_buffer + read_size; while (true) { diff --git a/src/duckdb/src/common/serializer/buffered_file_writer.cpp b/src/duckdb/src/common/serializer/buffered_file_writer.cpp index f7533e2ec..6f65cd673 100644 --- a/src/duckdb/src/common/serializer/buffered_file_writer.cpp +++ b/src/duckdb/src/common/serializer/buffered_file_writer.cpp @@ -11,8 +11,8 @@ namespace duckdb { const FileOpenFlags BufferedFileWriter::DEFAULT_OPEN_FLAGS = FileOpenFlags(FileOpenFlags::FILE_FLAGS_WRITE | FileOpenFlags::FILE_FLAGS_FILE_CREATE); -BufferedFileWriter::BufferedFileWriter(FileSystem &fs, const string &path_p, const FileOpenFlags &open_flags, - QueryContext context_p) +BufferedFileWriter::BufferedFileWriter(FileSystem &fs, Context &context_p, const string &path_p, + const FileOpenFlags &open_flags) : fs(fs), path(path_p), data(make_unsafe_uniq_array_uninitialized(FILE_BUFFER_SIZE)), offset(0), total_written(0), context(context_p) { handle = fs.OpenFile(path, open_flags | FileLockType::WRITE_LOCK); diff --git a/src/duckdb/src/common/serializer/memory_stream.cpp b/src/duckdb/src/common/serializer/memory_stream.cpp index 277b94460..1962b7cf9 100644 --- a/src/duckdb/src/common/serializer/memory_stream.cpp +++ b/src/duckdb/src/common/serializer/memory_stream.cpp @@ -79,10 +79,6 @@ void MemoryStream::GrowCapacity(idx_t write_size) { } void MemoryStream::ReadData(data_ptr_t destination, idx_t read_size) { - ReadData(QueryContext(), destination, read_size); -} - -void MemoryStream::ReadData(QueryContext context, data_ptr_t destination, idx_t read_size) { if (position + read_size > capacity) { throw SerializationException("Failed to deserialize: not enough data in buffer to fulfill read request"); } diff --git a/src/duckdb/src/common/types/row/integer_partitioned_tuple_data.cpp b/src/duckdb/src/common/types/row/integer_partitioned_tuple_data.cpp index f6485fe9f..a9cf2bc51 100644 --- a/src/duckdb/src/common/types/row/integer_partitioned_tuple_data.cpp +++ b/src/duckdb/src/common/types/row/integer_partitioned_tuple_data.cpp @@ -12,7 +12,7 @@ namespace duckdb { IntegerPartitionedTupleData::IntegerPartitionedTupleData(BufferManager &buffer_manager, shared_ptr layout_ptr, const MemoryTag tag, const idx_t key_col_idx_p, const Value &min_value_p, - const idx_t value_count_p, QueryContext context) + const idx_t value_count_p, Context &context) : PartitionedTupleData(PartitionedTupleDataType::INTEGER, buffer_manager, layout_ptr, tag, context), key_col_idx(key_col_idx_p), min_value(min_value_p), value_count(value_count_p) { D_ASSERT(key_col_idx < layout.GetTypes().size()); diff --git a/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp b/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp index d89d6cf52..326524b0a 100644 --- a/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp +++ b/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp @@ -11,7 +11,7 @@ namespace duckdb { PartitionedTupleData::PartitionedTupleData(PartitionedTupleDataType type_p, BufferManager &buffer_manager_p, shared_ptr &layout_ptr_p, MemoryTag tag_p, - QueryContext context_p) + Context &context_p) : type(type_p), buffer_manager(buffer_manager_p), context(context_p), stl_allocator(make_shared_ptr(buffer_manager.GetBufferAllocator())), layout_ptr(layout_ptr_p), layout(*layout_ptr), tag(tag_p), count(0), data_size(0) { diff --git a/src/duckdb/src/common/types/row/tuple_data_allocator.cpp b/src/duckdb/src/common/types/row/tuple_data_allocator.cpp index 5d703d5a0..ca1aec08e 100644 --- a/src/duckdb/src/common/types/row/tuple_data_allocator.cpp +++ b/src/duckdb/src/common/types/row/tuple_data_allocator.cpp @@ -35,8 +35,7 @@ TupleDataBlock &TupleDataBlock::operator=(TupleDataBlock &&other) noexcept { } TupleDataAllocator::TupleDataAllocator(BufferManager &buffer_manager, shared_ptr layout_ptr_p, - MemoryTag tag_p, shared_ptr stl_allocator_p, - QueryContext context_p) + MemoryTag tag_p, shared_ptr stl_allocator_p, Context &context_p) : stl_allocator(std::move(stl_allocator_p)), buffer_manager(buffer_manager), context(context_p), layout_ptr(std::move(layout_ptr_p)), layout(*layout_ptr), tag(tag_p), row_blocks(*stl_allocator), heap_blocks(*stl_allocator) { diff --git a/src/duckdb/src/common/types/row/tuple_data_collection.cpp b/src/duckdb/src/common/types/row/tuple_data_collection.cpp index 622c46472..d71ea031b 100644 --- a/src/duckdb/src/common/types/row/tuple_data_collection.cpp +++ b/src/duckdb/src/common/types/row/tuple_data_collection.cpp @@ -23,8 +23,7 @@ namespace duckdb { using ValidityBytes = TupleDataLayout::ValidityBytes; TupleDataCollection::TupleDataCollection(BufferManager &buffer_manager, shared_ptr layout_ptr_p, - MemoryTag tag_p, shared_ptr stl_allocator_p, - QueryContext context) + MemoryTag tag_p, shared_ptr stl_allocator_p, Context &context) : scheduler(TaskScheduler::GetScheduler(buffer_manager.GetDatabase())), stl_allocator(stl_allocator_p ? std::move(stl_allocator_p) : make_shared_ptr(buffer_manager.GetBufferAllocator())), diff --git a/src/duckdb/src/common/virtual_file_system.cpp b/src/duckdb/src/common/virtual_file_system.cpp index d30e947d2..635eb253f 100644 --- a/src/duckdb/src/common/virtual_file_system.cpp +++ b/src/duckdb/src/common/virtual_file_system.cpp @@ -2,7 +2,6 @@ #include "duckdb/common/virtual_file_system.hpp" #include "duckdb/common/compressed_file_system.hpp" -#include "duckdb/common/file_opener.hpp" #include "duckdb/common/memory_mapped_file.hpp" #include "duckdb/common/gzip_file_system.hpp" #include "duckdb/common/local_file_system.hpp" @@ -209,41 +208,37 @@ optional_ptr VirtualFileSystem::FindCompressionFileSystem(FileSy resolved.ToString(), hint); } -unique_ptr VirtualFileSystem::OpenFile(const OpenFileInfo &file, FileOpenFlags flags, - optional_ptr opener) { +unique_ptr VirtualFileSystem::OpenFile(Context &context, const OpenFileInfo &file, FileOpenFlags flags) { 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); - auto file_handle = internal_filesystem.OpenFile(file, flags, opener); + auto &internal_filesystem = FindFileSystem(registry, file.path, context.GetDatabase()); + auto file_handle = internal_filesystem.OpenFile(context, file, flags); if (!file_handle) { return nullptr; } flags.SetCompression(compression); - return WrapOpenedFile(std::move(file_handle), file, flags, opener); + return WrapOpenedFile(context, std::move(file_handle), file, flags); } -unique_ptr VirtualFileSystem::WrapOpenedFile(unique_ptr file_handle, const OpenFileInfo &file, - const FileOpenFlags &flags, optional_ptr opener) { +unique_ptr VirtualFileSystem::WrapOpenedFile(Context &context, unique_ptr file_handle, + const OpenFileInfo &file, const FileOpenFlags &flags) { const auto &compression = flags.Compression(); auto registry = file_system_registry.atomic_load(); try { // Evaluate and apply compression option then. - QueryContext context; - auto opener_context = FileOpener::TryGetContext(opener); - if (opener_context && !flags.MultiClientAccess()) { - context = QueryContext(*opener_context); - } + // a handle shared between clients must not hold on to the context of the client that opened it + auto &handle_context = flags.MultiClientAccess() ? context.GetDatabase().GetContext() : context; if (file_handle->GetType() == FileType::FILE_TYPE_FIFO) { - file_handle = PipeFileSystem::OpenPipe(context, std::move(file_handle)); + file_handle = PipeFileSystem::OpenPipe(handle_context, std::move(file_handle)); } else { auto compression_filesystem = FindCompressionFileSystem(*registry, compression, file.path, flags.OpenForWriting()); if (compression_filesystem) { - file_handle = - compression_filesystem->OpenCompressedFile(context, std::move(file_handle), flags.OpenForWriting()); + file_handle = compression_filesystem->OpenCompressedFile(handle_context, std::move(file_handle), + flags.OpenForWriting()); } } } catch (...) { @@ -338,18 +333,22 @@ bool VirtualFileSystem::IsDisabledForPath(const string &path) { return disabled_file_systems.find(fs->GetName()) != disabled_file_systems.end(); } -BaseFileSystem &VirtualFileSystem::FindFileSystem(const string &path, optional_ptr opener) { +BaseFileSystem &VirtualFileSystem::FindFileSystem(const string &path) { + auto registry = file_system_registry.atomic_load(); + return FindFileSystem(registry, path, nullptr); +} + +BaseFileSystem &VirtualFileSystem::FindFileSystem(Context &context, const string &path) { auto registry = file_system_registry.atomic_load(); - return FindFileSystem(registry, path, opener); + return FindFileSystem(registry, path, context.GetDatabase()); } BaseFileSystem &VirtualFileSystem::FindFileSystem(shared_ptr ®istry, const string &path, - optional_ptr opener) { - auto db_instance = FileOpener::TryGetDatabase(opener); + optional_ptr autoload_db) { auto fs = FindFileSystemInternal(*registry, path); - if (!fs && db_instance) { - ExtensionHelper::AutoLoadExtensionForPath(*db_instance, path); + if (!fs && autoload_db) { + ExtensionHelper::AutoLoadExtensionForPath(*autoload_db, path); // refresh the registry after loading extensions registry = file_system_registry.atomic_load(); diff --git a/src/duckdb/src/execution/index/fixed_size_buffer.cpp b/src/duckdb/src/execution/index/fixed_size_buffer.cpp index 6712e5d69..cf13b4b48 100644 --- a/src/duckdb/src/execution/index/fixed_size_buffer.cpp +++ b/src/duckdb/src/execution/index/fixed_size_buffer.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/assert.hpp" #include "duckdb/common/numeric_utils.hpp" #include "duckdb/common/types/validity_mask.hpp" +#include "duckdb/main/database.hpp" #include "duckdb/storage/block_manager.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/partial_block_manager.hpp" @@ -102,8 +103,10 @@ shared_ptr FixedSizeBuffer::Persist(PartialBlockManager &partia const auto new_allocation_size = GetNewAllocationSize(available_segments, segment_size, bitmask_offset); auto result = make_shared_ptr(block_manager, segment_count, new_allocation_size); + // Index::Checkpoint has no context, so the blocks are written with the database-wide one + auto &context = block_manager.buffer_manager.GetDatabase().GetContext(); auto new_block_pointer = - partial_block_manager.Write(*result, buffer_handle, NumericCast(new_allocation_size)); + partial_block_manager.Write(context, *result, buffer_handle, NumericCast(new_allocation_size)); if (!new_block_pointer) { throw InternalException("failed to write FixedSizeBuffer to a partial block"); } diff --git a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp index 6259de5ed..29e29017e 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp @@ -14,7 +14,7 @@ CSVFileHandle::CSVFileHandle(ClientContext &context_p, unique_ptr fi can_seek = file_handle->CanSeek(); on_disk_file = file_handle->OnDiskFile(); file_size = file_handle->GetFileSize(); - is_pipe = file_handle->IsPipe(); + is_pipe = file_handle->IsPipe(context); compression_type = file_handle->GetFileCompressionType(); } 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 9304c2acd..bc277c0fe 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 @@ -100,7 +100,7 @@ void CSVEncoder::DetectByteOrder() { memcmp(encoded_buffer.Ptr(), mark.first.data(), mark.first.size()) != 0) { continue; } - auto &client_context = *context.GetClientContext(); + auto &client_context = *context.TryGetClientContext(); auto entry = EncodingFunction::Find(client_context, mark.second); if (!entry) { throw InternalException("Encoding \"%s\" picked by a byte order mark does not exist", mark.second); diff --git a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp index 9ac85bad5..06359ade2 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp @@ -1,7 +1,6 @@ #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/execution/operator/persistent/physical_copy_to_file.hpp" -#include "duckdb/common/file_opener.hpp" #include "duckdb/execution/chunk_hasher.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/path.hpp" diff --git a/src/duckdb/src/execution/operator/persistent/physical_delete.cpp b/src/duckdb/src/execution/operator/persistent/physical_delete.cpp index 366e10da9..4859b826b 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_delete.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_delete.cpp @@ -175,7 +175,7 @@ SinkResultType PhysicalDelete::Sink(ExecutionContext &context, DataChunk &chunk, delete_row_ids.Flatten(); fetch_chunk.Initialize(Allocator::Get(context.client), column_types, delete_count); - ColumnFetchState fetch_state; + ColumnFetchState fetch_state(context.client); table.Fetch(DuckTransaction::Get(context.client, table.db), fetch_chunk, column_ids, delete_row_ids, delete_count, fetch_state); delete_count = fetch_chunk.size(); diff --git a/src/duckdb/src/execution/operator/persistent/physical_insert.cpp b/src/duckdb/src/execution/operator/persistent/physical_insert.cpp index 32461bf5a..c49ee2ace 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_insert.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_insert.cpp @@ -472,7 +472,7 @@ static idx_t HandleInsertConflicts(DuckTableEntry &table, ExecutionContext &cont // We scan the existing table for the conflicting tuples, if we // need them for the conditions, or SET expressions. scan_chunk.Initialize(context.client, types_to_fetch); - fetch_state = make_uniq(); + fetch_state = make_uniq(context.client); if (GLOBAL) { auto &transaction = DuckTransaction::Get(context.client, table.catalog); diff --git a/src/duckdb/src/execution/operator/persistent/physical_update.cpp b/src/duckdb/src/execution/operator/persistent/physical_update.cpp index b83092b97..56218dec1 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_update.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_update.cpp @@ -291,7 +291,7 @@ SinkResultType PhysicalUpdate::Sink(ExecutionContext &context, DataChunk &chunk, // Fetch needs a flat vector, but deduplication may have sliced del_row_ids into a dictionary. del_row_ids.Flatten(); fetch_chunk.Reset(); - auto fetch_state = ColumnFetchState(); + auto fetch_state = ColumnFetchState(context.client); auto &transaction = DuckTransaction::Get(context.client, table.db); table.Fetch(transaction, fetch_chunk, column_ids, del_row_ids, update_count, fetch_state); diff --git a/src/duckdb/src/function/copy_blob.cpp b/src/duckdb/src/function/copy_blob.cpp index a0c428d9f..362d28a08 100644 --- a/src/duckdb/src/function/copy_blob.cpp +++ b/src/duckdb/src/function/copy_blob.cpp @@ -87,7 +87,7 @@ unique_ptr WriteBlobInitializeLocal(ExecutionContext &context return make_uniq_base(); } -void WriteBlobData(QueryContext &query_context, FileHandle &handle, data_ptr_t blob_ptr, idx_t blob_len) { +void WriteBlobData(Context &query_context, FileHandle &handle, data_ptr_t blob_ptr, idx_t blob_len) { while (blob_len > 0) { auto written = handle.Write(query_context, blob_ptr, blob_len); if (written <= 0) { @@ -110,7 +110,7 @@ void WriteBlobSink(ExecutionContext &context, const FunctionData &bind_data, Glo auto &handle = state.handle; - QueryContext query_context(context.client); + Context &query_context(context.client); for (auto entry : input.data[0].Values()) { if (entry.IsValid()) { @@ -155,7 +155,7 @@ void WriteBlobFlushBatch(ClientContext &context, const FunctionData &bind_data, auto &blob_batch = batch.Cast(); lock_guard glock(state.lock); - QueryContext query_context(context); + Context &query_context(context); for (auto &blob : blob_batch.blobs) { WriteBlobData(query_context, *state.handle, data_ptr_cast(blob.data()), blob.size()); } diff --git a/src/duckdb/src/function/scalar/system/write_log.cpp b/src/duckdb/src/function/scalar/system/write_log.cpp index 4ffe4a268..d5860bdb5 100644 --- a/src/duckdb/src/function/scalar/system/write_log.cpp +++ b/src/duckdb/src/function/scalar/system/write_log.cpp @@ -133,12 +133,13 @@ void WriteLogFunction(DataChunk &args, ExpressionState &state, Vector &result) { } else if (info.scope == "database") { WriteLogValues(*info.context->db, info.level, input_data, idata.sel, args.size(), info.type); - } else if (info.scope == "file_opener") { - WriteLogValues(*info.context->GetContext().TryGetFileOpener(), info.level, input_data, - idata.sel, args.size(), info.type); + } else if (info.scope == "context" || info.scope == "file_opener") { + // file_opener is the former name of the context scope + WriteLogValues(info.context->GetContext(), info.level, input_data, idata.sel, args.size(), + info.type); } else { throw InvalidInputException( - "write_log: 'scope' argument unknown: '%s'. Valid values are [connection, database, file_opener]", + "write_log: 'scope' argument unknown: '%s'. Valid values are [connection, database, context]", info.scope); } } diff --git a/src/duckdb/src/function/table/direct_file_reader.cpp b/src/duckdb/src/function/table/direct_file_reader.cpp index c84fdc485..8b6e02126 100644 --- a/src/duckdb/src/function/table/direct_file_reader.cpp +++ b/src/duckdb/src/function/table/direct_file_reader.cpp @@ -105,7 +105,7 @@ AsyncResult DirectFileReader::Scan(ClientContext &context, GlobalTableFunctionSt const auto file_size = file_handle->GetFileSize(); AssertMaxFileSize(file.path, file_size); // Zero-sized files could be a special file, so read until EOF. - const bool read_until_eof = file_handle->IsPipe() || file_size == 0; + const bool read_until_eof = file_handle->IsPipe(context) || file_size == 0; // Initialize write stream if not yet done if (!state.stream) { diff --git a/src/duckdb/src/function/table/system/duckdb_extensions.cpp b/src/duckdb/src/function/table/system/duckdb_extensions.cpp index 133e7a3da..be2525d41 100644 --- a/src/duckdb/src/function/table/system/duckdb_extensions.cpp +++ b/src/duckdb/src/function/table/system/duckdb_extensions.cpp @@ -130,7 +130,8 @@ unique_ptr DuckDBExtensionsInit(ClientContext &context auto info_file_path = fs.JoinPath(ext_directory, path + ".info"); // Read the info file - auto extension_install_info = ExtensionInstallInfo::TryReadInfoFile(fs, info_file_path, info.name); + auto extension_install_info = + ExtensionInstallInfo::TryReadInfoFile(context.GetContext(), fs, info_file_path, info.name); info.install_mode = extension_install_info->mode; info.extension_version = extension_install_info->version; info.signature_key_fingerprint = extension_install_info->signature_key_fingerprint; diff --git a/src/duckdb/src/function/table/system/pragma_storage_info.cpp b/src/duckdb/src/function/table/system/pragma_storage_info.cpp index 3927923a9..31bc448a0 100644 --- a/src/duckdb/src/function/table/system/pragma_storage_info.cpp +++ b/src/duckdb/src/function/table/system/pragma_storage_info.cpp @@ -167,7 +167,7 @@ static void PragmaStorageInfoFunction(ClientContext &context, TableFunctionInput auto &gstate = data_p.global_state->Cast(); auto &lstate = data_p.local_state->Cast(); auto &columns = bind_data.table_entry.GetColumns(); - QueryContext query_context(context); + Context &query_context(context); idx_t count = 0; diff --git a/src/duckdb/src/function/table/table_scan.cpp b/src/duckdb/src/function/table/table_scan.cpp index 448b276e4..6aa72cb68 100644 --- a/src/duckdb/src/function/table/table_scan.cpp +++ b/src/duckdb/src/function/table/table_scan.cpp @@ -128,6 +128,9 @@ struct TableScanLocalState : public LocalTableFunctionState { }; struct IndexScanLocalState : public LocalTableFunctionState { + explicit IndexScanLocalState(ClientContext &context) : fetch_state(context) { + } + //! The batch index, which determines the offset in the row ID vector. idx_t batch_index; //! The DataChunk containing all read columns. @@ -214,8 +217,7 @@ class DuckIndexScanState : public TableScanGlobalState { public: unique_ptr InitLocalState(ExecutionContext &context, TableFunctionInitInput &input) override { - auto l_state = make_uniq(); - l_state->fetch_state.context = context.client; + auto l_state = make_uniq(context.client); if (input.CanRemoveFilterColumns()) { l_state->all_columns.Initialize(context.client, scanned_types); } diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index b36854a73..d37ffb6c5 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-alpha58157" +#define DUCKDB_PATCH_VERSION "0-alpha58282" #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-alpha58157" +#define DUCKDB_VERSION "v2.1.0-alpha58282" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "07c9a117d0" +#define DUCKDB_SOURCE_ID "9345a4d95c" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/include/duckdb/catalog/catalog.hpp b/src/duckdb/src/include/duckdb/catalog/catalog.hpp index c5b489c0c..e57b211d9 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog.hpp @@ -50,7 +50,7 @@ class SchemaScanFilters; class AttachedDatabase; class ClientContext; -class QueryContext; +class Context; class Transaction; class AggregateFunctionCatalogEntry; diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_table_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_table_entry.hpp index f6bae8aaa..872a6eea3 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_table_entry.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_table_entry.hpp @@ -58,10 +58,10 @@ class DuckTableEntry : public TableCatalogEntry { TableFunction GetScanFunction(ClientContext &context, unique_ptr &bind_data) override; vector - GetColumnSegmentInfo(const QueryContext &context, + GetColumnSegmentInfo(Context &context, const ColumnSegmentInfoScanOptions &options = ColumnSegmentInfoScanOptions {}) override; void InitializeColumnSegmentInfoScan(ColumnSegmentInfoScanState &state) override; - bool ScanColumnSegmentInfo(const QueryContext &context, ColumnSegmentInfoScanState &state, + bool ScanColumnSegmentInfo(Context &context, ColumnSegmentInfoScanState &state, vector &result) override; TableStorageInfo GetStorageInfo(ClientContext &context) override; diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/table_catalog_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/table_catalog_entry.hpp index e4452ed85..3f58ec917 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/table_catalog_entry.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry/table_catalog_entry.hpp @@ -128,12 +128,12 @@ class TableCatalogEntry : public StandardEntry { //! Returns a list of segment information for this table, if exists virtual vector - GetColumnSegmentInfo(const QueryContext &context, + GetColumnSegmentInfo(Context &context, const ColumnSegmentInfoScanOptions &options = ColumnSegmentInfoScanOptions {}); //! Initialize an incremental scan over the table's column segment info. virtual void InitializeColumnSegmentInfoScan(ColumnSegmentInfoScanState &state); //! Append the next row group's column segment info to result. Returns false when no row groups remain. - virtual bool ScanColumnSegmentInfo(const QueryContext &context, ColumnSegmentInfoScanState &state, + virtual bool ScanColumnSegmentInfo(Context &context, ColumnSegmentInfoScanState &state, vector &result); //! Returns the storage info of this table diff --git a/src/duckdb/src/include/duckdb/common/base_file_system.hpp b/src/duckdb/src/include/duckdb/common/base_file_system.hpp index d5ac29142..a4672b0e4 100644 --- a/src/duckdb/src/include/duckdb/common/base_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/base_file_system.hpp @@ -36,13 +36,12 @@ namespace duckdb { class AttachedDatabase; class DatabaseInstance; -class FileOpener; class BaseFileSystem; class FileSystem; class Logger; class ClientContext; +class Context; class CompressedFileSystem; -class QueryContext; class MemoryMappedFile; struct MMapOptions; class MultiFileList; @@ -122,14 +121,14 @@ struct FileHandle { // Read at [nr_bytes] bytes into [buffer], and return the bytes actually read. // File offset will be changed, which advances for number of bytes read. DUCKDB_API int64_t Read(void *buffer, idx_t nr_bytes); - DUCKDB_API int64_t Read(QueryContext context, void *buffer, idx_t nr_bytes); + DUCKDB_API int64_t Read(Context &context, void *buffer, idx_t nr_bytes); DUCKDB_API int64_t Write(void *buffer, idx_t nr_bytes); - DUCKDB_API int64_t Write(QueryContext context, void *buffer, idx_t nr_bytes); + DUCKDB_API int64_t Write(Context &context, void *buffer, idx_t nr_bytes); // Read at [nr_bytes] bytes into [buffer]. // File offset will not be changed. DUCKDB_API void Read(void *buffer, idx_t nr_bytes, idx_t location); - DUCKDB_API void Read(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location); - DUCKDB_API void Write(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location); + DUCKDB_API void Read(Context &context, void *buffer, idx_t nr_bytes, idx_t location); + DUCKDB_API void Write(Context &context, void *buffer, idx_t nr_bytes, idx_t location); DUCKDB_API void Seek(idx_t location); DUCKDB_API void Reset(); DUCKDB_API idx_t SeekPosition(); @@ -138,14 +137,14 @@ struct FileHandle { //! Abandon an incomplete write without publishing any buffered or staged data. DUCKDB_API void AbortWrite(); DUCKDB_API string ReadLine(); - DUCKDB_API string ReadLine(QueryContext context); + DUCKDB_API string ReadLine(Context &context); DUCKDB_API bool Trim(idx_t offset_bytes, idx_t length_bytes); DUCKDB_API virtual idx_t GetProgress(); DUCKDB_API virtual FileCompressionType GetFileCompressionType(); DUCKDB_API virtual bool CanSeek(); DUCKDB_API FileWriteMode GetWriteMode(); - DUCKDB_API bool IsPipe(); + DUCKDB_API bool IsPipe(Context &context); DUCKDB_API bool OnDiskFile(); //! Try to obtain a network throughput estimate (Local files return false). DUCKDB_API bool TryGetNetworkThroughput(NetworkThroughputEstimate &result); @@ -153,7 +152,7 @@ struct FileHandle { DUCKDB_API FileType GetType(); DUCKDB_API FileMetadata Stats(); - DUCKDB_API void TryAddLogger(FileOpener &opener); + DUCKDB_API void TryAddLogger(Context &context); //! Closes the file handle. DUCKDB_API virtual void Close() = 0; @@ -193,15 +192,12 @@ class BaseFileSystem { public: DUCKDB_API virtual ~BaseFileSystem(); - DUCKDB_API virtual unique_ptr OpenFile(const string &path, FileOpenFlags flags, - optional_ptr opener); - DUCKDB_API unique_ptr OpenFile(const OpenFileInfo &path, const FileOpenFlags &flags, - optional_ptr opener); + DUCKDB_API virtual unique_ptr OpenFile(Context &context, const string &path, FileOpenFlags flags); + DUCKDB_API unique_ptr OpenFile(Context &context, const OpenFileInfo &path, const FileOpenFlags &flags); //! Open a memory-mapped view of [path]. Throws if not supported by this filesystem. - DUCKDB_API virtual unique_ptr MemoryMapFile(const OpenFileInfo &path, FileOpenFlags flags, - const MMapOptions &options, - optional_ptr opener); + DUCKDB_API virtual unique_ptr MemoryMapFile(Context &context, const OpenFileInfo &path, + FileOpenFlags flags, const MMapOptions &options); //! Read exactly nr_bytes from the specified location in the file. Fails if nr_bytes could not be read. This is //! equivalent to calling SetFilePointer(location) followed by calling Read(). @@ -232,46 +228,45 @@ class BaseFileSystem { //! Returns the file stats of the attached handle. DUCKDB_API virtual FileMetadata Stats(FileHandle &handle); //! Returns the stats of a file, or nullopt if the file does not exist. - DUCKDB_API virtual optional GetStatsIfExists(const OpenFileInfo &file, - optional_ptr opener); + DUCKDB_API virtual optional GetStatsIfExists(Context &context, const OpenFileInfo &file); //! Truncate a file to a maximum size of new_size, new_size should be smaller than or equal to the current size of //! the file DUCKDB_API virtual void Truncate(FileHandle &handle, int64_t new_size); //! Check if a directory exists - DUCKDB_API virtual bool DirectoryExists(const string &directory, optional_ptr opener); + DUCKDB_API virtual bool DirectoryExists(Context &context, const string &directory); //! Create a directory if it does not exist - DUCKDB_API virtual void CreateDirectory(const string &directory, optional_ptr opener); + DUCKDB_API virtual void CreateDirectory(Context &context, const string &directory); //! Create one directory or a directory tree. Returns whether this call is known to have created the target. - DUCKDB_API virtual bool CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener); + DUCKDB_API virtual bool CreateDirectoryExtended(Context &context, const string &directory, + const CreateDirectoryOptions &options); //! Helper function that uses DirectoryExists and CreateDirectory to ensure all directories in path are created - DUCKDB_API virtual void CreateDirectoriesRecursive(const string &path, optional_ptr opener); + DUCKDB_API virtual void CreateDirectoriesRecursive(Context &context, const string &path); //! Recursively remove a directory and all files in it - DUCKDB_API virtual void RemoveDirectory(const string &directory, optional_ptr opener); + DUCKDB_API virtual void RemoveDirectory(Context &context, const string &directory); //! Remove an empty directory or a directory tree. Returns whether the target was removed. - DUCKDB_API virtual bool RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener); + DUCKDB_API virtual bool RemoveDirectoryExtended(Context &context, const string &directory, + const RemoveDirectoryOptions &options); //! List files in a directory, invoking the callback method for each one with (filename, is_dir) - DUCKDB_API virtual bool ListFiles(const string &directory, - const std::function &callback, FileOpener *opener); - DUCKDB_API bool ListFiles(const string &directory, const std::function &callback, - optional_ptr opener); + DUCKDB_API virtual bool ListFiles(Context &context, const string &directory, + const std::function &callback); + DUCKDB_API bool ListFiles(Context &context, const string &directory, + const std::function &callback); //! Move a file from source path to the target, StorageManager relies on this being an atomic action for ACID //! properties - DUCKDB_API virtual void MoveFile(const string &source, const string &target, optional_ptr opener); + DUCKDB_API virtual void MoveFile(Context &context, const string &source, const string &target); //! Check if a file exists - DUCKDB_API virtual bool FileExists(const string &filename, optional_ptr opener); + DUCKDB_API virtual bool FileExists(Context &context, const string &filename); //! Check if path is a pipe or character device - DUCKDB_API virtual bool IsPipe(const string &filename, optional_ptr opener); + DUCKDB_API virtual bool IsPipe(Context &context, const string &filename); //! Remove a file from disk - DUCKDB_API virtual void RemoveFile(const string &filename, optional_ptr opener); + DUCKDB_API virtual void RemoveFile(Context &context, const string &filename); //! Remove a file from disk if it exists - if it does not exist, return false - DUCKDB_API virtual bool TryRemoveFile(const string &filename, optional_ptr opener); + DUCKDB_API virtual bool TryRemoveFile(Context &context, const string &filename); //! Remove multiple files from disk - does not error if any file does not exist - DUCKDB_API virtual void RemoveFiles(const vector &filenames, optional_ptr opener); + DUCKDB_API virtual void RemoveFiles(Context &context, const vector &filenames); //! Sync a file handle to disk DUCKDB_API virtual void FileSync(FileHandle &handle); //! Abandon an incomplete write represented by this file handle. @@ -301,9 +296,8 @@ class BaseFileSystem { DUCKDB_API string ExtractName(const string &path); //! Runs a glob on the file system, returning a list of matching files - DUCKDB_API virtual vector Glob(const string &path, FileOpener *opener); - DUCKDB_API unique_ptr Glob(const string &path, const FileGlobInput &input, - optional_ptr opener); + DUCKDB_API virtual vector Glob(Context &context, const string &path); + DUCKDB_API unique_ptr Glob(Context &context, const string &path, const FileGlobInput &input); //! Whether or not a sub-system can handle a specific file path DUCKDB_API virtual bool CanHandleFile(const string &fpath); @@ -327,7 +321,7 @@ class BaseFileSystem { //! Used for file systems DUCKDB_API virtual bool TryGetNetworkThroughput(FileHandle &handle, NetworkThroughputEstimate &result); - DUCKDB_API virtual unique_ptr OpenCompressedFile(QueryContext context, unique_ptr handle, + DUCKDB_API virtual unique_ptr OpenCompressedFile(Context &context, unique_ptr handle, bool write); //! Whether this is a LocalFileSystem instance. @@ -337,20 +331,21 @@ class BaseFileSystem { DUCKDB_API virtual std::string GetName() const = 0; //! Canonicalize a path - DUCKDB_API virtual string CanonicalizePath(const string &path, optional_ptr opener); + DUCKDB_API virtual string CanonicalizePath(Context &context, const string &path); + //! Canonicalizes a path without consulting the file system: removes "." and ".." segments + DUCKDB_API string GenericCanonicalizePath(const string &path); protected: - DUCKDB_API virtual unique_ptr OpenFileExtended(const OpenFileInfo &path, FileOpenFlags flags, - optional_ptr opener); + DUCKDB_API virtual unique_ptr OpenFileExtended(Context &context, const OpenFileInfo &path, + FileOpenFlags flags); DUCKDB_API virtual bool SupportsOpenFileExtended() const; - DUCKDB_API virtual bool ListFilesExtended(const string &directory, - const std::function &callback, - optional_ptr opener); + DUCKDB_API virtual bool ListFilesExtended(Context &context, const string &directory, + const std::function &callback); DUCKDB_API virtual bool SupportsListFilesExtended() const; - DUCKDB_API virtual unique_ptr GlobFilesExtended(const string &path, const FileGlobInput &input, - optional_ptr opener); + DUCKDB_API virtual unique_ptr GlobFilesExtended(Context &context, const string &path, + const FileGlobInput &input); DUCKDB_API virtual bool SupportsGlobExtended() const; public: diff --git a/src/duckdb/src/include/duckdb/common/compressed_file_system.hpp b/src/duckdb/src/include/duckdb/common/compressed_file_system.hpp index 1a242c28d..fe48afa8b 100644 --- a/src/duckdb/src/include/duckdb/common/compressed_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/compressed_file_system.hpp @@ -12,7 +12,7 @@ #include "duckdb/common/atomic.hpp" #include "duckdb/common/common.hpp" #include "duckdb/common/base_file_system.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { class CompressedFile; @@ -35,7 +35,7 @@ struct StreamData { struct StreamWrapper { DUCKDB_API virtual ~StreamWrapper(); - DUCKDB_API virtual void Initialize(QueryContext context, CompressedFile &file, bool write) = 0; + DUCKDB_API virtual void Initialize(Context &context, CompressedFile &file, bool write) = 0; DUCKDB_API virtual bool Read(StreamData &stream_data) = 0; DUCKDB_API virtual void FinalizeRead(StreamData &stream_data); DUCKDB_API virtual void Write(CompressedFile &file, StreamData &stream_data, data_ptr_t buffer, @@ -80,11 +80,11 @@ class CompressedFile : public FileHandle { //! Whether the file is opened for reading or for writing bool write = false; StreamData stream_data; - //! The query context, used to attribute the (compressed) on-disk I/O of the child handle to the query - QueryContext context; + //! The context, used to attribute the (compressed) on-disk I/O of the child handle to the query + optional_ptr context; public: - DUCKDB_API void Initialize(QueryContext context, bool write); + DUCKDB_API void Initialize(Context &context, bool write); DUCKDB_API int64_t ReadData(void *buffer, int64_t nr_bytes); DUCKDB_API int64_t WriteData(data_ptr_t buffer, int64_t nr_bytes); DUCKDB_API void Close() override; diff --git a/src/duckdb/src/include/duckdb/common/csv_writer.hpp b/src/duckdb/src/include/duckdb/common/csv_writer.hpp index de04d050a..244b67de6 100644 --- a/src/duckdb/src/include/duckdb/common/csv_writer.hpp +++ b/src/duckdb/src/include/duckdb/common/csv_writer.hpp @@ -11,7 +11,7 @@ #include "duckdb/common/common.hpp" #include "duckdb/execution/operator/csv_scanner/csv_reader_options.hpp" #include "duckdb/common/serializer/memory_stream.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { class AsyncFileWriter; @@ -67,7 +67,8 @@ class CSVWriter { //! Create a CSVWriter that writes to a file CSVWriter(const CSVReaderOptions &options, FileSystem &fs, const string &file_path, FileCompressionType compression, - QueryContext context = QueryContext(), bool shared = true); + Context &context, bool shared = true); + ~CSVWriter(); //! Writes header and prefix if necessary diff --git a/src/duckdb/src/include/duckdb/common/file_buffer.hpp b/src/duckdb/src/include/duckdb/common/file_buffer.hpp index af8dee413..1def9d665 100644 --- a/src/duckdb/src/include/duckdb/common/file_buffer.hpp +++ b/src/duckdb/src/include/duckdb/common/file_buffer.hpp @@ -16,7 +16,7 @@ namespace duckdb { class BlockAllocator; class BlockManager; class MemoryMappedFile; -class QueryContext; +class Context; struct FileHandle; @@ -39,15 +39,15 @@ class FileBuffer { public: //! Read into the FileBuffer from the location. - void Read(QueryContext context, FileHandle &handle, uint64_t location); + void Read(Context &context, FileHandle &handle, uint64_t location); //! Read into the FileBuffer from a memory-mapped file at the location. - void Read(QueryContext context, MemoryMappedFile &handle, uint64_t location); + void Read(Context &context, MemoryMappedFile &handle, uint64_t location); //! Read into the FileBuffer from an in-memory source; the source must cover location + AllocSize() bytes. void ReadFromMemory(const_data_ptr_t source, uint64_t location); //! Write the FileBuffer to the location. - void Write(QueryContext context, FileHandle &handle, const uint64_t location); + void Write(Context &context, FileHandle &handle, const uint64_t location); //! Write the FileBuffer to the location in a memory-mapped file. - void Write(QueryContext context, MemoryMappedFile &handle, uint64_t location); + void Write(Context &context, MemoryMappedFile &handle, uint64_t location); void Clear(); diff --git a/src/duckdb/src/include/duckdb/common/file_lookup_info.hpp b/src/duckdb/src/include/duckdb/common/file_lookup_info.hpp new file mode 100644 index 000000000..718be555f --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/file_lookup_info.hpp @@ -0,0 +1,29 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/file_lookup_info.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/open_file_info.hpp" + +namespace duckdb { + +//! The file an open, listing or request is for +struct FileLookupInfo { + FileLookupInfo() = default; + FileLookupInfo(string path) // NOLINT: allow implicit conversion from a path + : file(std::move(path)) { + } + FileLookupInfo(OpenFileInfo file_p) // NOLINT: allow implicit conversion from a file + : file(std::move(file_p)) { + } + + //! The file, with the options it is opened with, e.g. the secret to open it with + OpenFileInfo file; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/file_opener.hpp b/src/duckdb/src/include/duckdb/common/file_opener.hpp deleted file mode 100644 index e3d01fb78..000000000 --- a/src/duckdb/src/include/duckdb/common/file_opener.hpp +++ /dev/null @@ -1,81 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/common/file_opener.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/open_file_info.hpp" -#include "duckdb/common/string.hpp" -#include "duckdb/common/winapi.hpp" -#include "duckdb/main/setting_info.hpp" - -namespace duckdb { - -struct CatalogTransaction; -class SecretManager; -class Context; -class HTTPUtil; -class Value; -class Logger; - -//! The file an open, listing or request is for -struct FileOpenerInfo { - FileOpenerInfo() = default; - FileOpenerInfo(string path) // NOLINT: allow implicit conversion from a path - : file(std::move(path)) { - } - FileOpenerInfo(OpenFileInfo file_p) // NOLINT: allow implicit conversion from a file - : file(std::move(file_p)) { - } - - //! The file, with the options it is opened with, e.g. the secret to open it with - OpenFileInfo file; -}; - -//! Abstract type that provide client-specific context to FileSystem. -class FileOpener { -public: - FileOpener() { - } - virtual ~FileOpener() {}; - - virtual SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result, FileOpenerInfo &info); - virtual SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result) = 0; - virtual Context &TryGetContext() = 0; - virtual optional_ptr TryGetDatabase() = 0; - virtual HTTPUtil &GetHTTPUtil() = 0; - - DUCKDB_API virtual Logger &GetLogger() const = 0; - DUCKDB_API static unique_ptr TryGetCatalogTransaction(optional_ptr opener); - DUCKDB_API static optional_ptr TryGetContext(optional_ptr opener); - DUCKDB_API static optional_ptr TryGetDatabase(optional_ptr opener); - DUCKDB_API static optional_ptr TryGetSecretManager(optional_ptr opener); - DUCKDB_API static SettingLookupResult TryGetCurrentSetting(optional_ptr opener, const Identifier &key, - Value &result); - DUCKDB_API static SettingLookupResult TryGetCurrentSetting(optional_ptr opener, const Identifier &key, - Value &result, FileOpenerInfo &info); - - template - static SettingLookupResult TryGetCurrentSetting(optional_ptr opener, const Identifier &key, - TYPE &result, optional_ptr info) { - Value output; - SettingLookupResult lookup_result; - - if (info) { - lookup_result = TryGetCurrentSetting(opener, key, output, *info); - } else { - lookup_result = TryGetCurrentSetting(opener, key, output); - } - - if (lookup_result) { - result = output.GetValue(); - } - return lookup_result; - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/file_system.hpp b/src/duckdb/src/include/duckdb/common/file_system.hpp index 4f7dd7186..c80fbf0ef 100644 --- a/src/duckdb/src/include/duckdb/common/file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/file_system.hpp @@ -14,9 +14,9 @@ namespace duckdb { class MultiFileList; -//! A file system bound to a context: it wraps a BaseFileSystem and pushes the FileOpener of that context into every -//! call after checking that the access is allowed. It is not a BaseFileSystem: code that obtains it through -//! FileSystem::GetFileSystem(context) cannot call the opener-taking BaseFileSystem methods by accident. +//! A file system bound to a context: it wraps a BaseFileSystem and passes that context into every call after checking +//! that the access is allowed. It is not a BaseFileSystem: code that obtains it through +//! FileSystem::GetFileSystem(context) cannot call the context-taking BaseFileSystem methods by accident. class FileSystem { public: virtual ~FileSystem() = default; @@ -41,9 +41,13 @@ class FileSystem { //! Gets the working directory DUCKDB_API static string GetWorkingDirectory(); //! Gets the users home directory - DUCKDB_API static string GetHomeDirectory(optional_ptr opener); + DUCKDB_API static string GetHomeDirectory(Context &context); + //! Gets the default home directory of the user (without consulting the home_directory setting) + DUCKDB_API static string GetDefaultHomeDirectory(); //! Expands a given path, including e.g. expanding the home directory of the user - DUCKDB_API static string ExpandPath(const string &path, optional_ptr opener); + DUCKDB_API static string ExpandPath(Context &context, const string &path); + //! Expands "~" and file URLs in the path using the given home directory + DUCKDB_API static string ExpandPathWithHome(const string &path, const string &home_directory); //! Returns the system-available memory in bytes. Returns an invalid index if the system function fails. DUCKDB_API static optional_idx GetAvailableMemory(); //! Returns the space available on the disk. Returns an invalid index if the information was not available. @@ -115,7 +119,7 @@ class FileSystem { handle.file_system.FileSync(handle); } - //! Path-level operations: the access is verified, then forwarded together with the opener + //! Path-level operations: the access is verified, then forwarded together with the context DUCKDB_API unique_ptr OpenFile(const string &path, const FileOpenFlags &flags); DUCKDB_API unique_ptr OpenFile(const OpenFileInfo &file, const FileOpenFlags &flags); DUCKDB_API unique_ptr MemoryMapFile(const OpenFileInfo &path, const FileOpenFlags &flags, @@ -217,7 +221,7 @@ class FileSystem { protected: //! The root that picks the file system of a path virtual VirtualFileSystem &GetFileSystem() const = 0; - virtual optional_ptr GetOpener() const = 0; + virtual Context &GetContext() 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; diff --git a/src/duckdb/src/include/duckdb/common/gzip_file_system.hpp b/src/duckdb/src/include/duckdb/common/gzip_file_system.hpp index 2115b8d9f..abd0d1161 100644 --- a/src/duckdb/src/include/duckdb/common/gzip_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/gzip_file_system.hpp @@ -17,7 +17,7 @@ class GZipFileSystem : public CompressedFileSystem { static constexpr const idx_t BUFFER_SIZE = 1u << 15; public: - unique_ptr OpenCompressedFile(QueryContext context, unique_ptr handle, bool write) override; + unique_ptr OpenCompressedFile(Context &context, unique_ptr handle, bool write) override; std::string GetName() const override { return "GZipFileSystem"; diff --git a/src/duckdb/src/include/duckdb/common/local_file_system.hpp b/src/duckdb/src/include/duckdb/common/local_file_system.hpp index 67f47fa7f..85c1511e6 100644 --- a/src/duckdb/src/include/duckdb/common/local_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/local_file_system.hpp @@ -15,10 +15,10 @@ namespace duckdb { class LocalFileSystem : public BaseFileSystem { public: - unique_ptr OpenFile(const string &path, FileOpenFlags flags, optional_ptr opener) override; + unique_ptr OpenFile(Context &context, const string &path, FileOpenFlags flags) override; - unique_ptr MemoryMapFile(const OpenFileInfo &path, FileOpenFlags flags, - const MMapOptions &options, optional_ptr opener) override; + unique_ptr MemoryMapFile(Context &context, const OpenFileInfo &path, FileOpenFlags flags, + const MMapOptions &options) override; //! Read exactly nr_bytes from the specified location in the file. Fails if nr_bytes could not be read. This is //! equivalent to calling SetFilePointer(location) followed by calling Read(). @@ -47,32 +47,32 @@ class LocalFileSystem : public BaseFileSystem { FileType GetFileType(FileHandle &handle) override; //! Returns the file stats of the attached handle. FileMetadata Stats(FileHandle &handle) override; - optional GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) override; + optional GetStatsIfExists(Context &context, const OpenFileInfo &file) override; //! Truncate a file to a maximum size of new_size, new_size should be smaller than or equal to the current size of //! the file void Truncate(FileHandle &handle, int64_t new_size) override; //! Check if a directory exists - bool DirectoryExists(const string &directory, optional_ptr opener) override; + bool DirectoryExists(Context &context, const string &directory) override; //! Create a directory if it does not exist - void CreateDirectory(const string &directory, optional_ptr opener) override; - bool CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener) override; - void CreateDirectoriesRecursive(const string &path, optional_ptr opener) override; + void CreateDirectory(Context &context, const string &directory) override; + bool CreateDirectoryExtended(Context &context, const string &directory, + const CreateDirectoryOptions &options) override; + void CreateDirectoriesRecursive(Context &context, const string &path) override; //! Recursively remove a directory and all files in it - void RemoveDirectory(const string &directory, optional_ptr opener) override; - bool RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener) override; + void RemoveDirectory(Context &context, const string &directory) override; + bool RemoveDirectoryExtended(Context &context, const string &directory, + const RemoveDirectoryOptions &options) override; //! Move a file from source path to the target, StorageManager relies on this being an atomic action for ACID //! properties - void MoveFile(const string &source, const string &target, optional_ptr opener) override; + void MoveFile(Context &context, const string &source, const string &target) override; //! Check if a file exists - bool FileExists(const string &filename, optional_ptr opener) override; + bool FileExists(Context &context, const string &filename) override; //! Check if path is a pipe or character device - bool IsPipe(const string &filename, optional_ptr opener) override; + bool IsPipe(Context &context, const string &filename) override; //! Remove a file from disk - void RemoveFile(const string &filename, optional_ptr opener) override; + void RemoveFile(Context &context, const string &filename) override; //! Sync a file handle to disk void FileSync(FileHandle &handle) override; //! Close and remove an incomplete output file @@ -80,7 +80,7 @@ class LocalFileSystem : public BaseFileSystem { //! Checks if path is is an absolute path bool IsPathAbsolute(const string &path) override; - string MakePathAbsolute(const string &input, optional_ptr opener); + string MakePathAbsolute(const string &input, const string &home_directory); bool PathStartsWithDrive(const string &path); bool CanHandleFile(const string &fpath) override { @@ -112,22 +112,24 @@ class LocalFileSystem : public BaseFileSystem { static std::string GetLastErrorAsString(); //! Checks a file is private (checks for 600 on linux/macos, TODO: currently always returns true on windows) - static bool IsPrivateFile(const string &path_p, FileOpener *opener); + static bool IsPrivateFile(const string &path_p); - vector FetchFileWithoutGlob(const string &path, optional_ptr opener, bool absolute_path); + vector FetchFileWithoutGlob(const string &path, Context &context, bool absolute_path); - string CanonicalizePath(const string &path_p, optional_ptr opener) override; + string CanonicalizePath(Context &context, const string &path_p) override; + //! Canonicalizes a path, expanding "~" with the given home directory + string CanonicalizePathWithHome(const string &path_p, const string &home_directory); protected: - bool ListFilesExtended(const string &directory, const std::function &callback, - optional_ptr opener) override; + bool ListFilesExtended(Context &context, const string &directory, + const std::function &callback) override; bool SupportsListFilesExtended() const override { return true; } - unique_ptr GlobFilesExtended(const string &path, const FileGlobInput &input, - optional_ptr opener) override; + unique_ptr GlobFilesExtended(Context &context, const string &path, + const FileGlobInput &input) override; bool SupportsGlobExtended() const override { return true; } diff --git a/src/duckdb/src/include/duckdb/common/multi_file/base_file_reader.hpp b/src/duckdb/src/include/duckdb/common/multi_file/base_file_reader.hpp index 2b2762650..8cb1831fb 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/base_file_reader.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/base_file_reader.hpp @@ -84,6 +84,10 @@ class BaseFileReader : public enable_shared_from_this { //! Whether or not to push casts into the cast map return false; } + //! Whether the reader only produces the rows its deletion filter selects + virtual bool SupportsDeletionFilter() const { + return false; + } //! Adds a virtual column to be projected at the end virtual void AddVirtualColumn(column_t virtual_column_id) { throw InternalException("Reader %s does not support AddVirtualColumn", GetReaderType()); 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 efe9415ec..a70a9fd50 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 @@ -11,6 +11,7 @@ #include "duckdb/common/multi_file/multi_file_reader.hpp" #include "duckdb/function/partition_stats.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/database.hpp" #include "duckdb/main/profiler/profiling_node.hpp" #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/common/vector/flat_vector.hpp" @@ -365,8 +366,13 @@ class MultiFileFunction : public TableFunction { // 1. The MultiFileReader::Bind call // 2. The 'schema' parquet option auto &global_columns = bind_data.reader_bind.schema.empty() ? bind_data.columns : bind_data.reader_bind.schema; - return bind_data.multi_file_reader->InitializeReader(reader_data, bind_data, global_columns, global_column_ids, - table_filters, context, global_state); + auto result = bind_data.multi_file_reader->InitializeReader( + reader_data, bind_data, global_columns, global_column_ids, table_filters, context, global_state); + if (result == ReaderInitializeType::INITIALIZED && !reader.deletion_filter) { + // the file list can describe the rows of a file to scan with its options + reader.deletion_filter = DatabaseInstance::GetDatabase(context).CreateFileFilter(context, reader); + } + return result; } static bool TrySkipFileFromFilters(ClientContext &context, const MultiFileBindData &bind_data, diff --git a/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file.hpp b/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file.hpp index 81d2c64f7..23ea3d454 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file.hpp @@ -211,6 +211,8 @@ struct TableFunctionMultiFileSettings { bool supports_cast_map = false; //! Whether the function counts the bytes it scans, reported as operator.bytes_scanned of the scan bool reports_bytes_scanned = false; + //! Whether the function only produces the rows that TableFunctionFileInitInput::deletion_filter selects + bool supports_deletion_filter = false; }; //! The function info of a multi-file wrapper - holds the single-file function that is wrapped @@ -253,6 +255,7 @@ class TableFunctionFileReader : public BaseFileReader { public: string GetReaderType() const override; bool UseCastMap() const override; + bool SupportsDeletionFilter() const override; shared_ptr GetUnionData(idx_t file_idx) override; unique_ptr GetStatistics(ClientContext &context, const Identifier &name) override; unique_ptr GetVirtualColumnStatistics(ClientContext &context, column_t virtual_column_id) override; 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 index 9f360503c..7ba24f980 100644 --- 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 @@ -25,8 +25,19 @@ class TableFunctionMultiFileList : public LazyMultiFileList { //! produces TableFunctionMultiFileList(ClientContext &context, const Identifier &function_name, vector inputs, named_argument_map_t named_parameters = named_argument_map_t()); + //! List the files of an already bound table function - no catalog lookup, the bind data is owned by the list + TableFunctionMultiFileList(ClientContext &context, TableFunction function, unique_ptr bind_data, + vector return_types); ~TableFunctionMultiFileList() override; + //! The bind data of the function that produces the files + optional_ptr GetBindData() const { + return bind_data.get(); + } + ClientContext &GetClientContext() const { + return context; + } + //! 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; diff --git a/src/duckdb/src/include/duckdb/common/multi_file/table_function_query_filter.hpp b/src/duckdb/src/include/duckdb/common/multi_file/table_function_query_filter.hpp new file mode 100644 index 000000000..3bdd95e0b --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/multi_file/table_function_query_filter.hpp @@ -0,0 +1,70 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/multi_file/table_function_query_filter.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/multi_file/multi_file_data.hpp" +#include "duckdb/common/open_file_info.hpp" + +namespace duckdb { +class BaseFileReader; +class ClientContext; +class DataChunk; + +//! Row filter described by the open options of a file in a file list: +//! filter_query SQL query that returns the rows of the file to scan as (row_start BIGINT, row_end BIGINT, bits BIT). +//! Every row of the result describes some rows, and the rows to scan are all of them together: +//! - bits is NULL: the rows from row_start up to but not including row_end. A NULL row_start is the +//! start of the file, a NULL row_end is the end of the file +//! - bits is set: a bitmap window - bit i is the row with id row_start + i (row_end is not used). A NULL +//! row_start is the start of the file +class TableFunctionQueryFilter : public DeleteFilter { +public: + //! Create the filter for the file of a reader - returns nullptr if its options do not have a filter query. The + //! query runs in the transaction of the context, and must be a single SELECT statement that does not modify a + //! database + static unique_ptr TryCreate(ClientContext &context, BaseFileReader &reader); + //! The open option that holds the filter query + static constexpr const char *FILTER_QUERY_OPTION = "filter_query"; + + //! Whether the options of a file have a filter query - the rows of such a file cannot be counted from its metadata. + //! Inline: extensions call it without linking the query that TryCreate runs + static bool HasFilterQuery(const OpenFileInfo &file) { + if (!file.extended_info) { + return false; + } + auto entry = file.extended_info->options.find(FILTER_QUERY_OPTION); + return entry != file.extended_info->options.end() && !entry->second.IsNull(); + } + + idx_t Filter(row_t start_row_index, idx_t count, SelectionVector &result_sel) override; + +private: + //! 64 rows of a bitmap window: bit i of the word is the row 64 * index + i + struct ScanWord { + idx_t index; + uint64_t bits; + }; + +private: + void ReadFilterQuery(ClientContext &context, const string &query, const string &path); + void AddRows(DataChunk &chunk); + void AddWindow(idx_t window_start, const char *data, idx_t size); + void AddWindowBits(idx_t row_start, uint64_t bits, idx_t bit_count); + //! Sort the ranges and words, and merge those that overlap or touch + void Finalize(); + +private: + //! The rows to scan as ranges, sorted and not overlapping or touching: from the first row up to but not including + //! the second + vector> scan_ranges; + //! The rows to scan as bitmap windows, as sorted words that are not empty + vector scan_words; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/pipe_file_system.hpp b/src/duckdb/src/include/duckdb/common/pipe_file_system.hpp index 68d9223d0..1e7c4f74f 100644 --- a/src/duckdb/src/include/duckdb/common/pipe_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/pipe_file_system.hpp @@ -14,7 +14,7 @@ namespace duckdb { class PipeFileSystem : public BaseFileSystem { public: - static unique_ptr OpenPipe(QueryContext context, unique_ptr handle); + static unique_ptr OpenPipe(Context &context, unique_ptr handle); int64_t Read(FileHandle &handle, void *buffer, int64_t nr_bytes) override; int64_t Write(FileHandle &handle, void *buffer, int64_t nr_bytes) override; @@ -29,7 +29,7 @@ class PipeFileSystem : public BaseFileSystem { bool CanSeek() override { return false; } - bool IsPipe(const string &filename, optional_ptr opener) override { + bool IsPipe(Context &context, const string &filename) override { return true; } void FileSync(FileHandle &handle) override; diff --git a/src/duckdb/src/include/duckdb/common/query_context.hpp b/src/duckdb/src/include/duckdb/common/query_context.hpp deleted file mode 100644 index acfc2e7d2..000000000 --- a/src/duckdb/src/include/duckdb/common/query_context.hpp +++ /dev/null @@ -1,48 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/common/query_context.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/optional_ptr.hpp" -#include "duckdb/common/winapi.hpp" -#include "duckdb/main/context.hpp" - -namespace duckdb { - -class ClientContext; - -//! The QueryContext wraps optional execution services. -//! It makes query-related information available to operations. -class QueryContext { -public: - QueryContext() { - } - DUCKDB_API QueryContext(optional_ptr client_context); // NOLINT: allow implicit construction - DUCKDB_API QueryContext(ClientContext &client_context); // NOLINT: allow implicit construction - QueryContext(Context &context_p) : context(&context_p) { // NOLINT: allow implicit construction - } - -public: - bool Valid() const { - return context != nullptr; - } - //! The context (null if the context is not valid) - optional_ptr GetContext() const { - return context; - } - //! The client the QueryContext was created from (null if it was created from a Context) - optional_ptr GetClientContext() const { - return client_context; - } - -private: - optional_ptr context; - optional_ptr client_context; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/radix_partitioning.hpp b/src/duckdb/src/include/duckdb/common/radix_partitioning.hpp index e049f0269..d8fcdc0a7 100644 --- a/src/duckdb/src/include/duckdb/common/radix_partitioning.hpp +++ b/src/duckdb/src/include/duckdb/common/radix_partitioning.hpp @@ -116,7 +116,7 @@ class RadixPartitionedColumnData : public PartitionedColumnData { class RadixPartitionedTupleData : public PartitionedTupleData { public: RadixPartitionedTupleData(BufferManager &buffer_manager, shared_ptr layout_ptr, MemoryTag tag, - idx_t radix_bits_p, idx_t hash_col_idx_p, QueryContext context = QueryContext()); + idx_t radix_bits_p, idx_t hash_col_idx_p, Context &context); RadixPartitionedTupleData(RadixPartitionedTupleData &other); ~RadixPartitionedTupleData() override; diff --git a/src/duckdb/src/include/duckdb/common/serializer/async_file_writer.hpp b/src/duckdb/src/include/duckdb/common/serializer/async_file_writer.hpp index aa000f73a..0ce02cd16 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/async_file_writer.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/async_file_writer.hpp @@ -12,7 +12,7 @@ #include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/serializer/async_write_queue.hpp" #include "duckdb/common/serializer/write_stream.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" #include diff --git a/src/duckdb/src/include/duckdb/common/serializer/buffered_file_reader.hpp b/src/duckdb/src/include/duckdb/common/serializer/buffered_file_reader.hpp index 5295bd547..0f63ac20b 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/buffered_file_reader.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/buffered_file_reader.hpp @@ -27,7 +27,6 @@ class BufferedFileReader : public ReadStream { public: void ReadData(data_ptr_t buffer, uint64_t read_size) override; - void ReadData(QueryContext context, data_ptr_t buffer, uint64_t read_size) override; //! Returns true if the reader has finished reading the entire file bool Finished(); diff --git a/src/duckdb/src/include/duckdb/common/serializer/buffered_file_writer.hpp b/src/duckdb/src/include/duckdb/common/serializer/buffered_file_writer.hpp index d97da64f9..e72a5dac3 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/buffered_file_writer.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/buffered_file_writer.hpp @@ -10,7 +10,7 @@ #include "duckdb/common/serializer/write_stream.hpp" #include "duckdb/common/file_system.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { @@ -21,11 +21,10 @@ class BufferedFileWriter : public WriteStream { DUCKDB_API static const FileOpenFlags DEFAULT_OPEN_FLAGS; //! Serializes to a buffer allocated by the serializer, will expand when - //! writing past the initial threshold. The optional QueryContext is used to attribute + //! writing past the initial threshold. The Context is used to attribute //! the written bytes to the query's I/O metrics. - DUCKDB_API BufferedFileWriter(FileSystem &fs, const string &path, - const FileOpenFlags &open_flags = DEFAULT_OPEN_FLAGS, - QueryContext context = QueryContext()); + DUCKDB_API BufferedFileWriter(FileSystem &fs, Context &context, const string &path, + const FileOpenFlags &open_flags = DEFAULT_OPEN_FLAGS); FileSystem &fs; string path; @@ -33,7 +32,7 @@ class BufferedFileWriter : public WriteStream { idx_t offset; idx_t total_written; unique_ptr handle; - QueryContext context; + Context &context; public: DUCKDB_API void WriteData(const_data_ptr_t buffer, idx_t write_size) override; diff --git a/src/duckdb/src/include/duckdb/common/serializer/memory_stream.hpp b/src/duckdb/src/include/duckdb/common/serializer/memory_stream.hpp index b08b34471..f83b3cf7a 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/memory_stream.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/memory_stream.hpp @@ -55,7 +55,6 @@ class MemoryStream : public WriteStream, public ReadStream { //! Read data from the stream. //! Throws if the read would exceed the capacity of the stream void ReadData(data_ptr_t buffer, idx_t read_size) override; - void ReadData(QueryContext context, data_ptr_t buffer, idx_t read_size) override; //! Rewind the stream to the start, keeping the capacity and the backing buffer intact void Rewind(); diff --git a/src/duckdb/src/include/duckdb/common/serializer/read_stream.hpp b/src/duckdb/src/include/duckdb/common/serializer/read_stream.hpp index 964824050..2f91dcba8 100644 --- a/src/duckdb/src/include/duckdb/common/serializer/read_stream.hpp +++ b/src/duckdb/src/include/duckdb/common/serializer/read_stream.hpp @@ -8,7 +8,7 @@ #pragma once -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/common.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/vector.hpp" @@ -21,17 +21,22 @@ class ReadStream { public: // Reads a set amount of data from the stream into the specified buffer and moves the stream forward accordingly virtual void ReadData(data_ptr_t buffer, idx_t read_size) = 0; - virtual void ReadData(QueryContext context, data_ptr_t buffer, idx_t read_size) = 0; + // Variant that attributes the work (e.g. buffer pins) to the given context. Defaults to the plain variant + virtual void ReadData(Context &context, data_ptr_t buffer, idx_t read_size) { + ReadData(buffer, read_size); + } // Reads a type from the stream and moves the stream forward sizeof(T) bytes // The type must be a standard layout type template T Read() { - return Read(QueryContext()); + T value; + ReadData(data_ptr_cast(&value), sizeof(T)); + return value; } template - T Read(QueryContext context) { + T Read(Context &context) { static_assert(std::is_standard_layout(), "Read element must be a standard layout data type"); T value; ReadData(context, data_ptr_cast(&value), sizeof(T)); diff --git a/src/duckdb/src/include/duckdb/common/types/row/integer_partitioned_tuple_data.hpp b/src/duckdb/src/include/duckdb/common/types/row/integer_partitioned_tuple_data.hpp index 5ff4e2cd4..2036f7ad1 100644 --- a/src/duckdb/src/include/duckdb/common/types/row/integer_partitioned_tuple_data.hpp +++ b/src/duckdb/src/include/duckdb/common/types/row/integer_partitioned_tuple_data.hpp @@ -20,8 +20,7 @@ class ClientContext; class IntegerPartitionedTupleData : public PartitionedTupleData { public: IntegerPartitionedTupleData(BufferManager &buffer_manager, shared_ptr layout_ptr, MemoryTag tag, - idx_t key_col_idx, const Value &min_value, idx_t value_count, - QueryContext context = QueryContext()); + idx_t key_col_idx, const Value &min_value, idx_t value_count, Context &context); IntegerPartitionedTupleData(IntegerPartitionedTupleData &other); ~IntegerPartitionedTupleData() override; diff --git a/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp b/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp index f9858a33a..5e9e76534 100644 --- a/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp +++ b/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp @@ -187,7 +187,7 @@ class PartitionedTupleData { protected: //! PartitionedTupleData can only be instantiated by derived classes PartitionedTupleData(PartitionedTupleDataType type, BufferManager &buffer_manager, - shared_ptr &layout_ptr, MemoryTag tag, QueryContext context = QueryContext()); + shared_ptr &layout_ptr, MemoryTag tag, Context &context); PartitionedTupleData(PartitionedTupleData &other); //! Whether to use fixed size map or regular map @@ -214,8 +214,8 @@ class PartitionedTupleData { PartitionedTupleDataType type; BufferManager &buffer_manager; - //! The query context, used to attribute eviction/spill I/O of the partitions to the query - QueryContext context; + //! The context, used to attribute eviction/spill I/O of the partitions to the query + Context &context; shared_ptr stl_allocator; shared_ptr layout_ptr; diff --git a/src/duckdb/src/include/duckdb/common/types/row/tuple_data_allocator.hpp b/src/duckdb/src/include/duckdb/common/types/row/tuple_data_allocator.hpp index 7fc8eafcc..7cf96a65e 100644 --- a/src/duckdb/src/include/duckdb/common/types/row/tuple_data_allocator.hpp +++ b/src/duckdb/src/include/duckdb/common/types/row/tuple_data_allocator.hpp @@ -57,15 +57,15 @@ struct TupleDataBlock { class TupleDataAllocator { public: TupleDataAllocator(BufferManager &buffer_manager, shared_ptr layout_ptr, MemoryTag tag, - shared_ptr stl_allocator, QueryContext context = QueryContext()); + shared_ptr stl_allocator, Context &context); TupleDataAllocator(TupleDataAllocator &allocator); ~TupleDataAllocator(); //! Get the buffer manager BufferManager &GetBufferManager(); - //! Get the query context used to attribute eviction/spill I/O - QueryContext GetContext() const { + //! Get the context used to attribute eviction/spill I/O + Context &GetContext() const { return context; } //! Get the buffer allocator @@ -145,8 +145,8 @@ class TupleDataAllocator { shared_ptr stl_allocator; //! The buffer manager BufferManager &buffer_manager; - //! The query context, used to attribute eviction/spill I/O to the query - QueryContext context; + //! The context, used to attribute eviction/spill I/O to the query + Context &context; //! The layout of the data shared_ptr layout_ptr; const TupleDataLayout &layout; diff --git a/src/duckdb/src/include/duckdb/common/types/row/tuple_data_collection.hpp b/src/duckdb/src/include/duckdb/common/types/row/tuple_data_collection.hpp index 06b1bd048..918aef618 100644 --- a/src/duckdb/src/include/duckdb/common/types/row/tuple_data_collection.hpp +++ b/src/duckdb/src/include/duckdb/common/types/row/tuple_data_collection.hpp @@ -67,7 +67,7 @@ class TupleDataCollection { public: //! Constructs a TupleDataCollection with the specified layout TupleDataCollection(BufferManager &buffer_manager, shared_ptr layout_ptr, MemoryTag tag, - shared_ptr stl_allocator = nullptr, QueryContext context = QueryContext()); + shared_ptr stl_allocator, Context &context); TupleDataCollection(ClientContext &context, shared_ptr layout_ptr, MemoryTag tag, shared_ptr stl_allocator = nullptr); 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 cef8b5dc6..1eea714cf 100644 --- a/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp @@ -17,6 +17,7 @@ namespace duckdb { struct FileSystemRegistry; class DatabaseInstance; class ClientContext; +class Context; //! 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 @@ -32,14 +33,14 @@ class VirtualFileSystem { 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); + DUCKDB_API unique_ptr OpenFile(Context &context, const OpenFileInfo &file, FileOpenFlags flags); //! 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); + DUCKDB_API unique_ptr WrapOpenedFile(Context &context, unique_ptr handle, + const OpenFileInfo &file, const FileOpenFlags &flags); //! 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 BaseFileSystem &FindFileSystem(const string &path, optional_ptr opener); + //! disabled. The overload with a context first loads the extension that provides the file system, if any. + DUCKDB_API BaseFileSystem &FindFileSystem(const string &path); + DUCKDB_API BaseFileSystem &FindFileSystem(Context &context, const string &path); DUCKDB_API void RegisterSubSystem(unique_ptr fs); DUCKDB_API void RegisterCompressionFilesystem(unique_ptr fs); @@ -59,7 +60,7 @@ class VirtualFileSystem { private: BaseFileSystem &FindFileSystem(shared_ptr ®istry, const string &path, - optional_ptr file_opener); + optional_ptr autoload_db); optional_ptr FindFileSystemInternal(FileSystemRegistry ®istry, const string &path); // Return nullptr if compression is not involved, throw exception if compression is requested but no usable // filesystem gets registered. diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_handle.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_handle.hpp index 6f63e6e31..6830c1f48 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_handle.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_file_handle.hpp @@ -73,7 +73,7 @@ class CSVFileHandle { } private: - QueryContext context; + Context &context; unique_ptr file_handle; CSVEncoder encoder; const OpenFileInfo file; 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 6d15e26e7..02410d5bd 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 @@ -64,7 +64,7 @@ class CSVEncoder { string encoding_name; private: - QueryContext context; + Context &context; //! The actual encoded buffer CSVEncoderBuffer encoded_buffer; diff --git a/src/duckdb/src/include/duckdb/function/compression_function.hpp b/src/duckdb/src/include/duckdb/function/compression_function.hpp index 0a3b8c013..9d5c705b0 100644 --- a/src/duckdb/src/include/duckdb/function/compression_function.hpp +++ b/src/duckdb/src/include/duckdb/function/compression_function.hpp @@ -152,8 +152,7 @@ typedef void (*compression_compress_finalize_t)(CompressionState &state); // Uncompress / Scan //===--------------------------------------------------------------------===// typedef void (*compression_init_prefetch_t)(ColumnSegment &segment, PrefetchState &prefetch_state); -typedef unique_ptr (*compression_init_segment_scan_t)(const QueryContext &context, - ColumnSegment &segment); +typedef unique_ptr (*compression_init_segment_scan_t)(Context &context, ColumnSegment &segment); //! Function prototype used for reading an entire vector (STANDARD_VECTOR_SIZE) typedef void (*compression_scan_vector_t)(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, @@ -207,8 +206,7 @@ typedef void (*compression_visit_block_ids_t)(const ColumnSegment &segment, Bloc // GetSegmentInfo (optional) //===--------------------------------------------------------------------===// //! Function prototype for retrieving segment information straight from the column segment -typedef InsertionOrderPreservingMap (*compression_get_segment_info_t)(QueryContext context, - ColumnSegment &segment); +typedef InsertionOrderPreservingMap (*compression_get_segment_info_t)(Context &context, ColumnSegment &segment); enum class CompressionValidity : uint8_t { REQUIRES_VALIDITY, NO_VALIDITY_REQUIRED }; diff --git a/src/duckdb/src/include/duckdb/logging/logger.hpp b/src/duckdb/src/include/duckdb/logging/logger.hpp index 980237f4e..98472dea8 100644 --- a/src/duckdb/src/include/duckdb/logging/logger.hpp +++ b/src/duckdb/src/include/duckdb/logging/logger.hpp @@ -21,8 +21,9 @@ class LogManager; class ColumnDataCollection; class Context; class ThreadContext; -class FileOpener; +class Context; class LogSink; + class ExecutionContext; struct FileHandle; @@ -85,7 +86,6 @@ class Logger { DUCKDB_API static Logger &Get(const ExecutionContext &execution_context); DUCKDB_API static Logger &Get(const ClientContext &client_context); DUCKDB_API static Logger &Get(const Context &context); - DUCKDB_API static Logger &Get(const FileOpener &opener); DUCKDB_API static Logger &Get(const DatabaseInstance &db); DUCKDB_API static Logger &Get(const shared_ptr &logger); diff --git a/src/duckdb/src/include/duckdb/main/attached_database.hpp b/src/duckdb/src/include/duckdb/main/attached_database.hpp index f8b1ffc37..b37966e46 100644 --- a/src/duckdb/src/include/duckdb/main/attached_database.hpp +++ b/src/duckdb/src/include/duckdb/main/attached_database.hpp @@ -18,6 +18,7 @@ namespace duckdb { struct CompiledGrammar; class Catalog; +class Context; class DatabaseInstance; class StorageManager; class TransactionManager; @@ -141,6 +142,8 @@ class AttachedDatabase : public CatalogEntry, public enable_shared_from_this { Context &GetContext() const { return *context; } + //! A ClientContext can be passed where the Context of the client is expected + operator Context &() const { // NOLINT: allow implicit conversion + return GetContext(); + } //! Returns the current query string (if any) const string &GetCurrentQuery(); diff --git a/src/duckdb/src/include/duckdb/main/client_context_file_opener.hpp b/src/duckdb/src/include/duckdb/main/client_context_file_opener.hpp deleted file mode 100644 index 350aa44f3..000000000 --- a/src/duckdb/src/include/duckdb/main/client_context_file_opener.hpp +++ /dev/null @@ -1,38 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/client_context_file_opener.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/file_opener.hpp" - -namespace duckdb { - -class Context; - -//! FileOpener implementation backed by a Context. -//! The Context must outlive the opener. -class ClientContextFileOpener : public FileOpener { -public: - explicit ClientContextFileOpener(Context &context_p) : context(context_p) { - } - - Logger &GetLogger() const override; - SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result, FileOpenerInfo &info) override; - SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result) override; - - Context &TryGetContext() override { - return context; - } - optional_ptr TryGetDatabase() override; - HTTPUtil &GetHTTPUtil() override; - -private: - Context &context; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/client_context_state.hpp b/src/duckdb/src/include/duckdb/main/client_context_state.hpp index 7e74d8883..a7dd7cfd3 100644 --- a/src/duckdb/src/include/duckdb/main/client_context_state.hpp +++ b/src/duckdb/src/include/duckdb/main/client_context_state.hpp @@ -37,6 +37,10 @@ struct BindPreparedStatementCallbackInfo { class ClientContextState { public: virtual ~ClientContextState() = default; + //! Identifies the kind of state for code that only sees the base class, null when not set + virtual const void *GetStateTag() const { + return nullptr; + } virtual void QueryBegin(ClientContext &context) { } virtual void QueryEnd() { @@ -103,17 +107,16 @@ class ClientContextState { class RegisteredStateManager { public: + //! The state under `key`, constructed first if there is none. The constructor runs outside the registry lock, so + //! it may use the context: when several threads race for a key, all but the first state inserted are discarded. template shared_ptr GetOrCreate(const string &key, ARGS &&...args) { - lock_guard l(lock); - auto lookup = registered_state.find(key); - if (lookup != registered_state.end()) { - return shared_ptr_cast(lookup->second); + auto existing = Get(key); + if (existing) { + return existing; } - auto cache = make_shared_ptr(std::forward(args)...); - registered_state[key] = cache; - InvalidateSnapshot(); - return cache; + auto state = GetOrInsert(key, make_shared_ptr(std::forward(args)...)); + return shared_ptr_cast(std::move(state)); } template @@ -126,18 +129,43 @@ class RegisteredStateManager { return shared_ptr_cast(lookup->second); } - void Insert(const string &key, shared_ptr state_p) { + //! Inserts `state_p` under `key` unless the key is taken, and returns the state the key then holds. A state that + //! is not inserted is released after the registry lock is. + shared_ptr GetOrInsert(const string &key, shared_ptr state_p) { + shared_ptr>> old_snapshot; lock_guard l(lock); - if (registered_state.insert(make_pair(key, std::move(state_p))).second) { - InvalidateSnapshot(); + auto lookup = registered_state.find(key); + if (lookup != registered_state.end()) { + return lookup->second; } + registered_state.emplace(key, state_p); + old_snapshot = InvalidateSnapshot(); + return state_p; + } + + void Insert(const string &key, shared_ptr state_p) { + GetOrInsert(key, std::move(state_p)); } void Remove(const string &key) { + RemoveIf(key, [](ClientContextState &) { return true; }); + } + + //! Removes the state under `key` if `predicate` accepts it, which runs under the registry lock. The removed state + //! is released after the registry lock is, so its destructor may use the context. + template + bool RemoveIf(const string &key, PREDICATE &&predicate) { + shared_ptr removed; + shared_ptr>> old_snapshot; lock_guard l(lock); - if (registered_state.erase(key)) { - InvalidateSnapshot(); + auto lookup = registered_state.find(key); + if (lookup == registered_state.end() || !predicate(*lookup->second)) { + return false; } + removed = std::move(lookup->second); + registered_state.erase(lookup); + old_snapshot = InvalidateSnapshot(); + return true; } vector> States() { @@ -184,10 +212,13 @@ class RegisteredStateManager { return states; } - //! Called with the registry lock held after a successful mutation. - void InvalidateSnapshot() { + //! Called with the registry lock held after a successful mutation. Returns the old snapshot, for the caller to + //! release after the lock: it can hold the last reference to a removed state. + shared_ptr>> InvalidateSnapshot() { + auto old_snapshot = state_snapshot.atomic_load(); state_snapshot.atomic_store(nullptr); has_states.store(!registered_state.empty(), std::memory_order_release); + return old_snapshot; } private: diff --git a/src/duckdb/src/include/duckdb/main/client_data.hpp b/src/duckdb/src/include/duckdb/main/client_data.hpp index 3ce095f77..385be3050 100644 --- a/src/duckdb/src/include/duckdb/main/client_data.hpp +++ b/src/duckdb/src/include/duckdb/main/client_data.hpp @@ -19,7 +19,6 @@ class BufferedFileWriter; class ClientContext; class CatalogSearchPath; class ExpressionRewriter; -class FileOpener; class FileSystem; class QueryProfiler; class PreparedStatementData; diff --git a/src/duckdb/src/include/duckdb/main/config.hpp b/src/duckdb/src/include/duckdb/main/config.hpp index 97fd67348..c6aa0e3b3 100644 --- a/src/duckdb/src/include/duckdb/main/config.hpp +++ b/src/duckdb/src/include/duckdb/main/config.hpp @@ -344,14 +344,14 @@ struct DBConfig { SettingLookupResult TryGetDefaultValue(const Identifier &key, optional_ptr option, Value &result) const; - //! The opener (if any) is used to expand "~" using the connection-specific home_directory - bool CanAccessFile(const string &path, FileType type, optional_ptr opener = nullptr); + //! The context is used to expand "~" using the connection-specific home_directory + bool CanAccessFile(Context &context, const string &path, FileType type); void AddAllowedConfig(const Identifier &config_name); - void AddAllowedDirectory(const string &path); - void AddAllowedPath(const string &path); + void AddAllowedDirectory(Context &context, const string &path); + void AddAllowedPath(Context &context, const string &path); //! Replace / reset the allowed directories and paths as a whole (under the lock that guards them) - void SetAllowedDirectories(const vector &paths); - void SetAllowedPaths(const vector &paths); + void SetAllowedDirectories(Context &context, const vector &paths); + void SetAllowedPaths(Context &context, const vector &paths); void ResetAllowedDirectories(); void ResetAllowedPaths(); //! Whether the given optimizer is disabled (disabled_optimizers) @@ -360,10 +360,10 @@ struct DBConfig { DUCKDB_API void SetDisabledOptimizers(set disabled_optimizers); //! Allows a database file and its WAL files, so a database can be opened while external access is disabled. //! Only possible through API calls, not SQL calls. - void AddAllowedDatabasePath(const string &database_path); + void AddAllowedDatabasePath(Context &context, const string &database_path); vector GetAllowedDirectories() const; vector GetAllowedPaths() const; - string SanitizeAllowedPath(const string &path, optional_ptr opener = nullptr) const; + string SanitizeAllowedPath(Context &context, const string &path) const; ExtensionCallbackManager &GetCallbackManager(); const ExtensionCallbackManager &GetCallbackManager() const; diff --git a/src/duckdb/src/include/duckdb/main/context.hpp b/src/duckdb/src/include/duckdb/main/context.hpp index 9253c82e2..a8c0cbcb2 100644 --- a/src/duckdb/src/include/duckdb/main/context.hpp +++ b/src/duckdb/src/include/duckdb/main/context.hpp @@ -21,7 +21,6 @@ class BufferManager; class ClientContext; struct CatalogTransaction; class DatabaseInstance; -class FileOpener; class FileSystem; class Logger; class MetricsManager; @@ -41,8 +40,8 @@ class Context { DUCKDB_API explicit Context(DatabaseInstance &db); DUCKDB_API ~Context(); - //! Turns these into the services of the given client context: creates the client config, the query profiler, - //! the file opener and the client file system. The connection logger is set by the context (see SetLogger). + //! Turns these into the services of the given client context: creates the client config, the query profiler + //! and the client file system. The connection logger is set by the context (see SetLogger). //! The context must own these services - it is kept as a back reference. void InitializeClient(ClientContext &context); @@ -54,6 +53,8 @@ class Context { //! Null-safe variants for optional services DUCKDB_API static optional_ptr TryGetClientContext(optional_ptr services); DUCKDB_API static optional_ptr TryGetQueryProfiler(optional_ptr services); + //! The services of the client if there is one, otherwise the database-wide services + DUCKDB_API static Context &GetOrDatabase(optional_ptr client, DatabaseInstance &db); //! Checks whether the query was interrupted (or timed out, checked only every 256th call) and throws if so - no-op //! without a client DUCKDB_API void FastInterruptCheck() const; @@ -92,8 +93,6 @@ class Context { DUCKDB_API const shared_ptr &GetLoggerPtr() const; //! The file system: client-specific for the services of a ClientContext, otherwise the database file system DUCKDB_API FileSystem &GetFileSystem() const; - //! The file opener of the client - only present for the services of a ClientContext - DUCKDB_API optional_ptr TryGetFileOpener() const; //! The buffer manager wrapper: forwards to the database buffer manager, tracking the allocations of the services DUCKDB_API BufferManager &GetBufferManager() const; //! The database-wide task scheduler @@ -115,7 +114,6 @@ class Context { shared_ptr logger; shared_ptr profiler; unique_ptr registered_state; - unique_ptr file_opener; unique_ptr client_file_system; //! The buffer manager wrapper of the services unique_ptr buffer_manager; diff --git a/src/duckdb/src/include/duckdb/main/database.hpp b/src/duckdb/src/include/duckdb/main/database.hpp index 3670264c4..fad95a9ba 100644 --- a/src/duckdb/src/include/duckdb/main/database.hpp +++ b/src/duckdb/src/include/duckdb/main/database.hpp @@ -44,6 +44,10 @@ class Context; class ExternalFileCache; class ResultSetManager; struct ParserCache; +class DeleteFilter; +class BaseFileReader; + +typedef unique_ptr (*create_file_filter_fun_t)(ClientContext &context, BaseFileReader &reader); class DatabaseInstance : public enable_shared_from_this { friend class DuckDB; @@ -81,6 +85,8 @@ class DatabaseInstance : public enable_shared_from_this { DUCKDB_API void InvokeExtensionEntrypointV2(const ExtensionInitResult &init_result, const string &extension_name, ext_init_c_api_v2_fun_t init_fun, optional_ptr context, bool statically_linked); + //! Creates the row filter that the open options of the file of a reader describe, see create_file_filter + DUCKDB_API unique_ptr CreateFileFilter(ClientContext &context, BaseFileReader &reader); idx_t NumberOfThreads(); @@ -116,6 +122,7 @@ class DatabaseInstance : public enable_shared_from_this { void Configure(DBConfig &config, const char *path); private: + //! Declared first: destroyed last shared_ptr buffer_manager; unique_ptr db_manager; unique_ptr external_resource_type_registry; @@ -125,7 +132,7 @@ class DatabaseInstance : public enable_shared_from_this { unique_ptr connection_manager; unique_ptr extension_manager; ValidChecker db_validity; - //! Declared before the file systems: their openers reference it + //! Declared before the file systems: their contexts reference it unique_ptr services; unique_ptr db_file_system; unique_ptr local_db_file_system; @@ -142,6 +149,9 @@ class DatabaseInstance : public enable_shared_from_this { //! links, and which reaches it through autoloading - would therefore keep all of DuckDB alive in extensions that //! link it statically. Only Initialize names it, and nothing that fails to open a database can reach that. invoke_ext_capi_v2_fun_t invoke_capi_v2; + //! Set in Initialize. TableFunctionQueryFilter runs a query - naming it from the multi-file scan, which extensions + //! instantiate, would link the entire engine into them. + create_file_filter_fun_t create_file_filter; }; //! A describe function for an extension class, so that loading it by class goes through the same path as linked diff --git a/src/duckdb/src/include/duckdb/main/database_file_opener.hpp b/src/duckdb/src/include/duckdb/main/database_file_system.hpp similarity index 55% rename from src/duckdb/src/include/duckdb/main/database_file_opener.hpp rename to src/duckdb/src/include/duckdb/main/database_file_system.hpp index 077cfe031..4d1633e46 100644 --- a/src/duckdb/src/include/duckdb/main/database_file_opener.hpp +++ b/src/duckdb/src/include/duckdb/main/database_file_system.hpp @@ -1,14 +1,13 @@ //===----------------------------------------------------------------------===// // DuckDB // -// duckdb/main/database_file_opener.hpp +// duckdb/main/database_file_system.hpp // // //===----------------------------------------------------------------------===// #pragma once -#include "duckdb/common/file_opener.hpp" #include "duckdb/common/local_file_system.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/main/config.hpp" @@ -20,64 +19,33 @@ namespace duckdb { class DatabaseInstance; -class DatabaseFileOpener : public FileOpener { -public: - explicit DatabaseFileOpener(DatabaseInstance &db_p) : db(db_p), context(db_p.GetContext()) { - } - - Logger &GetLogger() const override { - return Logger::Get(db); - } - - SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result) override { - return db.TryGetCurrentSetting(key, result); - } - - SettingLookupResult TryGetCurrentSetting(const Identifier &key, Value &result, FileOpenerInfo &) override { - return db.TryGetCurrentSetting(key, result); - } - - Context &TryGetContext() override { - return context; - } - - optional_ptr TryGetDatabase() override { - return &db; - } - HTTPUtil &GetHTTPUtil() override { - return HTTPUtil::Get(*TryGetDatabase()); - } - -private: - DatabaseInstance &db; - Context &context; -}; - +//! The file system of a database: bound to the database-wide context class DatabaseFileSystem : public FileSystem { public: - explicit DatabaseFileSystem(DatabaseInstance &db_p) : db(db_p), database_opener(db_p) { + explicit DatabaseFileSystem(DatabaseInstance &db_p) : db(db_p), context(db_p.GetContext()) { } private: VirtualFileSystem &GetFileSystem() const override { return VirtualFileSystem::Get(db); } - optional_ptr GetOpener() const override { - return &database_opener; + Context &GetContext() const override { + return context; } DatabaseInstance &db; - mutable DatabaseFileOpener database_opener; + Context &context; }; +//! The local file system of a database: bound to the database-wide context class LocalDatabaseFileSystem : public FileSystem { public: explicit LocalDatabaseFileSystem(DatabaseInstance &db_p); private: VirtualFileSystem &GetFileSystem() const override; - optional_ptr GetOpener() const override { - return &database_opener; + Context &GetContext() const override { + return context; } //! Every path is local: the default file system if it is local, otherwise the owned local file system optional_ptr GetFixedFileSystem() const override; @@ -85,7 +53,7 @@ class LocalDatabaseFileSystem : public FileSystem { VirtualFileSystem &file_system; //! Only set if the default file system is not local unique_ptr owned_file_system; - mutable DatabaseFileOpener database_opener; + Context &context; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/database_path_and_type.hpp b/src/duckdb/src/include/duckdb/main/database_path_and_type.hpp index 7fe2c9885..4ddb67dfc 100644 --- a/src/duckdb/src/include/duckdb/main/database_path_and_type.hpp +++ b/src/duckdb/src/include/duckdb/main/database_path_and_type.hpp @@ -14,7 +14,7 @@ namespace duckdb { -class QueryContext; +class Context; struct PrefetchedFileData; struct DBPathAndType { @@ -22,11 +22,11 @@ struct DBPathAndType { static void ExtractExtensionPrefix(string &path, string &db_type); //! Check the magic bytes of a file and set the database type. For a DuckDB file, the prefetched header is //! returned through `out_prefetch` when set. - static void CheckMagicBytes(QueryContext context, FileSystem &fs, string &path, string &db_type, + static void CheckMagicBytes(Context &context, FileSystem &fs, string &path, string &db_type, optional_ptr out_prefetch = nullptr); //! Run ExtractExtensionPrefix followed by CheckMagicBytes. Same `out_prefetch` semantics as CheckMagicBytes. - static void ResolveDatabaseType(FileSystem &fs, string &path, string &db_type, + static void ResolveDatabaseType(Context &context, FileSystem &fs, string &path, string &db_type, optional_ptr out_prefetch = nullptr); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/extension_install_info.hpp b/src/duckdb/src/include/duckdb/main/extension_install_info.hpp index 18a80b7fe..fdd1a9292 100644 --- a/src/duckdb/src/include/duckdb/main/extension_install_info.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_install_info.hpp @@ -85,8 +85,8 @@ class ExtensionInstallInfo { void Serialize(Serializer &serializer) const; //! Try to read install info. returns ExtensionInstallMode::UNKNOWN on missing file, and throws on corrupt file - static unique_ptr TryReadInfoFile(FileSystem &fs, const string &info_file_path, - const string &extension_name); + static unique_ptr TryReadInfoFile(Context &context, FileSystem &fs, + const string &info_file_path, const string &extension_name); static unique_ptr Deserialize(Deserializer &deserializer); }; diff --git a/src/duckdb/src/include/duckdb/main/http/http_transport_manager.hpp b/src/duckdb/src/include/duckdb/main/http/http_transport_manager.hpp index a993e35f5..8a1a14b0d 100644 --- a/src/duckdb/src/include/duckdb/main/http/http_transport_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/http/http_transport_manager.hpp @@ -68,8 +68,7 @@ class HTTPTransportManager { public: DUCKDB_API Session CreateSession(DatabaseInstance &db, const string &path) DUCKDB_EXCLUDES(lock); DUCKDB_API Session CreateSession(ClientContext &context, const string &path) DUCKDB_EXCLUDES(lock); - DUCKDB_API Session CreateSession(optional_ptr opener, optional_ptr info) - DUCKDB_EXCLUDES(lock); + DUCKDB_API Session CreateSession(Context &context, optional_ptr info) DUCKDB_EXCLUDES(lock); private: using ClientKey = HTTPClientPool::ClientKey; diff --git a/src/duckdb/src/include/duckdb/main/http/http_transport_manager_state.hpp b/src/duckdb/src/include/duckdb/main/http/http_transport_manager_state.hpp new file mode 100644 index 000000000..413929ef3 --- /dev/null +++ b/src/duckdb/src/include/duckdb/main/http/http_transport_manager_state.hpp @@ -0,0 +1,34 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/main/http/http_transport_manager_state.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/main/http/http_util.hpp" + +namespace duckdb { + +class HTTPTransportManagerState { +public: + HTTPTransportManagerState(shared_ptr http_util_p, HTTPTransportReusePolicy reuse_policy_p, + idx_t provider_epoch_p) + : http_util(std::move(http_util_p)), reuse_policy(reuse_policy_p), provider_epoch(provider_epoch_p) { + } + + //! Provider retained for this publication. + const shared_ptr http_util; + //! Client reuse contract reported by the provider. + const HTTPTransportReusePolicy reuse_policy; + //! Stable manager-issued provider identity. + const idx_t provider_epoch; + //! Current connection generation for explicit invalidation. + uint64_t connection_epoch = 0; + //! Whether epoch exhaustion permanently disabled reuse. + bool reuse_poisoned = false; +}; + +} // namespace duckdb 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 ca6ef720b..1c913294b 100644 --- a/src/duckdb/src/include/duckdb/main/http/http_util.hpp +++ b/src/duckdb/src/include/duckdb/main/http/http_util.hpp @@ -26,8 +26,8 @@ class HTTPUtil; class HTTPRetryBudget; class HTTPTransportManager; class HTTPTransportManagerState; -class FileOpener; -struct FileOpenerInfo; +class Context; +struct FileLookupInfo; struct HTTPParams { explicit HTTPParams(HTTPUtil &http_util) : http_util(http_util) { @@ -69,7 +69,7 @@ struct HTTPParams { shared_ptr logger; public: - void Initialize(optional_ptr opener); + void Initialize(Context &context); DUCKDB_API idx_t GetTransportReuseDomain() const; //! Require server certificate verification for the requests made with these parameters, whatever the settings and //! secrets they were initialized from said. The provider recaptures its connection-reuse domain from the new values @@ -395,8 +395,7 @@ class HTTPUtil { virtual unique_ptr InitializeParameters(DatabaseInstance &db, const string &path); virtual unique_ptr InitializeParameters(ClientContext &context, const string &path); - virtual unique_ptr InitializeParameters(optional_ptr opener, - optional_ptr info); + virtual unique_ptr InitializeParameters(Context &context, optional_ptr info); virtual unique_ptr InitializeClient(HTTPParams &http_params, const string &proto_host_port); DUCKDB_API virtual unique_ptr InitializeClientExtended(HTTPParams &http_params, diff --git a/src/duckdb/src/include/duckdb/main/secret/secret.hpp b/src/duckdb/src/include/duckdb/main/secret/secret.hpp index 08449afa8..252499ac8 100644 --- a/src/duckdb/src/include/duckdb/main/secret/secret.hpp +++ b/src/duckdb/src/include/duckdb/main/secret/secret.hpp @@ -19,9 +19,8 @@ namespace duckdb { class BaseSecret; class Context; struct SecretEntry; -struct FileOpenerInfo; +struct FileLookupInfo; struct CreateSecretInfo; -class FileOpener; //! The lifetime of a secret enum class SecretPersistType : uint8_t { DEFAULT, TEMPORARY, PERSISTENT, TRANSACTION }; @@ -281,12 +280,12 @@ class KeyValueSecret : public BaseSecret { class KeyValueSecretReader { public: //! Manually pass in a secret reference - KeyValueSecretReader(const KeyValueSecret &secret_p, FileOpener &opener_p); + KeyValueSecretReader(const KeyValueSecret &secret_p, Context &context_p); //! Initializes the KeyValueSecretReader by fetching the secret automatically - KeyValueSecretReader(FileOpener &opener_p, optional_ptr info, const char **secret_types, + KeyValueSecretReader(Context &context_p, optional_ptr info, const char **secret_types, idx_t secret_types_len); - KeyValueSecretReader(FileOpener &opener_p, optional_ptr info, const char *secret_type); + KeyValueSecretReader(Context &context_p, optional_ptr info, const char *secret_type); //! Initialize KeyValueSecretReader from a db instance KeyValueSecretReader(DatabaseInstance &db, const char **secret_types, idx_t secret_types_len, string path); diff --git a/src/duckdb/src/include/duckdb/storage/block_manager.hpp b/src/duckdb/src/include/duckdb/storage/block_manager.hpp index 0e73608f1..1f5651ddf 100644 --- a/src/duckdb/src/include/duckdb/storage/block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/block_manager.hpp @@ -14,7 +14,7 @@ #include "duckdb/common/optional.hpp" #include "duckdb/common/optional_idx.hpp" #include "duckdb/common/unordered_map.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/storage/block.hpp" #include "duckdb/storage/storage_info.hpp" @@ -73,21 +73,21 @@ class BlockManager { //! Get the first meta block id virtual idx_t GetMetaBlock() = 0; //! Read the content of the block from disk - virtual void Read(QueryContext context, Block &block) = 0; + virtual void Read(Context &context, Block &block) = 0; //! Read the content of the block from disk - virtual void ReadBlocks(QueryContext context, FileBuffer &buffer, block_id_t start_block, idx_t block_count) = 0; + virtual void ReadBlocks(Context &context, FileBuffer &buffer, block_id_t start_block, idx_t block_count) = 0; //! Writes the block to disk. virtual void Write(FileBuffer &block, block_id_t block_id) = 0; - virtual void Write(QueryContext context, FileBuffer &block, block_id_t block_id); + virtual void Write(Context &context, FileBuffer &block, block_id_t block_id); //! Writes the block to disk. void Write(Block &block) { Write(block, block.id); } //! Write the header of a checkpoint with the given bound; should be the final step of a checkpoint //! What the header frees waits for the transactions that started before read_stamp, if any are active - virtual void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound, - transaction_t read_stamp, transaction_t lowest_active_start) = 0; + virtual void WriteHeader(Context &context, DatabaseHeader header, VisibilityBound bound, transaction_t read_stamp, + transaction_t lowest_active_start) = 0; //! Lets the blocks be reused that headers freed before every active transaction started virtual void ReuseFreedBlocks(transaction_t lowest_active_start) { } @@ -119,11 +119,11 @@ class BlockManager { //! This can only be safely used when there is no other (lingering) usage of old_block //! If there is concurrent usage of the block elsewhere - use the THREAD_SAFE mode which creates an extra copy //! Unless a tag is given, keep old_block's tag, except IN_MEMORY_TABLE becomes BASE_TABLE. - shared_ptr ConvertToPersistent(QueryContext context, block_id_t block_id, + shared_ptr ConvertToPersistent(Context &context, block_id_t block_id, shared_ptr old_block, BufferHandle old_handle, ConvertToPersistentMode mode = ConvertToPersistentMode::DESTRUCTIVE, optional tag = nullopt); - shared_ptr ConvertToPersistent(QueryContext context, block_id_t block_id, + shared_ptr ConvertToPersistent(Context &context, block_id_t block_id, shared_ptr old_block, ConvertToPersistentMode mode = ConvertToPersistentMode::DESTRUCTIVE, optional tag = nullopt); diff --git a/src/duckdb/src/include/duckdb/storage/buffer/block_handle.hpp b/src/duckdb/src/include/duckdb/storage/buffer/block_handle.hpp index 11c6bcc4f..87f9bc9c2 100644 --- a/src/duckdb/src/include/duckdb/storage/buffer/block_handle.hpp +++ b/src/duckdb/src/include/duckdb/storage/buffer/block_handle.hpp @@ -226,8 +226,10 @@ class BlockMemory : public enable_shared_from_this { //! The state here can change if the block lock is held. //! However, this method does not hold the block lock. CanUnloadResult CanUnload() const; - unique_ptr UnloadAndTakeBlock(BlockLock &l, QueryContext context = QueryContext()); - void Unload(BlockLock &l, QueryContext context = QueryContext()); + unique_ptr UnloadAndTakeBlock(BlockLock &l, Context &context); + unique_ptr UnloadAndTakeBlock(BlockLock &l); + void Unload(BlockLock &l, Context &context); + void Unload(BlockLock &l); private: //! A reference to the buffer manager. @@ -312,7 +314,7 @@ class BlockHandle : public enable_shared_from_this { public: BufferHandle LoadFromBuffer(BlockLock &l, data_ptr_t data, unique_ptr reusable_buffer, BufferPoolReservation reservation); - BufferHandle Load(BlockLock &l, QueryContext context, unique_ptr buffer = nullptr); + BufferHandle Load(BlockLock &l, Context &context, unique_ptr buffer = nullptr); private: //! The block manager, which loads the block. diff --git a/src/duckdb/src/include/duckdb/storage/buffer/buffer_pool.hpp b/src/duckdb/src/include/duckdb/storage/buffer/buffer_pool.hpp index b2455e3d8..c87cee06d 100644 --- a/src/duckdb/src/include/duckdb/storage/buffer/buffer_pool.hpp +++ b/src/duckdb/src/include/duckdb/storage/buffer/buffer_pool.hpp @@ -51,7 +51,7 @@ class BufferPool { //! Set a new memory limit to the buffer pool, throws an exception if the new limit is too low and not enough //! blocks can be evicted - void SetLimit(idx_t limit, const char *exception_postscript); + void SetLimit(Context &context, idx_t limit, const char *exception_postscript); //! If bulk deallocation larger than this occurs, flush outstanding allocations void SetAllocatorBulkDeallocationFlushThreshold(idx_t threshold); @@ -89,9 +89,9 @@ class BufferPool { bool success; TempBufferPoolReservation reservation; }; - virtual EvictionResult EvictBlocks(QueryContext context, MemoryTag tag, idx_t extra_memory, idx_t memory_limit, + virtual EvictionResult EvictBlocks(Context &context, MemoryTag tag, idx_t extra_memory, idx_t memory_limit, unique_ptr *buffer = nullptr); - virtual EvictionResult EvictBlocksInternal(QueryContext context, EvictionQueue &queue, MemoryTag tag, + virtual EvictionResult EvictBlocksInternal(Context &context, EvictionQueue &queue, MemoryTag tag, idx_t extra_memory, idx_t memory_limit, unique_ptr *buffer = nullptr); diff --git a/src/duckdb/src/include/duckdb/storage/buffer_manager.hpp b/src/duckdb/src/include/duckdb/storage/buffer_manager.hpp index 9d425f37d..c2a740bb7 100644 --- a/src/duckdb/src/include/duckdb/storage/buffer_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/buffer_manager.hpp @@ -58,17 +58,17 @@ class BufferManager { virtual BufferHandle Allocate(MemoryTag tag, BlockManager *block_manager, bool can_destroy = true) = 0; //! Allocate variants that attribute the (possible) eviction/spill I/O to a query. The base implementations //! ignore the context and delegate to the variants above; StandardBufferManager threads it through. - virtual BufferHandle Allocate(QueryContext context, MemoryTag tag, idx_t block_size, bool can_destroy = true); - virtual BufferHandle Allocate(QueryContext context, MemoryTag tag, BlockManager *block_manager, + virtual BufferHandle Allocate(Context &context, MemoryTag tag, idx_t block_size, bool can_destroy = true); + virtual BufferHandle Allocate(Context &context, MemoryTag tag, BlockManager *block_manager, bool can_destroy = true); //! Pin a block handle. virtual BufferHandle Pin(shared_ptr &handle) = 0; - virtual BufferHandle Pin(const QueryContext &context, shared_ptr &handle) = 0; + virtual BufferHandle Pin(Context &context, shared_ptr &handle) = 0; //! Pre-fetch a series of blocks. //! Using this function is a performance suggestion. - virtual void Prefetch(QueryContext context, vector> &handles) = 0; + virtual void Prefetch(Context &context, vector> &handles) = 0; //! Creates one async task per contiguous run of blocks needing load - virtual vector> CreatePrefetchTasks(QueryContext context, + virtual vector> CreatePrefetchTasks(Context &context, vector> &handles); //! Unpin a block handle. virtual void Unpin(shared_ptr &handle) = 0; @@ -140,9 +140,9 @@ class BufferManager { //! Add the block handle to the eviction queue. virtual void AddToEvictionQueue(shared_ptr &handle); //! Write a temporary file buffer. - virtual void WriteTemporaryBuffer(QueryContext context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer); + virtual void WriteTemporaryBuffer(Context &context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer); //! Read a temporary buffer. - virtual unique_ptr ReadTemporaryBuffer(QueryContext context, MemoryTag tag, BlockHandle &block, + virtual unique_ptr ReadTemporaryBuffer(Context &context, MemoryTag tag, BlockHandle &block, unique_ptr buffer); //! Delete the temporary file containing the block memory. virtual void DeleteTemporaryFile(BlockMemory &memory); diff --git a/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp b/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp index 99c461055..8e0af5892 100644 --- a/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/checkpoint_manager.hpp @@ -69,8 +69,7 @@ class ActiveCheckpointWrapper { class CheckpointWriter { public: - CheckpointWriter(AttachedDatabase &db, QueryContext context, - optional_ptr checkpoint_context = nullptr); + CheckpointWriter(AttachedDatabase &db, Context &context, optional_ptr checkpoint_context = nullptr); virtual ~CheckpointWriter(); //! The database @@ -151,7 +150,7 @@ class SingleFileCheckpointWriter final : public CheckpointWriter { friend class SingleFileTableDataWriter; public: - SingleFileCheckpointWriter(QueryContext context, AttachedDatabase &db, BlockManager &block_manager, + SingleFileCheckpointWriter(Context &context, AttachedDatabase &db, BlockManager &block_manager, CheckpointOptions options, optional_ptr checkpoint_context = nullptr); ~SingleFileCheckpointWriter() override; diff --git a/src/duckdb/src/include/duckdb/storage/compression/alp/alp_scan.hpp b/src/duckdb/src/include/duckdb/storage/compression/alp/alp_scan.hpp index 231ad893c..a461664e8 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/alp/alp_scan.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/alp/alp_scan.hpp @@ -283,7 +283,7 @@ struct AlpScanState : public SegmentScanState { }; template -unique_ptr AlpInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr AlpInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); auto result = make_uniq_base>(std::move(handle), segment); diff --git a/src/duckdb/src/include/duckdb/storage/compression/alprd/alprd_scan.hpp b/src/duckdb/src/include/duckdb/storage/compression/alprd/alprd_scan.hpp index f344a96e0..37da80e5c 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/alprd/alprd_scan.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/alprd/alprd_scan.hpp @@ -301,7 +301,7 @@ struct AlpRDScanState : public SegmentScanState { }; template -unique_ptr AlpRDInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr AlpRDInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); auto result = make_uniq_base>(std::move(handle), segment); diff --git a/src/duckdb/src/include/duckdb/storage/compression/chimp/chimp_scan.hpp b/src/duckdb/src/include/duckdb/storage/compression/chimp/chimp_scan.hpp index 829b00981..32c205003 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/chimp/chimp_scan.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/chimp/chimp_scan.hpp @@ -308,7 +308,7 @@ struct ChimpScanState : public SegmentScanState { }; template -unique_ptr ChimpInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr ChimpInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); auto result = make_uniq_base>(std::move(handle), segment); diff --git a/src/duckdb/src/include/duckdb/storage/compression/empty_validity.hpp b/src/duckdb/src/include/duckdb/storage/compression/empty_validity.hpp index 9e1de9c0b..1743c0c98 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/empty_validity.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/empty_validity.hpp @@ -73,7 +73,7 @@ class EmptyValidityCompression { auto &checkpoint_state = checkpoint_data.GetCheckpointState(); checkpoint_state.FlushSegment(std::move(compressed_segment), std::move(handle), 0); } - static unique_ptr InitScan(const QueryContext &context, ColumnSegment &segment) { + static unique_ptr InitScan(Context &context, ColumnSegment &segment) { return make_uniq(); } static void ScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, diff --git a/src/duckdb/src/include/duckdb/storage/compression/patas/patas_scan.hpp b/src/duckdb/src/include/duckdb/storage/compression/patas/patas_scan.hpp index eda924e65..a3af103be 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/patas/patas_scan.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/patas/patas_scan.hpp @@ -261,7 +261,7 @@ struct PatasScanState : public SegmentScanState { }; template -unique_ptr PatasInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr PatasInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); auto result = make_uniq_base>(std::move(handle), segment); diff --git a/src/duckdb/src/include/duckdb/storage/compression/roaring/roaring.hpp b/src/duckdb/src/include/duckdb/storage/compression/roaring/roaring.hpp index b83c2a5da..4948bd9c1 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/roaring/roaring.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/roaring/roaring.hpp @@ -674,7 +674,7 @@ struct RoaringScanState : public SegmentScanState { static SegmentLayout ReadLayout(const BufferHandle &handle, const ColumnSegment &segment); - explicit RoaringScanState(const QueryContext &context, ColumnSegment &segment); + explicit RoaringScanState(Context &context, ColumnSegment &segment); public: bool UseContainerStateCache(idx_t container_index, idx_t internal_offset); diff --git a/src/duckdb/src/include/duckdb/storage/data_table.hpp b/src/duckdb/src/include/duckdb/storage/data_table.hpp index b3b32f096..47cc78aba 100644 --- a/src/duckdb/src/include/duckdb/storage/data_table.hpp +++ b/src/duckdb/src/include/duckdb/storage/data_table.hpp @@ -214,8 +214,8 @@ class DataTable : public enable_shared_from_this { void MergeStorage(RowGroupCollection &data, optional_ptr commit_state); //! Remove the row identifiers from the indexes of the table added before the bound - void RemoveFromIndexes(const QueryContext &context, Vector &row_identifiers, idx_t count, - IndexRemovalType removal_type, optional_idx checkpoint_id, VisibilityBound bound); + void RemoveFromIndexes(Context &context, Vector &row_identifiers, idx_t count, IndexRemovalType removal_type, + optional_idx checkpoint_id, VisibilityBound bound); void SetAsMainTable() { this->version = DataTableVersion::MAIN_TABLE; @@ -261,11 +261,10 @@ class DataTable : public enable_shared_from_this { idx_t GetRowGroupCountWithLocalStorage(ClientContext &context); vector - GetColumnSegmentInfo(const QueryContext &context, + GetColumnSegmentInfo(Context &context, const ColumnSegmentInfoScanOptions &options = ColumnSegmentInfoScanOptions {}); void InitializeColumnSegmentInfoScan(ColumnSegmentInfoScanState &state); - bool ScanColumnSegmentInfo(const QueryContext &context, ColumnSegmentInfoScanState &state, - vector &result); + bool ScanColumnSegmentInfo(Context &context, ColumnSegmentInfoScanState &state, vector &result); //! Scans the next chunk for the CREATE INDEX operator, as of the build commit when building in place bool CreateIndexScan(TableScanState &state, DataChunk &result, optional_ptr build); diff --git a/src/duckdb/src/include/duckdb/storage/database_handle.hpp b/src/duckdb/src/include/duckdb/storage/database_handle.hpp index 60ea2c828..f2552a7ae 100644 --- a/src/duckdb/src/include/duckdb/storage/database_handle.hpp +++ b/src/duckdb/src/include/duckdb/storage/database_handle.hpp @@ -25,13 +25,13 @@ struct DatabaseHandle { //! Open a fresh handle for the database file. A header prefix in `options.prefetched` (from file-type //! detection) is adopted to serve the initial header reads from memory. With a client in `context`, the file //! is opened through that client's file system, so the handle uses its settings and logger. - static unique_ptr Open(QueryContext context, AttachedDatabase &db, const string &path, + static unique_ptr Open(Context &context, AttachedDatabase &db, const string &path, const StorageManagerOptions &options, DatabaseOpenMode open_mode); bool OnDiskFile() const; - void CheckMagicBytes(QueryContext context); - void Read(QueryContext context, FileBuffer &block, uint64_t location) const; - void Write(QueryContext context, FileBuffer &block, uint64_t location); + void CheckMagicBytes(Context &context); + void Read(Context &context, FileBuffer &block, uint64_t location) const; + void Write(Context &context, FileBuffer &block, uint64_t location); void Sync(); void Truncate(idx_t new_size); @@ -44,9 +44,9 @@ struct DatabaseHandle { //! Throws if a write at [required_size] would exceed the mmap reserve. No-op otherwise. void EnsureMappedSize(idx_t required_size) const; - static unique_ptr OpenMemoryMap(QueryContext context, AttachedDatabase &db, const string &path, + static unique_ptr OpenMemoryMap(Context &context, AttachedDatabase &db, const string &path, const StorageManagerOptions &options, DatabaseOpenMode open_mode); - static unique_ptr OpenFile(QueryContext context, AttachedDatabase &db, const string &path, + static unique_ptr OpenFile(Context &context, AttachedDatabase &db, const string &path, const StorageManagerOptions &options, DatabaseOpenMode open_mode); private: diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp index 11ee6baeb..c356c69f9 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp @@ -11,10 +11,9 @@ #include "duckdb/common/file_system.hpp" #include "duckdb/common/enums/cache_validation_mode.hpp" #include "duckdb/common/file_open_flags.hpp" -#include "duckdb/common/file_opener.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/open_file_info.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/shared_ptr.hpp" #include "duckdb/common/winapi.hpp" #include "duckdb/storage/external_file_cache/external_file_cache.hpp" @@ -30,7 +29,7 @@ class FileOpenFlags; class FileSystem; struct FileHandle; struct NetworkThroughputEstimate; -class QueryContext; +class Context; class CachingFileSystem; struct ReadThroughputEstimator { @@ -57,8 +56,8 @@ struct CachingFileHandle { using CachedFile = ExternalFileCache::CachedFile; private: - CachingFileHandle(QueryContext context, CachingFileSystem &caching_file_system, const OpenFileInfo &path, - FileOpenFlags flags, optional_ptr opener); + CachingFileHandle(Context &context, CachingFileSystem &caching_file_system, const OpenFileInfo &path, + FileOpenFlags flags); public: DUCKDB_API ~CachingFileHandle(); @@ -78,12 +77,12 @@ struct CachingFileHandle { //! Read [nr_bytes] bytes and sets [nr_bytes] to the actually read bytes. DUCKDB_API FileBufferHandleGroup Read(idx_t &nr_bytes); //! Read and record time - DUCKDB_API void ReadAndRecord(QueryContext context, data_ptr_t buffer, idx_t nr_bytes, idx_t location); + DUCKDB_API void ReadAndRecord(Context &context, data_ptr_t buffer, idx_t nr_bytes, idx_t location); //! Whether responses observed by this handle prohibit sharing cached data (e.g., HTTP no-store/Vary) DUCKDB_API bool IsCacheReuseProhibited(); //! Get some properties of the file DUCKDB_API string GetPath() const; - DUCKDB_API optional_ptr GetOpener() const; + DUCKDB_API idx_t GetFileSize(); DUCKDB_API timestamp_t GetLastModifiedTime(); DUCKDB_API string GetVersionTag(); @@ -123,7 +122,7 @@ struct CachingFileHandle { void RecordReadThroughput(double total_seconds, idx_t bytes); private: - QueryContext context; + Context &context; //! The file system, held directly because the caching file system can be destroyed before this handle FileSystem &file_system; @@ -135,8 +134,6 @@ struct CachingFileHandle { OpenFileInfo path; //! Flags used to open the file FileOpenFlags flags; - //! File opener, which contains file open context. - optional_ptr opener; //! Cache validation mode for this file CacheValidationMode validate; //! Associated cached file. @@ -171,11 +168,8 @@ class CachingFileSystem { public: DUCKDB_API static CachingFileSystem Get(ClientContext &context); - DUCKDB_API unique_ptr OpenFile(const OpenFileInfo &path, const FileOpenFlags &flags, - optional_ptr opener = nullptr); - DUCKDB_API unique_ptr OpenFile(QueryContext context, const OpenFileInfo &path, - const FileOpenFlags &flags, - optional_ptr opener = nullptr); + DUCKDB_API unique_ptr OpenFile(Context &context, const OpenFileInfo &path, + const FileOpenFlags &flags); private: //! The Client FileSystem (needs to be client-specific so we can do, e.g., HTTPFS profiling) 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 4edc8a781..9300bca5e 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 @@ -9,7 +9,7 @@ #pragma once #include "duckdb/common/enable_shared_from_this_ipp.hpp" -#include "duckdb/common/file_opener.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/winapi.hpp" #include "duckdb/storage/external_file_cache/caching_file_system.hpp" @@ -56,10 +56,8 @@ class CachingFileSystemWrapper : public BaseFileSystem, public enable_shared_fro DUCKDB_API std::string GetName() const override; - DUCKDB_API unique_ptr OpenFile(const string &path, FileOpenFlags flags, - optional_ptr opener) override; - DUCKDB_API unique_ptr OpenFile(const OpenFileInfo &path, FileOpenFlags flags, - optional_ptr opener); + DUCKDB_API unique_ptr OpenFile(Context &context, const string &path, FileOpenFlags flags) override; + DUCKDB_API unique_ptr OpenFile(Context &context, const OpenFileInfo &path, FileOpenFlags flags); DUCKDB_API void Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) override; DUCKDB_API void Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) override; @@ -72,34 +70,33 @@ class CachingFileSystemWrapper : public BaseFileSystem, public enable_shared_fro DUCKDB_API string GetVersionTag(FileHandle &handle) override; DUCKDB_API FileType GetFileType(FileHandle &handle) override; DUCKDB_API FileMetadata Stats(FileHandle &handle) override; - DUCKDB_API optional GetStatsIfExists(const OpenFileInfo &file, - optional_ptr opener) override; + DUCKDB_API optional GetStatsIfExists(Context &context, const OpenFileInfo &file) override; DUCKDB_API void Truncate(FileHandle &handle, int64_t new_size) override; DUCKDB_API void FileSync(FileHandle &handle) override; - DUCKDB_API bool DirectoryExists(const string &directory, optional_ptr opener) override; - DUCKDB_API void CreateDirectory(const string &directory, optional_ptr opener) override; - DUCKDB_API bool CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener) override; - DUCKDB_API void CreateDirectoriesRecursive(const string &path, optional_ptr opener) override; - DUCKDB_API void RemoveDirectory(const string &directory, optional_ptr opener) override; - DUCKDB_API bool RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener) override; + DUCKDB_API bool DirectoryExists(Context &context, const string &directory) override; + DUCKDB_API void CreateDirectory(Context &context, const string &directory) override; + DUCKDB_API bool CreateDirectoryExtended(Context &context, const string &directory, + const CreateDirectoryOptions &options) override; + DUCKDB_API void CreateDirectoriesRecursive(Context &context, const string &path) override; + DUCKDB_API void RemoveDirectory(Context &context, const string &directory) override; + DUCKDB_API bool RemoveDirectoryExtended(Context &context, const string &directory, + const RemoveDirectoryOptions &options) override; - DUCKDB_API bool ListFiles(const string &directory, const std::function &callback, - FileOpener *opener) override; + DUCKDB_API bool ListFiles(Context &context, const string &directory, + const std::function &callback) override; - DUCKDB_API void MoveFile(const string &source, const string &target, optional_ptr opener) override; - DUCKDB_API bool FileExists(const string &filename, optional_ptr opener) override; - DUCKDB_API bool IsPipe(const string &filename, optional_ptr opener) override; - DUCKDB_API void RemoveFile(const string &filename, optional_ptr opener) override; - DUCKDB_API bool TryRemoveFile(const string &filename, optional_ptr opener) override; + DUCKDB_API void MoveFile(Context &context, const string &source, const string &target) override; + DUCKDB_API bool FileExists(Context &context, const string &filename) override; + DUCKDB_API bool IsPipe(Context &context, const string &filename) override; + DUCKDB_API void RemoveFile(Context &context, const string &filename) override; + DUCKDB_API bool TryRemoveFile(Context &context, const string &filename) override; DUCKDB_API string GetHomeDirectory() override; DUCKDB_API string ExpandPath(const string &path) override; DUCKDB_API string PathSeparator(const string &path) override; - DUCKDB_API vector Glob(const string &path, FileOpener *opener) override; + DUCKDB_API vector Glob(Context &context, const string &path) override; DUCKDB_API bool CanHandleFile(const string &fpath) override; @@ -110,15 +107,15 @@ class CachingFileSystemWrapper : public BaseFileSystem, public enable_shared_fro DUCKDB_API bool IsManuallySet() override; DUCKDB_API bool OnDiskFile(FileHandle &handle) override; - DUCKDB_API unique_ptr OpenCompressedFile(QueryContext context, unique_ptr handle, + DUCKDB_API unique_ptr OpenCompressedFile(Context &context, unique_ptr handle, bool write) override; protected: - DUCKDB_API unique_ptr OpenFileExtended(const OpenFileInfo &path, FileOpenFlags flags, - optional_ptr opener) override; + DUCKDB_API unique_ptr OpenFileExtended(Context &context, const OpenFileInfo &path, + FileOpenFlags flags) override; DUCKDB_API bool SupportsOpenFileExtended() const override; - DUCKDB_API bool ListFilesExtended(const string &directory, const std::function &callback, - optional_ptr opener) override; + DUCKDB_API bool ListFilesExtended(Context &context, const string &directory, + const std::function &callback) override; DUCKDB_API bool SupportsListFilesExtended() const override; private: @@ -127,7 +124,7 @@ class CachingFileSystemWrapper : public BaseFileSystem, public enable_shared_fro // Return an optional caching file handle, if certain filepath is cached. CachingFileHandle *GetCachingHandleIfPossible(FileHandle &handle); - //! The bound file system the files are opened with; it pushes its own opener + //! The bound file system the files are opened with; it passes its own context FileSystem &underlying_file_system; CachingFileSystem caching_file_system; CachingMode caching_mode; diff --git a/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp b/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp index f07174786..142288930 100644 --- a/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp @@ -53,19 +53,19 @@ class InMemoryBlockManager : public BlockManager { throw InternalException("Cannot perform IO in in-memory database - GetMetaBlock!"); } - void Read(QueryContext context, Block &block) override { + void Read(Context &context, Block &block) override { throw InternalException("Cannot perform IO in in-memory database - Read!"); } - void ReadBlocks(QueryContext context, FileBuffer &buffer, block_id_t start_block, idx_t block_count) override { + void ReadBlocks(Context &context, FileBuffer &buffer, block_id_t start_block, idx_t block_count) override { throw InternalException("Cannot perform IO in in-memory database - ReadBlocks!"); } void Write(FileBuffer &block, block_id_t block_id) override { throw InternalException("Cannot perform IO in in-memory database - Write!"); } - void Write(QueryContext context, FileBuffer &block, block_id_t block_id) override { + void Write(Context &context, FileBuffer &block, block_id_t block_id) override { throw InternalException("Cannot perform IO in in-memory database - Write with client context!"); } - void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound, transaction_t read_stamp, + void WriteHeader(Context &context, DatabaseHeader header, VisibilityBound bound, transaction_t read_stamp, transaction_t lowest_active_start) override { throw InternalException("Cannot perform IO in in-memory database - WriteHeader!"); } diff --git a/src/duckdb/src/include/duckdb/storage/magic_bytes.hpp b/src/duckdb/src/include/duckdb/storage/magic_bytes.hpp index 0fbf2d0c5..fcfcba360 100644 --- a/src/duckdb/src/include/duckdb/storage/magic_bytes.hpp +++ b/src/duckdb/src/include/duckdb/storage/magic_bytes.hpp @@ -13,7 +13,7 @@ namespace duckdb { class FileSystem; -class QueryContext; +class Context; struct PrefetchedFileData; enum class DataFileType : uint8_t { @@ -28,7 +28,7 @@ class MagicBytes { public: //! Detect the file type at `path` from its magic bytes. For a DuckDB file, a prefetched header prefix is //! returned through `out_prefetch` (when set) so a later storage open reuses it instead of re-reading. - static DataFileType CheckMagicBytes(QueryContext context, FileSystem &fs, const string &path, + static DataFileType CheckMagicBytes(Context &context, FileSystem &fs, const string &path, optional_ptr out_prefetch = nullptr); }; diff --git a/src/duckdb/src/include/duckdb/storage/metadata/metadata_manager.hpp b/src/duckdb/src/include/duckdb/storage/metadata/metadata_manager.hpp index ab92ae13d..ee54b3084 100644 --- a/src/duckdb/src/include/duckdb/storage/metadata/metadata_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/metadata/metadata_manager.hpp @@ -61,6 +61,7 @@ class MetadataManager { public: MetadataManager(BlockManager &block_manager, BufferManager &buffer_manager); + DatabaseInstance &GetDatabase(); ~MetadataManager(); BufferManager &GetBufferManager() const { @@ -70,7 +71,7 @@ class MetadataManager { MetadataHandle AllocateHandle(); MetadataHandle Pin(const MetadataPointer &pointer); - MetadataHandle Pin(const QueryContext &context, const MetadataPointer &pointer); + MetadataHandle Pin(Context &context, const MetadataPointer &pointer); MetaBlockPointer GetDiskPointer(const MetadataPointer &pointer, uint32_t offset = 0); MetadataPointer FromDiskPointer(MetaBlockPointer pointer); @@ -80,7 +81,7 @@ class MetadataManager { static MetaBlockPointer FromBlockPointer(BlockPointer block_pointer, const idx_t metadata_block_size); //! Flush all blocks to disk - void Flush(QueryContext context = QueryContext()); + void Flush(Context &context); bool BlockIsModified(const MetaBlockPointer &ptr); bool BlockHasBeenCleared(const MetaBlockPointer &ptr); diff --git a/src/duckdb/src/include/duckdb/storage/metadata/metadata_reader.hpp b/src/duckdb/src/include/duckdb/storage/metadata/metadata_reader.hpp index 84175f30a..7134e6879 100644 --- a/src/duckdb/src/include/duckdb/storage/metadata/metadata_reader.hpp +++ b/src/duckdb/src/include/duckdb/storage/metadata/metadata_reader.hpp @@ -27,7 +27,7 @@ class MetadataReader : public ReadStream { //! Read content of size read_size into the buffer void ReadData(data_ptr_t buffer, idx_t read_size) override; - void ReadData(QueryContext context, data_ptr_t buffer, idx_t read_size) override; + void ReadData(Context &context, data_ptr_t buffer, idx_t read_size) override; MetaBlockPointer GetMetaBlockPointer(); @@ -41,7 +41,7 @@ class MetadataReader : public ReadStream { void ReadNextBlock(); - void ReadNextBlock(QueryContext context); + void ReadNextBlock(Context &context); MetadataPointer FromDiskPointer(MetaBlockPointer pointer); diff --git a/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp b/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp index 5c6f8d83b..68f2643b0 100644 --- a/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp @@ -13,7 +13,7 @@ #include "duckdb/common/optional.hpp" #include "duckdb/common/optional_idx.hpp" #include "duckdb/common/optional_ptr.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/unique_ptr.hpp" #include "duckdb/storage/block.hpp" #include @@ -64,9 +64,6 @@ class PartialBlockManager { //! The source is neither modified nor retained; destination and packable lifetime rules are as above. optional Write(Context &context, BlockPackable &packable, const BufferHandle &source, uint32_t byte_size); - //! As above, for index checkpoints, whose Index::Checkpoint API does not provide a context: blocks this flushes - //! are not attributed to a query. - optional Write(BlockPackable &packable, const BufferHandle &source, uint32_t byte_size); //! Reserve a disk block ID, using checkpoint accounting in FULL_CHECKPOINT mode; not for in-memory storage. block_id_t GetFreeBlockId(); @@ -88,9 +85,9 @@ class PartialBlockManager { //! Remove the block with least free space if the map limit is exceeded; otherwise return nullptr. unique_ptr PruneFreeList(); //! Consume the block, retaining it if reusable or flushing it otherwise; also flush any pruned map entry. - void RetainOrFlush(optional_ptr context, unique_ptr partial_block); + void RetainOrFlush(Context &context, unique_ptr partial_block); //! Store a copy of the source in a block and retain or flush it. - optional WriteCopy(optional_ptr context, BlockPackable &packable, const BufferHandle &source, + optional WriteCopy(Context &context, BlockPackable &packable, const BufferHandle &source, uint32_t byte_size); private: diff --git a/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp b/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp index 3e2db79ba..ea5308f9e 100644 --- a/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp @@ -76,10 +76,10 @@ class SingleFileBlockManager : public BlockManager { ~SingleFileBlockManager() override; //! Creates a new database. - void CreateNewDatabase(QueryContext context); + void CreateNewDatabase(Context &context); //! Loads an existing database. We pass the provided block allocation size as a parameter //! to detect inconsistencies with the file header. - void LoadExistingDatabase(QueryContext context); + void LoadExistingDatabase(Context &context); //! Creates a new Block using the specified block_id and returns a pointer unique_ptr ConvertBlock(block_id_t block_id, FileBuffer &source_buffer) override; @@ -109,19 +109,19 @@ class SingleFileBlockManager : public BlockManager { //! Return the meta block id idx_t GetMetaBlock() override; //! Read the content of the block from disk - void Read(QueryContext context, Block &block) override; + void Read(Context &context, Block &block) override; //! Read individual blocks void ReadBlock(Block &block, bool skip_block_header = false) const; void ReadBlock(data_ptr_t internal_buffer, uint64_t block_size, bool skip_block_header = false) const; //! Read the content of a range of blocks into a buffer - void ReadBlocks(QueryContext context, FileBuffer &buffer, block_id_t start_block, idx_t block_count) override; + void ReadBlocks(Context &context, FileBuffer &buffer, block_id_t start_block, idx_t block_count) override; //! Write the block to disk. Use Write with client context instead. void Write(FileBuffer &buffer, block_id_t block_id) override; //! Write the block to disk. - void Write(QueryContext context, FileBuffer &buffer, block_id_t block_id) override; + void Write(Context &context, FileBuffer &buffer, block_id_t block_id) override; //! Write the header to disk, this is the final step of the checkpointing process - void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound, transaction_t read_stamp, + void WriteHeader(Context &context, DatabaseHeader header, VisibilityBound bound, transaction_t read_stamp, transaction_t lowest_active_start) override; void ReuseFreedBlocks(transaction_t lowest_active_start) override; //! Sync changes to the underlying file @@ -156,10 +156,9 @@ class SingleFileBlockManager : public BlockManager { //! Rewrites the main header //! Usage should be avoided //! Except for phasing-out the storage version - void RewriteMainHeader(QueryContext &context, - StorageVersion version_number = MainHeader::DEPRECATED_VERSION_NUMBER); + void RewriteMainHeader(Context &context, StorageVersion version_number = MainHeader::DEPRECATED_VERSION_NUMBER); //! Loads the free list of the file. - void LoadFreeList(QueryContext context); + void LoadFreeList(Context &context); //! Initializes the database header. We pass the provided block allocation size as a parameter //! to detect inconsistencies with the file header. @@ -168,9 +167,8 @@ class SingleFileBlockManager : public BlockManager { void CheckChecksum(FileBuffer &block, uint64_t location, uint64_t delta, bool skip_block_header = false) const; void CheckChecksum(data_ptr_t start_ptr, uint64_t delta, bool skip_block_header = false) const; - void ReadAndChecksum(QueryContext context, FileBuffer &handle, uint64_t location, - bool skip_block_header = false) const; - void ChecksumAndWrite(QueryContext context, FileBuffer &handle, uint64_t location, + void ReadAndChecksum(Context &context, FileBuffer &handle, uint64_t location, bool skip_block_header = false) const; + void ChecksumAndWrite(Context &context, FileBuffer &handle, uint64_t location, bool skip_block_header = false) const; idx_t GetBlockLocation(block_id_t block_id) const; diff --git a/src/duckdb/src/include/duckdb/storage/standard_buffer_manager.hpp b/src/duckdb/src/include/duckdb/storage/standard_buffer_manager.hpp index 22245937d..21ce51a3e 100644 --- a/src/duckdb/src/include/duckdb/storage/standard_buffer_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/standard_buffer_manager.hpp @@ -67,17 +67,15 @@ class StandardBufferManager : public BufferManager { bool can_destroy = true) final; DUCKDB_API BufferHandle Allocate(MemoryTag tag, idx_t block_size, bool can_destroy = true) final; DUCKDB_API BufferHandle Allocate(MemoryTag tag, BlockManager *block_manager, bool can_destroy = true) final; - DUCKDB_API BufferHandle Allocate(QueryContext context, MemoryTag tag, idx_t block_size, - bool can_destroy = true) final; - DUCKDB_API BufferHandle Allocate(QueryContext context, MemoryTag tag, BlockManager *block_manager, + DUCKDB_API BufferHandle Allocate(Context &context, MemoryTag tag, idx_t block_size, bool can_destroy = true) final; + DUCKDB_API BufferHandle Allocate(Context &context, MemoryTag tag, BlockManager *block_manager, bool can_destroy = true) final; BufferHandle Pin(shared_ptr &handle) final; - BufferHandle Pin(const QueryContext &context, shared_ptr &handle) final; + BufferHandle Pin(Context &context, shared_ptr &handle) final; - void Prefetch(QueryContext context, vector> &handles) final; - vector> CreatePrefetchTasks(QueryContext context, - vector> &handles) final; + void Prefetch(Context &context, vector> &handles) final; + vector> CreatePrefetchTasks(Context &context, vector> &handles) final; void Unpin(shared_ptr &handle) final; //! Set a new memory limit to the buffer manager, throws an exception if the new limit is too low and not enough @@ -120,7 +118,7 @@ class StandardBufferManager : public BufferManager { protected: //! Helper template - TempBufferPoolReservation EvictBlocksOrThrow(QueryContext context, MemoryTag tag, idx_t memory_delta, + TempBufferPoolReservation EvictBlocksOrThrow(Context &context, MemoryTag tag, idx_t memory_delta, unique_ptr *buffer, const ARGS &...); //! Register an in-memory buffer of arbitrary size, as long as it is >= BLOCK_SIZE. can_destroy signifies whether or @@ -133,7 +131,8 @@ class StandardBufferManager : public BufferManager { //! This needs to be private to prevent creating blocks without ever pinning them: //! blocks that are never pinned are never added to the eviction queue shared_ptr RegisterMemory(MemoryTag tag, idx_t block_size, idx_t block_header_size, bool can_destroy, - QueryContext context = QueryContext()); + Context &context); + shared_ptr RegisterMemory(MemoryTag tag, idx_t block_size, idx_t block_header_size, bool can_destroy); //! Get allocated size for a block idx_t GetBlockAllocSize(idx_t block_size) const; @@ -145,9 +144,9 @@ class StandardBufferManager : public BufferManager { TemporaryMemoryManager &GetTemporaryMemoryManager() final; //! Write a temporary buffer to disk - void WriteTemporaryBuffer(QueryContext context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer) final; + void WriteTemporaryBuffer(Context &context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer) final; //! Read a temporary buffer from disk - unique_ptr ReadTemporaryBuffer(QueryContext context, MemoryTag tag, BlockHandle &block, + unique_ptr ReadTemporaryBuffer(Context &context, MemoryTag tag, BlockHandle &block, unique_ptr buffer = nullptr) final; //! Get the path of the temporary buffer string GetTemporaryPath(block_id_t id); @@ -172,8 +171,8 @@ class StandardBufferManager : public BufferManager { //! Computes the contiguous runs of blocks that still need to be loaded, without performing any I/O static vector RegisterPrefetch(vector> &handles); //! Synchronously executes every run in the plan through BatchRead - void ExecutePrefetch(QueryContext context, vector &plan); - void BatchRead(QueryContext context, PrefetchRun &run); + void ExecutePrefetch(Context &context, vector &plan); + void BatchRead(Context &context, PrefetchRun &run); bool EncryptTemporaryFiles(); diff --git a/src/duckdb/src/include/duckdb/storage/storage_info.hpp b/src/duckdb/src/include/duckdb/storage/storage_info.hpp index 98cadbac6..e90585b09 100644 --- a/src/duckdb/src/include/duckdb/storage/storage_info.hpp +++ b/src/duckdb/src/include/duckdb/storage/storage_info.hpp @@ -11,13 +11,13 @@ #include "duckdb/common/constants.hpp" #include "duckdb/common/string.hpp" #include "duckdb/common/vector_size.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { struct FileHandle; class MemoryMappedFile; -class QueryContext; +class Context; //! The standard row group size #define DEFAULT_ROW_GROUP_SIZE 122880ULL @@ -279,7 +279,7 @@ class MainHeader { static constexpr uint64_t AES_IV_LEN = 16; static constexpr uint64_t AES_TAG_LEN = 16; - static void CheckMagicBytes(QueryContext context, FileHandle &handle); + static void CheckMagicBytes(Context &context, FileHandle &handle); static void CheckMagicBytes(MemoryMappedFile &handle); string LibraryGitDesc() { diff --git a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp index 6cfcbb4f7..37f62b932 100644 --- a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp @@ -66,7 +66,7 @@ class StorageManager { //! Initialize a database or load an existing database from the database file path. The block_alloc_size is //! either set, or invalid. If invalid, then DuckDB defaults to the default_block_alloc_size (DBConfig), //! or the file's block allocation size, if it is an existing database. - void Initialize(QueryContext context); + void Initialize(Context &context); static bool TargetAtLeastVersion(StorageVersion version, idx_t target_version); static bool TargetAtLeastVersion(StorageVersion version, StorageVersion target_version); @@ -117,7 +117,7 @@ class StorageManager { virtual unique_ptr GenStorageCommitState(WriteAheadLog &wal) = 0; virtual bool IsCheckpointClean(MetaBlockPointer checkpoint_id) = 0; //! The client context is only passed for explicit checkpoints - virtual void CreateCheckpoint(QueryContext context, CheckpointOptions options = CheckpointOptions(), + virtual void CreateCheckpoint(Context &context, CheckpointOptions options = CheckpointOptions(), optional_ptr client_context = nullptr) = 0; virtual DatabaseSize GetDatabaseSize() = 0; virtual vector GetMetadataInfo() = 0; @@ -187,7 +187,7 @@ class StorageManager { } protected: - virtual void LoadDatabase(QueryContext context) = 0; + virtual void LoadDatabase(Context &context) = 0; protected: //! The attached database managed by this storage manager. @@ -246,7 +246,7 @@ class SingleFileStorageManager : public StorageManager { bool AutomaticCheckpoint(idx_t estimated_wal_bytes) override; unique_ptr GenStorageCommitState(WriteAheadLog &wal) override; bool IsCheckpointClean(MetaBlockPointer checkpoint_id) override; - void CreateCheckpoint(QueryContext context, CheckpointOptions options, + void CreateCheckpoint(Context &context, CheckpointOptions options, optional_ptr client_context) override; DatabaseSize GetDatabaseSize() override; vector GetMetadataInfo() override; @@ -255,9 +255,9 @@ class SingleFileStorageManager : public StorageManager { void Destroy() override; protected: - void LoadDatabase(QueryContext context) override; + void LoadDatabase(Context &context) override; - unique_ptr CreateCheckpointWriter(QueryContext context, CheckpointOptions options, + unique_ptr CreateCheckpointWriter(Context &context, CheckpointOptions options, optional_ptr checkpoint_context); private: diff --git a/src/duckdb/src/include/duckdb/storage/string_uncompressed.hpp b/src/duckdb/src/include/duckdb/storage/string_uncompressed.hpp index a4eaf050d..55a9cb68b 100644 --- a/src/duckdb/src/include/duckdb/storage/string_uncompressed.hpp +++ b/src/duckdb/src/include/duckdb/storage/string_uncompressed.hpp @@ -113,7 +113,7 @@ struct UncompressedStringStorage { static unique_ptr StringInitAnalyze(ColumnData &col_data, PhysicalType type); static bool StringAnalyze(AnalyzeState &state_p, const Vector &input); static idx_t StringFinalAnalyze(AnalyzeState &state_p); - static unique_ptr StringInitScan(const QueryContext &context, ColumnSegment &segment); + static unique_ptr StringInitScan(Context &context, ColumnSegment &segment); static void StringScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset); static void StringScan(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result); @@ -270,12 +270,12 @@ struct UncompressedStringStorage { static void WriteString(ColumnSegment &segment, string_t string, block_id_t &result_block, int32_t &result_offset); static void WriteStringMemory(ColumnSegment &segment, string_t string, block_id_t &result_block, int32_t &result_offset); - static string_t ReadOverflowString(const QueryContext &context, ColumnSegment &segment, Vector &result, - block_id_t block, int32_t offset); + static string_t ReadOverflowString(Context &context, ColumnSegment &segment, Vector &result, block_id_t block, + int32_t offset); static string_t ReadStringWithLength(CompressionSegmentReader reader, int32_t offset); static void WriteStringMarker(data_ptr_t target, block_id_t block_id, int32_t offset); - inline static string_t FetchStringFromEntry(const QueryContext &context, ColumnSegment &segment, Vector &result, + inline static string_t FetchStringFromEntry(Context &context, ColumnSegment &segment, Vector &result, const StringDictionaryEntry &entry) { if (DUCKDB_LIKELY(!entry.is_overflow)) { // regular string - fetch from dictionary diff --git a/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp index 785a9d1bc..dcc997025 100644 --- a/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp @@ -63,8 +63,8 @@ class ArrayColumnData : public ColumnData { PersistentColumnData Serialize() override; void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) override; - void GetColumnSegmentInfo(const QueryContext &context, duckdb::idx_t row_group_index, - vector col_path, vector &result, + void GetColumnSegmentInfo(Context &context, duckdb::idx_t row_group_index, vector col_path, + vector &result, const ColumnSegmentInfoScanOptions &options) override; void Verify(RowGroup &parent) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/column_data.hpp index a95444b7a..ed0a8544f 100644 --- a/src/duckdb/src/include/duckdb/storage/table/column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/column_data.hpp @@ -192,8 +192,8 @@ class ColumnData : public enable_shared_from_this { void FetchRowsAtSegmentLevel(TransactionData transaction, ColumnFetchState &state, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, idx_t result_offset); //! Fetches the base data of a batch of row offsets, without updates - void FetchBaseRows(const QueryContext &context, const idx_t *offsets, const SelectionVector &sel, idx_t count, - Vector &result, idx_t result_offset); + void FetchBaseRows(Context &context, const idx_t *offsets, const SelectionVector &sel, idx_t count, Vector &result, + idx_t result_offset); //! Fetches base values of row_ids into result, densely and in the same order, without updates void FetchBaseRows(const row_t *row_ids, idx_t count, Vector &result, idx_t row_group_start); //! Reads the selected rows of a scan through FetchBaseRows (debug_force_fetch_row) @@ -228,7 +228,7 @@ class ColumnData : public enable_shared_from_this { static shared_ptr Deserialize(BlockManager &block_manager, DataTableInfo &info, idx_t column_index, ReadStream &source, const LogicalType &type); - virtual void GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector col_path, + virtual void GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector col_path, vector &result, const ColumnSegmentInfoScanOptions &options); virtual void Verify(RowGroup &parent); diff --git a/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp index fc32e784a..947d20aa8 100644 --- a/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp @@ -66,7 +66,7 @@ class GeoColumnData final : public ColumnData { PersistentColumnData Serialize() override; void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) override; - void GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector col_path, + void GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector col_path, vector &result, const ColumnSegmentInfoScanOptions &options) override; void Verify(RowGroup &parent) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/in_memory_checkpoint.hpp b/src/duckdb/src/include/duckdb/storage/table/in_memory_checkpoint.hpp index 3788fcb73..a7cc6ae0e 100644 --- a/src/duckdb/src/include/duckdb/storage/table/in_memory_checkpoint.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/in_memory_checkpoint.hpp @@ -17,7 +17,7 @@ namespace duckdb { class InMemoryCheckpointer final : public CheckpointWriter { public: - InMemoryCheckpointer(QueryContext context, AttachedDatabase &db, BlockManager &block_manager, + InMemoryCheckpointer(Context &context, AttachedDatabase &db, BlockManager &block_manager, StorageManager &storage_manager, CheckpointOptions options, optional_ptr checkpoint_context = nullptr); diff --git a/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp index 8bb7434f5..a1bc28293 100644 --- a/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp @@ -79,8 +79,8 @@ class ListColumnData : public ColumnData { PersistentColumnData Serialize() override; void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) override; - void GetColumnSegmentInfo(const QueryContext &context, duckdb::idx_t row_group_index, - vector col_path, vector &result, + void GetColumnSegmentInfo(Context &context, duckdb::idx_t row_group_index, vector col_path, + vector &result, const ColumnSegmentInfoScanOptions &options) override; void SetValidityData(shared_ptr validity_p); diff --git a/src/duckdb/src/include/duckdb/storage/table/row_group.hpp b/src/duckdb/src/include/duckdb/storage/table/row_group.hpp index 7b38ebf8d..47cfbb885 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_group.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_group.hpp @@ -276,7 +276,7 @@ class RowGroup : public SegmentBase { unique_ptr GetStatistics(idx_t column_idx) const; unique_ptr GetStatistics(const StorageIndex &column_idx) const; - void GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector &result, + void GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector &result, const ColumnSegmentInfoScanOptions &options = ColumnSegmentInfoScanOptions {}); static PartitionStatistics GetPartitionStats(SegmentNode &row_group, TransactionData transaction); diff --git a/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp b/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp index eb48fba80..f5687ccc2 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp @@ -117,11 +117,11 @@ class RowGroupCollection { void Verify(); void Destroy(); - void InitializeScan(const QueryContext &context, CollectionScanState &state, const vector &column_ids, + void InitializeScan(Context &context, CollectionScanState &state, const vector &column_ids, optional_ptr table_filters); void InitializeCreateIndexScan(CreateIndexScanState &state); - void InitializeScanWithOffset(const QueryContext &context, CollectionScanState &state, - const vector &column_ids, idx_t start_row, idx_t end_row); + void InitializeScanWithOffset(Context &context, CollectionScanState &state, const vector &column_ids, + idx_t start_row, idx_t end_row); static bool InitializeScanInRowGroup(ClientContext &context, CollectionScanState &state, RowGroupCollection &collection, SegmentNode &row_group, idx_t vector_index, idx_t max_row, bool initialize_columns = true); @@ -160,7 +160,7 @@ class RowGroupCollection { bool IsPersistent() const; //! Removes the rows from the indexes added before the bound. - void RemoveFromIndexes(const QueryContext &context, TableIndexList &indexes, Vector &row_identifiers, idx_t count, + void RemoveFromIndexes(Context &context, TableIndexList &indexes, Vector &row_identifiers, idx_t count, IndexRemovalType removal_type, optional_idx active_checkpoint = optional_idx(), VisibilityBound bound = VisibilityBound::IncludingUncommitted()); @@ -200,12 +200,12 @@ class RowGroupCollection { vector GetPartitionStats(TransactionData transaction) const; vector - GetColumnSegmentInfo(const QueryContext &context, + GetColumnSegmentInfo(Context &context, const ColumnSegmentInfoScanOptions &options = ColumnSegmentInfoScanOptions {}) const; //! Initialize an incremental scan over column segment info, pinning the current row groups for consistency. void InitializeColumnSegmentInfoScan(ColumnSegmentInfoScanState &state) const; //! Append the next row group's column segment info to result. Returns false when no row groups remain. - bool ScanColumnSegmentInfo(const QueryContext &context, ColumnSegmentInfoScanState &state, + bool ScanColumnSegmentInfo(Context &context, ColumnSegmentInfoScanState &state, vector &result) const; bool SupportsPerColumnWrites() const; bool SupportsPerColumnWrites(); @@ -217,7 +217,7 @@ class RowGroupCollection { shared_ptr AlterType(ClientContext &context, idx_t changed_idx, const LogicalType &target_type, vector bound_columns, Expression &cast_expr, TransactionData transaction); - void VerifyNewConstraint(const QueryContext &context, DuckTransaction &transaction, DataTable &parent, + void VerifyNewConstraint(Context &context, DuckTransaction &transaction, DataTable &parent, const BoundConstraint &constraint); void CopyStats(TableStatistics &stats); 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 2322fe957..86d63b79e 100644 --- a/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp @@ -97,12 +97,13 @@ struct PushedDownExpressionState { }; struct ColumnScanState { - explicit ColumnScanState(optional_ptr parent_p) : parent(parent_p) { + ColumnScanState(optional_ptr parent_p, Context &context_p) + : parent(parent_p), context(context_p) { } optional_ptr parent; - //! The query context for this scan - QueryContext context; + //! The context for this scan + reference context; //! The column segment that is currently being scanned optional_ptr> current; //! Column segment tree @@ -141,9 +142,9 @@ struct ColumnScanState { void PushDownCast(const LogicalType &original_type, const LogicalType &cast_type); public: - void Initialize(const QueryContext &context_p, const LogicalType &type, const StorageIndex &column_id, + void Initialize(Context &context_p, const LogicalType &type, const StorageIndex &column_id, optional_ptr options); - void Initialize(const QueryContext &context_p, const LogicalType &type, optional_ptr options); + void Initialize(Context &context_p, const LogicalType &type, optional_ptr options); //! Move the scan state forward by "count" rows (including all child states) void Next(idx_t count); //! Move ONLY this state forward by "count" rows (i.e. not the child states) @@ -162,9 +163,12 @@ enum class FetchType { }; struct ColumnFetchState { + explicit ColumnFetchState(Context &context_p) : context(context_p) { + } + FetchType fetch_type = FetchType::TRANSACTIONAL_FETCH; - //! The query context for this fetch - QueryContext context; + //! The context for this fetch + reference context; //! Any child states of the fetch vector> child_states; //! The current row group we are fetching from @@ -272,7 +276,8 @@ class RowGroupScanAssignment { idx_t RowCount() const; private: - QueryContext context; + //! The context the scan runs in; not part of the assignment itself + mutable optional_ptr context; shared_ptr row_groups; optional_ptr> row_group; shared_ptr pinned_row_group; @@ -294,8 +299,8 @@ struct TableScanAssignment { class CollectionScanState { public: explicit CollectionScanState(TableScanState &parent_p); - //! The query context for this scan - QueryContext context; + //! The context for this scan + optional_ptr context; //! The vector index within the row_group idx_t vector_index; //! The maximum row within the row group @@ -331,7 +336,7 @@ class CollectionScanState { unique_ptr local_row_groups_lock; public: - void Initialize(const QueryContext &context_p, const vector &types); + void Initialize(Context &context_p, const vector &types); const vector &GetColumnIds(); ScanFilterInfo &GetFilterInfo(); ScanSamplingInfo &GetSamplingInfo(); diff --git a/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp index 48115a12b..c32c44a01 100644 --- a/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp @@ -60,8 +60,8 @@ class StandardColumnData : public ColumnData { void CheckpointScan(ColumnSegment &segment, ColumnScanState &state, idx_t count, Vector &scan_vector) const override; - void GetColumnSegmentInfo(const QueryContext &context, duckdb::idx_t row_group_index, - vector col_path, vector &result, + void GetColumnSegmentInfo(Context &context, duckdb::idx_t row_group_index, vector col_path, + vector &result, const ColumnSegmentInfoScanOptions &options) override; bool IsPersistent() override; diff --git a/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp index f3c7902b5..610d70bb3 100644 --- a/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp @@ -80,8 +80,8 @@ class StructColumnData : public ColumnData { PersistentColumnData Serialize() override; void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) override; - void GetColumnSegmentInfo(const QueryContext &context, duckdb::idx_t row_group_index, - vector col_path, vector &result, + void GetColumnSegmentInfo(Context &context, duckdb::idx_t row_group_index, vector col_path, + vector &result, const ColumnSegmentInfoScanOptions &options) override; void Verify(RowGroup &parent) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp index 29fadb778..a0d8b1da8 100644 --- a/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp @@ -71,8 +71,8 @@ class VariantColumnData : public ColumnData { PersistentColumnData Serialize() override; void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) override; - void GetColumnSegmentInfo(const QueryContext &context, duckdb::idx_t row_group_index, - vector col_path, vector &result, + void GetColumnSegmentInfo(Context &context, duckdb::idx_t row_group_index, vector col_path, + vector &result, const ColumnSegmentInfoScanOptions &options) override; void Verify(RowGroup &parent) override; diff --git a/src/duckdb/src/include/duckdb/storage/temporary_file_manager.hpp b/src/duckdb/src/include/duckdb/storage/temporary_file_manager.hpp index 8deb68bd3..46e268843 100644 --- a/src/duckdb/src/include/duckdb/storage/temporary_file_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/temporary_file_manager.hpp @@ -170,9 +170,9 @@ class TemporaryFileHandle { void EraseBlockIndex(block_id_t block_index); //! Read/Write temporary buffers at given positions in this file (potentially compressed) - unique_ptr ReadTemporaryBuffer(QueryContext context, const TemporaryFileIndex &index_in_file, + unique_ptr ReadTemporaryBuffer(Context &context, const TemporaryFileIndex &index_in_file, unique_ptr buffer); - void WriteTemporaryBuffer(QueryContext context, FileBuffer &buffer, idx_t block_index, + void WriteTemporaryBuffer(Context &context, FileBuffer &buffer, idx_t block_index, AllocatedData &compressed_buffer); //! Deletes the file if there are no more blocks @@ -314,10 +314,10 @@ class TemporaryFileManager { }; //! Create/Read/Update/Delete operations for temporary buffers - idx_t WriteTemporaryBuffer(QueryContext context, block_id_t block_id, FileBuffer &buffer); + idx_t WriteTemporaryBuffer(Context &context, block_id_t block_id, FileBuffer &buffer); bool HasTemporaryBuffer(block_id_t block_id); - unique_ptr ReadTemporaryBuffer(QueryContext context, block_id_t id, - unique_ptr reusable_buffer, idx_t *eviction_size = nullptr); + unique_ptr ReadTemporaryBuffer(Context &context, block_id_t id, unique_ptr reusable_buffer, + idx_t *eviction_size = nullptr); idx_t DeleteTemporaryBuffer(block_id_t id); bool IsEncrypted() const; diff --git a/src/duckdb/src/include/duckdb/storage/write_ahead_log.hpp b/src/duckdb/src/include/duckdb/storage/write_ahead_log.hpp index 4f50a4939..afdbb4d77 100644 --- a/src/duckdb/src/include/duckdb/storage/write_ahead_log.hpp +++ b/src/duckdb/src/include/duckdb/storage/write_ahead_log.hpp @@ -52,9 +52,8 @@ class WriteAheadLog { virtual ~WriteAheadLog(); public: - //! Replay and initialize the WAL, QueryContext is passed for metric collection purposes only!! - static unique_ptr Replay(QueryContext context, StorageManager &storage_manager, - const string &wal_path); + //! Replay and initialize the WAL, Context &is passed for metric collection purposes only!! + static unique_ptr Replay(Context &context, StorageManager &storage_manager, const string &wal_path); AttachedDatabase &GetDatabase(); StorageManager &GetStorageManager(); diff --git a/src/duckdb/src/include/duckdb/transaction/commit_state.hpp b/src/duckdb/src/include/duckdb/transaction/commit_state.hpp index 3f1ff1d5c..ad169326c 100644 --- a/src/duckdb/src/include/duckdb/transaction/commit_state.hpp +++ b/src/duckdb/src/include/duckdb/transaction/commit_state.hpp @@ -73,7 +73,7 @@ class CommitDropState { struct IndexDataRemover { public: - explicit IndexDataRemover(DuckTransaction &transaction, QueryContext context, IndexRemovalType removal_type); + explicit IndexDataRemover(DuckTransaction &transaction, Context &context, IndexRemovalType removal_type); //! Removes the deleted rows from the indexes; returns true if they stay in deleted_rows_in_use bool PushDelete(DeleteInfo &info); @@ -85,7 +85,7 @@ struct IndexDataRemover { private: DuckTransaction &transaction; // data for index cleanup - QueryContext context; + Context &context; //! While committing, we remove data from any indexes that was deleted IndexRemovalType removal_type; DataChunk chunk; diff --git a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp index 234b5fc7a..84483989a 100644 --- a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp +++ b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp @@ -13,7 +13,7 @@ #include "duckdb/storage/storage_lock.hpp" #include "duckdb/common/atomic.hpp" #include "duckdb/common/error_data.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/common/reference_map.hpp" namespace duckdb { @@ -102,7 +102,7 @@ class LocalTableStorage : public enable_shared_from_this { unique_ptr LockShared(); unique_ptr LockAppend(); //! Initialize a scan; the context of the scanning query is used for pushed down casts and zonemap checks - void InitializeScan(const QueryContext &context, CollectionScanState &state, + void InitializeScan(Context &context, CollectionScanState &state, optional_ptr table_filters = nullptr); //! Write a new row group to disk (if possible) void WriteNewRowGroup(Context &context, idx_t flushed_row_group_idx); @@ -193,7 +193,7 @@ class LocalStorage { static LocalStorage &Get(ClientContext &context, Catalog &catalog); //! Initialize a scan of the local storage - void InitializeScan(const QueryContext &context, DataTable &table, CollectionScanState &state, + void InitializeScan(Context &context, DataTable &table, CollectionScanState &state, optional_ptr table_filters); //! Scan void Scan(CollectionScanState &state, const vector &column_ids, DataChunk &result); diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 1c3af0dd7..fe18c7fd1 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -1548,25 +1548,64 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_connection_create_secret) (duckdb_v2_connection_handle conn, duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, duckdb_v2_secret_handle *created, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_get_or_create_state) + (duckdb_v2_connection_handle conn, const char *key, idx_t key_length, duckdb_v2_context_state_init_callback_fn init, + void *init_user_data, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_get_secret_by_name) (duckdb_v2_connection_handle conn, const char *name, idx_t name_length, duckdb_v2_secret_handle *secret, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_get_state) + (duckdb_v2_connection_handle conn, const char *key, idx_t key_length, bool *found, void **data, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_lookup_secret) (duckdb_v2_connection_handle conn, const char *path, idx_t path_length, const char *type, idx_t type_length, duckdb_v2_secret_handle *secret, int64_t *score, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_register_secret_function) (duckdb_v2_connection_handle conn, duckdb_v2_secret_function_handle function, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_remove_state) + (duckdb_v2_connection_handle conn, const char *key, idx_t key_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_context_create_secret) (duckdb_v2_context_handle ctx, duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, duckdb_v2_secret_handle *created, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_context_get_object_cache) (duckdb_v2_context_handle context, duckdb_v2_object_cache_handle *cache, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_get_or_create_state) + (duckdb_v2_context_handle context, const char *key, idx_t key_length, duckdb_v2_context_state_init_callback_fn init, + void *init_user_data, void **data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_context_get_secret_by_name) (duckdb_v2_context_handle ctx, const char *name, idx_t name_length, duckdb_v2_secret_handle *secret, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_get_state) + (duckdb_v2_context_handle context, const char *key, idx_t key_length, bool *found, void **data, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_context_lookup_secret) (duckdb_v2_context_handle ctx, const char *path, idx_t path_length, const char *type, idx_t type_length, duckdb_v2_secret_handle *secret, int64_t *score, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_remove_state) + (duckdb_v2_context_handle context, const char *key, idx_t key_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_state_profile_write) + (duckdb_v2_context_state_profile_handle profile, const char *text, idx_t text_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_state_set_profiling_callback) + (duckdb_v2_context_state_handle state, duckdb_v2_context_state_profiling_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_state_set_query_begin_callback) + (duckdb_v2_context_state_handle state, duckdb_v2_context_state_query_begin_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_state_set_query_end_callback) + (duckdb_v2_context_state_handle state, duckdb_v2_context_state_query_end_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_state_set_transaction_begin_callback) + (duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_begin_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_state_set_transaction_commit_callback) + (duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_end_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_state_set_transaction_rollback_callback) + (duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_end_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_state_set_user_data) + (duckdb_v2_context_state_handle state, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_crypto_cipher_create) (duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_CIPHER cipher, DUCKDB_V2_CRYPTO_MODE mode, const uint8_t *key, idx_t key_length, duckdb_v2_crypto_cipher_handle *stream, duckdb_v2_error_info_handle *err); @@ -1818,11 +1857,17 @@ typedef struct { 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_V2_ERROR(*duckdb_v2_connection_create_in_transaction) + (duckdb_v2_context_handle ctx, duckdb_v2_connection_handle *out_conn, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_copy_from_set_data_source) (duckdb_v2_copy_function_handle function, duckdb_v2_data_source_handle data_source, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_connection_create_in_transaction) - (duckdb_v2_context_handle ctx, duckdb_v2_connection_handle *out_conn, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_add_task) + (duckdb_v2_data_source_exec_info_handle info, duckdb_v2_data_source_task_callback_fn task, duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_set_result) + (duckdb_v2_data_source_exec_info_handle info, DUCKDB_V2_DATA_SOURCE_RESULT result, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_property) (duckdb_v2_table_function_handle function, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, duckdb_v2_error_info_handle *err); @@ -3804,27 +3849,72 @@ typedef struct { #define duckdb_v2_connection_create_secret duckdb_ext_api.duckdb_v2_connection_create_secret #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_connection_get_or_create_state duckdb_ext_api.duckdb_v2_connection_get_or_create_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_connection_get_secret_by_name duckdb_ext_api.duckdb_v2_connection_get_secret_by_name #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_connection_get_state duckdb_ext_api.duckdb_v2_connection_get_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_connection_lookup_secret duckdb_ext_api.duckdb_v2_connection_lookup_secret #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_connection_register_secret_function duckdb_ext_api.duckdb_v2_connection_register_secret_function #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_connection_remove_state duckdb_ext_api.duckdb_v2_connection_remove_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_context_create_secret duckdb_ext_api.duckdb_v2_context_create_secret #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_context_get_object_cache duckdb_ext_api.duckdb_v2_context_get_object_cache #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_get_or_create_state duckdb_ext_api.duckdb_v2_context_get_or_create_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_context_get_secret_by_name duckdb_ext_api.duckdb_v2_context_get_secret_by_name #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_get_state duckdb_ext_api.duckdb_v2_context_get_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_context_lookup_secret duckdb_ext_api.duckdb_v2_context_lookup_secret #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_remove_state duckdb_ext_api.duckdb_v2_context_remove_state +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_state_profile_write duckdb_ext_api.duckdb_v2_context_state_profile_write +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_state_set_profiling_callback duckdb_ext_api.duckdb_v2_context_state_set_profiling_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_state_set_query_begin_callback duckdb_ext_api.duckdb_v2_context_state_set_query_begin_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_state_set_query_end_callback duckdb_ext_api.duckdb_v2_context_state_set_query_end_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_state_set_transaction_begin_callback \ + duckdb_ext_api.duckdb_v2_context_state_set_transaction_begin_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_state_set_transaction_commit_callback \ + duckdb_ext_api.duckdb_v2_context_state_set_transaction_commit_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_state_set_transaction_rollback_callback \ + duckdb_ext_api.duckdb_v2_context_state_set_transaction_rollback_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_state_set_user_data duckdb_ext_api.duckdb_v2_context_state_set_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_crypto_cipher_create duckdb_ext_api.duckdb_v2_crypto_cipher_create #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -4146,10 +4236,18 @@ typedef struct { #define duckdb_v2_value_variant_to_value duckdb_ext_api.duckdb_v2_value_variant_to_value #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_copy_from_set_data_source duckdb_ext_api.duckdb_v2_copy_from_set_data_source #define duckdb_v2_connection_create_in_transaction duckdb_ext_api.duckdb_v2_connection_create_in_transaction #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_copy_from_set_data_source duckdb_ext_api.duckdb_v2_copy_from_set_data_source +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_exec_add_task duckdb_ext_api.duckdb_v2_data_source_exec_add_task +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_data_source_exec_set_result duckdb_ext_api.duckdb_v2_data_source_exec_set_result +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_set_property duckdb_ext_api.duckdb_v2_table_function_set_property #endif // capigen:end appended diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index 256899246..d5d9fc830 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -2066,6 +2066,402 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_progress_get(duckdb_v2_connect /* --- Struct definitions for connection --- */ +/* ============================================================================ + * MODULE: context state + * ============================================================================ */ + +/* --- Enums for context state --- */ + +/* --- Struct forward declarations for context state --- */ + +/* --- Types for context state --- */ + +/*! + * A borrowed opaque handle to connection state being set up, received by the init callback of + * `duckdb_v2_context_get_or_create_state()` or `duckdb_v2_connection_get_or_create_state()` and valid only for the + * duration of that call. Configure it with `duckdb_v2_context_state_set_user_data()` and the callback setters; whatever + * is not set stays inert. + */ +typedef struct _duckdb_v2_context_state { + void *internal_ptr; +} * duckdb_v2_context_state_handle; + +/*! + * A borrowed opaque handle to the profile of the query that just ended, received by a connection state's profiling + * callback and valid only for the duration of that call. Add text to it with `duckdb_v2_context_state_profile_write()`. + */ +typedef struct _duckdb_v2_context_state_profile { + void *internal_ptr; +} * duckdb_v2_context_state_profile_handle; + +/* --- Constants for context state --- */ + +/* --- Function pointer typedefs for context state --- */ + +/*! + * Sets up the connection state of a key that has none yet. + * + * Runs outside the lock of the connection's registered states, so it may use the context, state functions included. + * When the key gets registered while the init runs, by another thread or by the init itself, the state registered first + * is kept, and the one this init set up is released as if the init had failed. A failure reported through `err` leaves + * the key unregistered and fails the call that triggered the init. + */ +typedef void (*duckdb_v2_context_state_init_callback_fn)(duckdb_v2_context_handle context, void *user_data, + duckdb_v2_context_state_handle state, + duckdb_v2_error_info_handle *err); + +/*! + * Called when a query starts on the connection, before any of it runs. Called at most once per query, also for the + * queries DuckDB runs on behalf of another. No transaction is guaranteed to be active. + * + * An error reported through `err` fails the query. The query still ends: the query end callbacks of all states, the + * rejecting one included, receive the error, and a transaction the query started is rolled back. Inside an explicit + * transaction the failure aborts the transaction, as any failed query does. + */ +typedef void (*duckdb_v2_context_state_query_begin_callback_fn)(duckdb_v2_context_handle context, void *user_data, + duckdb_v2_error_info_handle *err); + +/*! + * Called when a query ends on the connection, whether it succeeded, failed or was cancelled. The place to drop what was + * only meant to last for one query. No transaction is guaranteed to be active. + * + * The callback cannot fail: there is nothing left to fail. + */ +typedef void (*duckdb_v2_context_state_query_end_callback_fn)(duckdb_v2_context_handle context, void *user_data, + const char *error, idx_t error_length); + +/*! + * Called when a transaction starts on the connection, explicitly or automatically. The transaction is active. + * + * An error reported through `err` fails the statement starting the transaction and rolls the transaction back: the + * transaction rollback callbacks of all states run. A query whose transaction is rejected this way does not begin, and + * its query begin and end callbacks do not run. + */ +typedef void (*duckdb_v2_context_state_transaction_begin_callback_fn)(duckdb_v2_context_handle context, void *user_data, + duckdb_v2_error_info_handle *err); + +/*! + * Called when a transaction ends on the connection: after it committed, or after it was rolled back, either explicitly + * or because its statement failed. A transaction whose commit fails is reported as rolled back. No transaction is + * active any longer. + * + * The callback cannot fail: the transaction has already ended, and its fate does not depend on the callback. + */ +typedef void (*duckdb_v2_context_state_transaction_end_callback_fn)(duckdb_v2_context_handle context, void *user_data); + +/*! + * Called when the text rendering of the profile of a query is written, as `EXPLAIN ANALYZE` does, to let the state add + * to it. What the state writes comes out next to what other connection states wrote. + */ +typedef void (*duckdb_v2_context_state_profiling_callback_fn)(duckdb_v2_context_state_profile_handle profile, + void *user_data, duckdb_v2_error_info_handle *err); + +/* --- Functions for context state --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Gets the state registered under a key on the connection of a context, creating it first if there is none. + * + * The init callback sets up a new state. When several threads race to get the same key, each may run its init, but only + * one state is registered, and all of them receive it. The state lives until `duckdb_v2_context_remove_state()` or + * until the connection is destroyed, and then releases its user data through the destructor bundled with it. The data + * pointer received is the state's user data, valid for as long as the state is. + * + * Keys are case-sensitive and shared by everything that registers state on the connection, DuckDB's extensions + * included: prefix them with the name of the extension. A key held by something that is not state of this API fails the + * call. + * + * history: + * - unstable: v2.0.0 + * + * @param context The context whose connection to take the state from. + * @param key The key of the state. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param init Sets up the state if the key has none yet. + * @param init_user_data Handed to the init callback. Borrowed for the duration of the call. + * @param data Receives the user data of the state, or null if it set none. Optional. + * @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_context_get_or_create_state(duckdb_v2_context_handle context, const char *key, + idx_t key_length, + duckdb_v2_context_state_init_callback_fn init, + void *init_user_data, void **data, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Gets the state registered under a key on a connection, creating it first if there is none. The same as + * `duckdb_v2_context_get_or_create_state()`, for a connection that is not seen from inside DuckDB. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection to take the state from. + * @param key The key of the state. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param init Sets up the state if the key has none yet. + * @param init_user_data Handed to the init callback. Borrowed for the duration of the call. + * @param data Receives the user data of the state, or null if it set none. Optional. + * @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_or_create_state(duckdb_v2_connection_handle conn, const char *key, + idx_t key_length, + duckdb_v2_context_state_init_callback_fn init, + void *init_user_data, void **data, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Looks up the state registered under a key on the connection of a context, without creating it. + * + * `found` receives false if there is no state under the key, and `data` is then left untouched. The data pointer is + * valid until the state is removed or the connection is destroyed. + * + * history: + * - unstable: v2.0.0 + * + * @param context The context whose connection to look the state up on. + * @param key The key of the state. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param found Receives whether the key has state. + * @param data Receives the user data of the state, or null if it set none. Optional. + * @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_context_get_state(duckdb_v2_context_handle context, const char *key, + idx_t key_length, bool *found, void **data, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Looks up the state registered under a key on a connection. The same as `duckdb_v2_context_get_state()`. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection to look the state up on. + * @param key The key of the state. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param found Receives whether the key has state. + * @param data Receives the user data of the state, or null if it set none. Optional. + * @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_state(duckdb_v2_connection_handle conn, const char *key, + idx_t key_length, bool *found, void **data, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Removes the state registered under a key on the connection of a context, destroying its user data. Removing a key + * that has no state is not an error. + * + * The callbacks of the state do not run for any later step of the query or transaction that is under way, and the data + * pointer handed out earlier must not be used any longer. A step already in progress, such as a query begin whose + * callback of another state removes this one, may still run the callback of this state; the user data is then released + * when that step is over. The destructor of the user data runs outside the lock of the connection's registered states, + * so it may use the connection. + * + * history: + * - unstable: v2.0.0 + * + * @param context The context whose connection to remove the state from. + * @param key The key of the state. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @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_context_remove_state(duckdb_v2_context_handle context, const char *key, + idx_t key_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Removes the state registered under a key on a connection. The same as `duckdb_v2_context_remove_state()`. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection to remove the state from. + * @param key The key of the state. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @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_remove_state(duckdb_v2_connection_handle conn, const char *key, + idx_t key_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the user data of the state, handed to all of its callbacks. + * + * The opaque handle bundles the pointer with an optional destructor, invoked when the state is removed or its + * connection is destroyed. If the state could not be created after all, because its init callback reported an error or + * the key got registered meanwhile, the destructor is invoked right away. + * + * history: + * - unstable: v2.0.0 + * + * @param state The state to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @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_context_state_set_user_data(duckdb_v2_context_state_handle state, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback called when a query starts on the connection. + * + * history: + * - unstable: v2.0.0 + * + * @param state The state to set the callback of. + * @param callback The callback. + * @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_context_state_set_query_begin_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_query_begin_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback called when a query ends on the connection. + * + * history: + * - unstable: v2.0.0 + * + * @param state The state to set the callback of. + * @param callback The callback. + * @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_context_state_set_query_end_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_query_end_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback called when a transaction starts on the connection. + * + * history: + * - unstable: v2.0.0 + * + * @param state The state to set the callback of. + * @param callback The callback. + * @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_context_state_set_transaction_begin_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_begin_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback called when a transaction on the connection committed. + * + * history: + * - unstable: v2.0.0 + * + * @param state The state to set the callback of. + * @param callback The callback. + * @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_context_state_set_transaction_commit_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_end_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback called when a transaction on the connection was rolled back. + * + * history: + * - unstable: v2.0.0 + * + * @param state The state to set the callback of. + * @param callback The callback. + * @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_context_state_set_transaction_rollback_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_end_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback called when the profile of a query is written, to let the state add to it. + * + * history: + * - unstable: v2.0.0 + * + * @param state The state to set the callback of. + * @param callback The callback. + * @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_context_state_set_profiling_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_profiling_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Adds text to the profile being written. The text is borrowed and copied. + * + * history: + * - unstable: v2.0.0 + * + * @param profile The profile to add to. + * @param text The text to add. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. + * @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_context_state_profile_write(duckdb_v2_context_state_profile_handle profile, + const char *text, idx_t text_length, + duckdb_v2_error_info_handle *err); +#endif + +/* --- Struct definitions for context state --- */ + /* ============================================================================ * MODULE: crypto * ============================================================================ */ @@ -17659,6 +18055,35 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_result_to_arrow_c_stream(duckdb_v2_ /* --- Enums for data_source --- */ +/*! + * What an invocation of the exec callback leaves the scan in, set with `duckdb_v2_data_source_exec_set_result()`. It + * mirrors the result of a table function in the engine (`AsyncResultType`): by default the size of the batch decides, + * and a callback can instead declare explicitly that the scan goes on, that it is finished, or that it is blocked on + * tasks to run first. + */ +typedef enum DUCKDB_V2_DATA_SOURCE_RESULT { + //! The default. A batch with rows means the scan goes on, an empty batch that it is finished. + DUCKDB_V2_DATA_SOURCE_RESULT_IMPLICIT = 0, + + //! The scan goes on. The batch must have rows. + DUCKDB_V2_DATA_SOURCE_RESULT_HAVE_MORE_OUTPUT = 1, + + /*! + * The scan is finished on this thread, and the callback is not invoked again on it. The batch must be empty. For a + * data source that claims its batches (see `duckdb_v2_data_source_set_claim_batch_callback()`) this also ends the + * claiming, where an empty batch only ends the claimed batch, except when a multi-file scan claims the batches: + * there it ends the batch like an empty batch does. + */ + DUCKDB_V2_DATA_SOURCE_RESULT_FINISHED = 2, + + /*! + * The scan cannot go on until the tasks added with `duckdb_v2_data_source_exec_add_task()` have run, after which + * the callback is invoked again. The batch must be empty, and at least one task must have been added. + */ + DUCKDB_V2_DATA_SOURCE_RESULT_BLOCKED = 3, + DUCKDB_V2_DATA_SOURCE_RESULT_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_DATA_SOURCE_RESULT; + /* --- Struct forward declarations for data_source --- */ /* --- Types for data_source --- */ @@ -17748,6 +18173,8 @@ typedef struct _duckdb_v2_data_source_metrics_info { /* --- Function pointer typedefs for data_source --- */ +typedef void (*duckdb_v2_data_source_task_callback_fn)(void *data, duckdb_v2_error_info_handle *err); + typedef void (*duckdb_v2_data_source_init_global_callback_fn)(duckdb_v2_data_source_init_global_info_handle info, duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); @@ -18349,7 +18776,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_local_state(duckdb_v * order; reach them with `duckdb_v2_data_chunk_get_vector()`. The chunk starts out empty on every invocation: write the * rows, then declare how many there are with `duckdb_v2_vector_set_size()` on the first vector, which the engine takes * as the batch's row count and propagates to the other vectors. Producing an empty batch signals the end of the scan, - * after which the callback is not invoked again on that thread. Borrowed; valid only for the duration of the callback. + * after which the callback is not invoked again on that thread, unless the invocation declares otherwise with + * `duckdb_v2_data_source_exec_set_result()` or `duckdb_v2_data_source_exec_add_task()`. Borrowed; valid only for the + * duration of the callback. * * history: * - unstable: v2.0.0 @@ -18411,6 +18840,58 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_column_index(duckdb_ duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Declares what this invocation of the exec callback leaves the scan in, see `DUCKDB_V2_DATA_SOURCE_RESULT`. + * + * Without it, the size of the batch decides: an empty batch finishes the scan on this thread. Checked when the callback + * returns: `DATA_SOURCE_RESULT_HAVE_MORE_OUTPUT` with an empty batch, `DATA_SOURCE_RESULT_FINISHED` or + * `DATA_SOURCE_RESULT_BLOCKED` with rows, `DATA_SOURCE_RESULT_BLOCKED` without a task, or a task added while the result + * is not `DATA_SOURCE_RESULT_BLOCKED` fail the query. + * + * history: + * - unstable: v2.0.0 + * + * @param info The exec info handle. + * @param result What the invocation leaves the scan in. + * @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_data_source_exec_set_result(duckdb_v2_data_source_exec_info_handle info, + DUCKDB_V2_DATA_SOURCE_RESULT result, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Adds a task to run before the scan goes on, and sets the result of this invocation to `DATA_SOURCE_RESULT_BLOCKED`. + * + * Once the callback returns, the scan is blocked until every task it added has run, after which the exec callback is + * invoked again, possibly on another thread. The engine runs the tasks on its scheduler, where they do not hold up the + * thread the scan ran on, or runs them on the calling thread, one after the other, when the scan runs synchronously. A + * task can do work the next invocation needs, like reading ahead, or nothing at all: a task that does nothing hands the + * thread back to the engine, which keeps the progress of a callback that works long without producing rows observable. + * A task runs once, without access to the exec info, and must not touch the state of the scan that other threads write + * unsynchronized. A task that fails fails the query. + * + * history: + * - unstable: v2.0.0 + * + * @param info The exec info handle. + * @param task The task to run. + * @param data Opaque handle bundling the data the task is called with plus an optional destructor, invoked once the + * task has run or when it is discarded. The pointer may be null. Taken over by the call, also when it fails. + * @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_data_source_exec_add_task(duckdb_v2_data_source_exec_info_handle info, + duckdb_v2_data_source_task_callback_fn task, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Retrieves the user data set via `duckdb_v2_data_source_set_user_data()`, or the user data of the table function or diff --git a/src/duckdb/src/logging/log_sink.cpp b/src/duckdb/src/logging/log_sink.cpp index 39b1d0687..b6c343baf 100644 --- a/src/duckdb/src/logging/log_sink.cpp +++ b/src/duckdb/src/logging/log_sink.cpp @@ -5,7 +5,7 @@ #include "duckdb/common/local_file_system.hpp" #include "duckdb/function/table/read_csv.hpp" #include "duckdb/common/serializer/memory_stream.hpp" -#include "duckdb/main/database_file_opener.hpp" +#include "duckdb/main/database_file_system.hpp" #include "duckdb/logging/logging.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/client_context.hpp" @@ -343,7 +343,7 @@ unique_ptr FileLogSink::InitializeFileWriter(DatabaseInstanc flags = FileFlags::FILE_FLAGS_DISABLE_LOGGING | FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_APPEND; } - return make_uniq(fs, path, flags); + return make_uniq(fs, db.GetContext(), path, flags); } void FileLogSink::Truncate() { diff --git a/src/duckdb/src/logging/log_types.cpp b/src/duckdb/src/logging/log_types.cpp index c8d4d8961..8cc0e0984 100644 --- a/src/duckdb/src/logging/log_types.cpp +++ b/src/duckdb/src/logging/log_types.cpp @@ -1,7 +1,6 @@ #include "duckdb/logging/log_type.hpp" #include "duckdb/common/exception.hpp" -#include "duckdb/common/file_opener.hpp" #include "duckdb/main/http/http_util.hpp" #include "duckdb/main/profiler/profiling_utils.hpp" #include "duckdb/execution/physical_operator.hpp" diff --git a/src/duckdb/src/logging/logger.cpp b/src/duckdb/src/logging/logger.cpp index 19959159a..53c713544 100644 --- a/src/duckdb/src/logging/logger.cpp +++ b/src/duckdb/src/logging/logger.cpp @@ -5,7 +5,6 @@ #include "duckdb/main/client_context.hpp" #include "duckdb/main/connection.hpp" #include "duckdb/main/database.hpp" -#include "duckdb/common/file_opener.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/parallel/thread_context.hpp" @@ -43,10 +42,6 @@ Logger &Logger::Get(const Context &context) { return context.GetLogger(); } -Logger &Logger::Get(const FileOpener &opener) { - return opener.GetLogger(); -} - Logger &Logger::Get(const shared_ptr &logger) { return *logger; } diff --git a/src/duckdb/src/main/attached_database.cpp b/src/duckdb/src/main/attached_database.cpp index d35f78fe7..e1b18de2a 100644 --- a/src/duckdb/src/main/attached_database.cpp +++ b/src/duckdb/src/main/attached_database.cpp @@ -1,4 +1,5 @@ #include "duckdb/main/attached_database.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/logging/log_manager.hpp" #include "duckdb/catalog/duck_catalog.hpp" @@ -119,6 +120,10 @@ ValidChecker &ValidChecker::Get(AttachedDatabase &db) { return db.GetValidChecker(); } +Context &AttachedDatabase::GetContext() { + return db.GetContext(); +} + AttachedDatabase::AttachedDatabase(DatabaseInstance &db, AttachedDatabaseType type) : CatalogEntry(CatalogType::DATABASE_ENTRY, Identifier(type == AttachedDatabaseType::SYSTEM_DATABASE ? SYSTEM_CATALOG : TEMP_CATALOG), 0), @@ -348,7 +353,7 @@ void AttachedDatabase::Initialize(optional_ptr context) { catalog->Initialize(context, false); } if (storage) { - storage->Initialize(context); + storage->Initialize(Context::GetOrDatabase(context, db)); } } @@ -487,7 +492,7 @@ void AttachedDatabase::Close(const DatabaseCloseAction action) { if (should_checkpoint) { CheckpointOptions options; options.wal_action = CheckpointWALAction::DELETE_WAL; - storage->CreateCheckpoint(QueryContext(), options); + storage->CreateCheckpoint(GetDatabase().GetContext(), options); } } } catch (std::exception &ex) { diff --git a/src/duckdb/src/main/capi/v2/capi_v2_context_state.cpp b/src/duckdb/src/main/capi/v2/capi_v2_context_state.cpp new file mode 100644 index 000000000..f72f63c3c --- /dev/null +++ b/src/duckdb/src/main/capi/v2/capi_v2_context_state.cpp @@ -0,0 +1,318 @@ +#include "duckdb/main/capi_v2/capi_v2_internal.hpp" + +#include "duckdb/main/client_context_state.hpp" +#include "duckdb/main/database.hpp" + +namespace duckdb::capiv2 { + +//---------------------------------------------------------------------------------------------------------------------- +// Connection state +//---------------------------------------------------------------------------------------------------------------------- + +//! What an init callback configures. Its user data is released when the builder is, i.e. right away if the init fails. +class CV2ContextStateBuilder { +public: + shared_ptr user_data; + duckdb_v2_context_state_query_begin_callback_fn query_begin_cb = nullptr; + duckdb_v2_context_state_query_end_callback_fn query_end_cb = nullptr; + duckdb_v2_context_state_transaction_begin_callback_fn transaction_begin_cb = nullptr; + duckdb_v2_context_state_transaction_end_callback_fn transaction_commit_cb = nullptr; + duckdb_v2_context_state_transaction_end_callback_fn transaction_rollback_cb = nullptr; + duckdb_v2_context_state_profiling_callback_fn profiling_cb = nullptr; +}; + +static auto Convert(duckdb_v2_context_state_handle state) -> CV2ContextStateBuilder * { + return reinterpret_cast(state); +} +static auto Convert(CV2ContextStateBuilder *state) -> duckdb_v2_context_state_handle { + return reinterpret_cast(state); +} + +//! The profile being written: the stream the registered states append to. +class CV2ContextStateProfile { +public: + explicit CV2ContextStateProfile(std::ostream &ss) : ss(ss) { + } + + std::ostream &ss; +}; + +static auto Convert(duckdb_v2_context_state_profile_handle profile) -> CV2ContextStateProfile * { + return reinterpret_cast(profile); +} +static auto Convert(CV2ContextStateProfile *profile) -> duckdb_v2_context_state_profile_handle { + return reinterpret_cast(profile); +} + +//! Tag identifying CV2ContextState without RTTI. +static const char CV2_CONTEXT_STATE_TAG = 0; + +//! Connection state set up through the C API: forwards ClientContextState's hooks to the callbacks the init set. +class CV2ContextState final : public ClientContextState { +public: + CV2ContextState(CV2Context &context, duckdb_v2_context_state_init_callback_fn init, void *init_user_data) { + CV2ContextStateBuilder builder; + InvokeWithErrorSlot( + [&](duckdb_v2_error_info_handle *err) { init(Convert(&context), init_user_data, Convert(&builder), err); }); + callbacks = std::move(builder); + } + + void *GetUserData() const { + return callbacks.user_data ? callbacks.user_data->GetData() : nullptr; + } + + using ClientContextState::QueryEnd; + using ClientContextState::TransactionRollback; + + void QueryBegin(ClientContext &context) override { + if (!callbacks.query_begin_cb) { + return; + } + CV2CallbackContext handle(context); + InvokeWithErrorSlot( + [&](duckdb_v2_error_info_handle *err) { callbacks.query_begin_cb(Convert(&handle), GetUserData(), err); }); + } + + void QueryEnd(ClientContext &context, optional_ptr error) override { + if (!callbacks.query_end_cb) { + return; + } + CV2CallbackContext handle(context); + if (error && error->HasError()) { + auto message = error->Message(); + callbacks.query_end_cb(Convert(&handle), GetUserData(), message.data(), message.size()); + } else { + callbacks.query_end_cb(Convert(&handle), GetUserData(), nullptr, 0); + } + } + + void TransactionBegin(MetaTransaction &transaction, ClientContext &context) override { + if (!callbacks.transaction_begin_cb) { + return; + } + CV2CallbackContext handle(context); + InvokeWithErrorSlot([&](duckdb_v2_error_info_handle *err) { + callbacks.transaction_begin_cb(Convert(&handle), GetUserData(), err); + }); + } + + void TransactionCommit(MetaTransaction &transaction, ClientContext &context) override { + if (callbacks.transaction_commit_cb) { + CV2CallbackContext handle(context); + callbacks.transaction_commit_cb(Convert(&handle), GetUserData()); + } + } + + void TransactionRollback(MetaTransaction &transaction, ClientContext &context, + optional_ptr error) override { + if (callbacks.transaction_rollback_cb) { + CV2CallbackContext handle(context); + callbacks.transaction_rollback_cb(Convert(&handle), GetUserData()); + } + } + + void WriteProfilingInformation(std::ostream &ss) override { + if (!callbacks.profiling_cb) { + return; + } + CV2ContextStateProfile profile(ss); + CV2ErrorInfo info; + auto handle = Convert(&info); + // an error is dropped: the profile is written whatever the state adds to it + callbacks.profiling_cb(Convert(&profile), GetUserData(), &handle); + } + + const void *GetStateTag() const override { + return &CV2_CONTEXT_STATE_TAG; + } + +private: + CV2ContextStateBuilder callbacks; +}; + +//! Throws if `state` is not C API state. +static void CheckState(const string &key, ClientContextState &state) { + if (state.GetStateTag() != &CV2_CONTEXT_STATE_TAG) { + throw InvalidInputException("The key \"%s\" is in use by state that is not registered through the C API", key); + } +} + +//! `state` as C API state. Throws if it is state of something else. +static auto CastState(const string &key, shared_ptr state) -> shared_ptr { + if (!state) { + return nullptr; + } + CheckState(key, *state); + return shared_ptr_cast(std::move(state)); +} + +//! The C API state under `key`, or null if the key has none. Throws if it is held by state of something else. +static auto FindState(ClientContext &client, const string &key) -> shared_ptr { + return CastState(key, client.GetContext().GetRegisteredState().Get(key)); +} + +static void GetOrCreateState(ClientContext &client, CV2Context &context, const string &key, + duckdb_v2_context_state_init_callback_fn init, void *init_user_data, void **data) { + auto state = FindState(client, key); + if (!state) { + // the init runs outside the registry lock, and loses to a state another thread registered meanwhile + auto created = make_shared_ptr(context, init, init_user_data); + state = CastState(key, client.GetContext().GetRegisteredState().GetOrInsert(key, std::move(created))); + } + if (data) { + *data = state->GetUserData(); + } +} + +static void GetState(ClientContext &client, const string &key, bool *found, void **data) { + auto state = FindState(client, key); + *found = state != nullptr; + if (state && data) { + *data = state->GetUserData(); + } +} + +static void RemoveState(ClientContext &client, const string &key) { + // refuse to remove what the C API did not register + client.GetContext().GetRegisteredState().RemoveIf(key, [&](ClientContextState &state) { + CheckState(key, state); + return true; + }); +} + +} // namespace duckdb::capiv2 + +//---------------------------------------------------------------------------------------------------------------------- +// Public Functions +//---------------------------------------------------------------------------------------------------------------------- + +using namespace duckdb::capiv2; + +DUCKDB_V2_ERROR duckdb_v2_context_get_or_create_state(duckdb_v2_context_handle context, const char *key, + idx_t key_length, duckdb_v2_context_state_init_callback_fn init, + void *init_user_data, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(context); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_ARG(init); + if (data) { + *data = nullptr; + } + return WithErrorHandler(err, [&]() { + GetOrCreateState(Convert(context)->context, *Convert(context), duckdb::string(key, key_length), init, + init_user_data, data); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_connection_get_or_create_state(duckdb_v2_connection_handle conn, const char *key, + idx_t key_length, + duckdb_v2_context_state_init_callback_fn init, + void *init_user_data, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(conn); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_ARG(init); + if (data) { + *data = nullptr; + } + return WithErrorHandler(err, [&]() { + auto &connection = *Convert(conn); + GetOrCreateState(*connection.context, connection.context_handle, duckdb::string(key, key_length), init, + init_user_data, data); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_context_get_state(duckdb_v2_context_handle context, const char *key, idx_t key_length, + bool *found, void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(context); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_ARG(found); + return WithErrorHandler( + err, [&]() { GetState(Convert(context)->context, duckdb::string(key, key_length), found, data); }); +} + +DUCKDB_V2_ERROR duckdb_v2_connection_get_state(duckdb_v2_connection_handle conn, const char *key, idx_t key_length, + bool *found, void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(conn); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_ARG(found); + return WithErrorHandler(err, + [&]() { GetState(*Convert(conn)->context, duckdb::string(key, key_length), found, data); }); +} + +DUCKDB_V2_ERROR duckdb_v2_context_remove_state(duckdb_v2_context_handle context, const char *key, idx_t key_length, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(context); + DUCKDB_CHECK_STR_ARG(key, key_length); + return WithErrorHandler(err, [&]() { RemoveState(Convert(context)->context, duckdb::string(key, key_length)); }); +} + +DUCKDB_V2_ERROR duckdb_v2_connection_remove_state(duckdb_v2_connection_handle conn, const char *key, idx_t key_length, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(conn); + DUCKDB_CHECK_STR_ARG(key, key_length); + return WithErrorHandler(err, [&]() { RemoveState(*Convert(conn)->context, duckdb::string(key, key_length)); }); +} + +DUCKDB_V2_ERROR duckdb_v2_context_state_set_user_data(duckdb_v2_context_state_handle state, duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(state); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { + Convert(state)->user_data = duckdb::make_shared_ptr(data->ptr, data->destroy, data->equals); + }); +} + +DUCKDB_V2_ERROR +duckdb_v2_context_state_set_query_begin_callback(duckdb_v2_context_state_handle state, + duckdb_v2_context_state_query_begin_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(state); + return WithErrorHandler(err, [&]() { Convert(state)->query_begin_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_context_state_set_query_end_callback(duckdb_v2_context_state_handle state, + duckdb_v2_context_state_query_end_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(state); + return WithErrorHandler(err, [&]() { Convert(state)->query_end_cb = callback; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_context_state_set_transaction_begin_callback(duckdb_v2_context_state_handle state, + duckdb_v2_context_state_transaction_begin_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(state); + return WithErrorHandler(err, [&]() { Convert(state)->transaction_begin_cb = callback; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_context_state_set_transaction_commit_callback(duckdb_v2_context_state_handle state, + duckdb_v2_context_state_transaction_end_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(state); + return WithErrorHandler(err, [&]() { Convert(state)->transaction_commit_cb = callback; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_context_state_set_transaction_rollback_callback(duckdb_v2_context_state_handle state, + duckdb_v2_context_state_transaction_end_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(state); + return WithErrorHandler(err, [&]() { Convert(state)->transaction_rollback_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_context_state_set_profiling_callback(duckdb_v2_context_state_handle state, + duckdb_v2_context_state_profiling_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(state); + return WithErrorHandler(err, [&]() { Convert(state)->profiling_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_context_state_profile_write(duckdb_v2_context_state_profile_handle profile, const char *text, + idx_t text_length, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(profile); + DUCKDB_CHECK_STR_ARG(text, text_length); + return WithErrorHandler(err, + [&]() { Convert(profile)->ss.write(text, static_cast(text_length)); }); +} diff --git a/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp b/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp index 2aff41431..5e3e4947c 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp @@ -7,6 +7,7 @@ #include "duckdb/execution/partition_info.hpp" #include "duckdb/function/partition_stats.hpp" #include "duckdb/main/profiler/metrics.hpp" +#include "duckdb/parallel/async_result.hpp" #include "duckdb/parallel/pipeline.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" @@ -26,7 +27,7 @@ class CV2DataSourceGlobalState final : public GlobalTableFunctionState { return max_threads; } - CV2UserData handle; + shared_ptr handle = make_shared_ptr(); idx_t max_threads = 1; // The declared column each vector of the output chunk stands for, kept here so the exec callback can ask. @@ -35,11 +36,15 @@ class CV2DataSourceGlobalState final : public GlobalTableFunctionState { class CV2DataSourceLocalState final : public LocalTableFunctionState { public: - CV2UserData handle; + //! Shared with the tasks the exec callback adds, whose data may refer to it + shared_ptr handle = make_shared_ptr(); //! Whether the caller claims the batches of this thread (see TableFunction::claim_batch) bool claimed_externally = false; //! Whether this thread has claimed a batch it has not exhausted yet bool batch_claimed = false; + //! What the last invocation of the exec callback declared, and the tasks it added + DUCKDB_V2_DATA_SOURCE_RESULT result = DUCKDB_V2_DATA_SOURCE_RESULT_IMPLICIT; + vector> tasks; //! Written into by the exec callback when the scan requests no columns, as the function produces its rows through //! its first column unique_ptr row_chunk; @@ -155,7 +160,37 @@ class CV2TableExecInfo { void *in_local_state = nullptr; const vector *in_scan_columns = nullptr; + //! The states the data of an added task may refer to, kept alive by the task + vector> task_states; + DataChunk *output = nullptr; + DUCKDB_V2_DATA_SOURCE_RESULT out_result = DUCKDB_V2_DATA_SOURCE_RESULT_IMPLICIT; + vector> out_tasks; +}; + +//! A task the exec callback added: the scan is blocked until it has run. The task may outlive the scan, so it keeps the +//! states its data may refer to alive until its data is destroyed. +class CV2DataSourceTask final : public AsyncTask { +public: + CV2DataSourceTask(duckdb_v2_data_source_task_callback_fn task_cb, CV2UserData data, + vector> states) + : task_cb(task_cb), states(std::move(states)), data(std::move(data)) { + } + + void Execute() override { + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + task_cb(data.GetData(), &err_ptr); + if (err.HasError()) { + err.ThrowAsException(); + } + } + +private: + duckdb_v2_data_source_task_callback_fn task_cb; + //! Declared before the data, so that the data is destroyed first + vector> states; + CV2UserData data; }; static auto Convert(duckdb_v2_data_source_exec_info_handle info) -> CV2TableExecInfo * { @@ -430,7 +465,7 @@ auto CV2DataSourceInitGlobal(ClientContext &context, TableFunctionInitInput &inp info.init_global_cb(Convert(&args), Convert(&callback_context), &err_ptr); if (args.out_global_state.ptr) { - result->handle = + *result->handle = CV2UserData(args.out_global_state.ptr, args.out_global_state.destroy, args.out_global_state.equals); } result->max_threads = args.out_max_threads; @@ -527,7 +562,7 @@ auto CV2DataSourceInitLocal(ExecutionContext &context, TableFunctionInitInput &i args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; args.in_scan_columns = &scan_columns; if (global_state) { - args.in_global_state = global_state->Cast().handle.GetData(); + args.in_global_state = global_state->Cast().handle->GetData(); } CV2ErrorInfo err = {}; @@ -536,7 +571,7 @@ auto CV2DataSourceInitLocal(ExecutionContext &context, TableFunctionInitInput &i info.init_local_cb(Convert(&args), Convert(&callback_context), &err_ptr); if (args.out_local_state.ptr) { - result->handle = + *result->handle = CV2UserData(args.out_local_state.ptr, args.out_local_state.destroy, args.out_local_state.equals); } @@ -558,9 +593,9 @@ static auto CV2TableClaimNextBatch(ClientContext &context, TableFunctionInput &i args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; if (input.global_state) { - args.in_global_state = input.global_state->Cast().handle.GetData(); + args.in_global_state = input.global_state->Cast().handle->GetData(); } - args.in_local_state = local_state.handle.GetData(); + args.in_local_state = local_state.handle->GetData(); CV2ErrorInfo err = {}; auto err_ptr = Convert(&err); @@ -582,7 +617,7 @@ auto CV2DataSourceClaimBatch(ClientContext &context, TableFunctionInput &input) static auto CV2TableExecBatch(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void; -auto CV2DataSourceExec(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { +static auto CV2DataSourceExecClaimed(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { const auto &info = *input.bind_data->Cast().source; if (!info.claim_batch_cb) { CV2TableExecBatch(context, input, output); @@ -600,10 +635,78 @@ auto CV2DataSourceExec(ClientContext &context, TableFunctionInput &input, DataCh return; } CV2TableExecBatch(context, input, output); - if (output.size() > 0) { + if (output.size() > 0 || local_state.result == DUCKDB_V2_DATA_SOURCE_RESULT_BLOCKED) { return; } local_state.batch_claimed = false; + if (local_state.result == DUCKDB_V2_DATA_SOURCE_RESULT_FINISHED) { + return; + } + } +} + +//! Checks the result the exec callback declared against the batch it produced +static auto CheckDeclaredResult(const CV2DataSourceLocalState &local_state, idx_t row_count) -> void { + switch (local_state.result) { + case DUCKDB_V2_DATA_SOURCE_RESULT_IMPLICIT: + break; + case DUCKDB_V2_DATA_SOURCE_RESULT_HAVE_MORE_OUTPUT: + if (row_count == 0) { + throw InvalidInputException("A data source declared that its scan has more output, but produced no rows"); + } + break; + case DUCKDB_V2_DATA_SOURCE_RESULT_FINISHED: + if (row_count > 0) { + throw InvalidInputException("A data source declared that its scan is finished, but produced rows"); + } + break; + case DUCKDB_V2_DATA_SOURCE_RESULT_BLOCKED: + if (row_count > 0) { + throw InvalidInputException("A data source declared that its scan is blocked, but produced rows"); + } + if (local_state.tasks.empty()) { + throw InvalidInputException("A data source declared that its scan is blocked, but added no task to run"); + } + break; + default: + throw InvalidInputException("A data source declared an unknown result: %d", + static_cast(local_state.result)); + } + if (!local_state.tasks.empty() && local_state.result != DUCKDB_V2_DATA_SOURCE_RESULT_BLOCKED) { + throw InvalidInputException("A data source added a task to run, but declared that its scan is not blocked"); + } +} + +auto CV2DataSourceExec(ClientContext &context, TableFunctionInput &input, DataChunk &output) -> void { + auto &local_state = input.local_state->Cast(); + while (true) { + // a pass that claims no batch does not invoke the callback, and declares nothing + local_state.result = DUCKDB_V2_DATA_SOURCE_RESULT_IMPLICIT; + local_state.tasks.clear(); + CV2DataSourceExecClaimed(context, input, output); + switch (local_state.result) { + case DUCKDB_V2_DATA_SOURCE_RESULT_HAVE_MORE_OUTPUT: + input.async_result = AsyncResultType::HAVE_MORE_OUTPUT; + return; + case DUCKDB_V2_DATA_SOURCE_RESULT_FINISHED: + input.async_result = AsyncResultType::FINISHED; + return; + case DUCKDB_V2_DATA_SOURCE_RESULT_BLOCKED: { + AsyncResult blocked(std::move(local_state.tasks)); + local_state.tasks.clear(); + if (input.results_execution_mode == AsyncResultsExecutionMode::TASK_EXECUTOR) { + // the scan reschedules once the tasks have run, which calls the function again + input.async_result = std::move(blocked); + return; + } + // a synchronous scan cannot block: run the tasks here, then call the function again + blocked.ExecuteTasksSynchronously(); + context.FastInterruptCheck(); + break; + } + default: + return; + } } } @@ -656,11 +759,18 @@ static auto CV2TableExecBatchOnce(ClientContext &context, TableFunctionInput &in args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; if (input.global_state) { auto &global_state = input.global_state->Cast(); - args.in_global_state = global_state.handle.GetData(); + args.in_global_state = global_state.handle->GetData(); args.in_scan_columns = &global_state.scan_columns; } auto &local_state = input.local_state->Cast(); - args.in_local_state = local_state.handle.GetData(); + args.in_local_state = local_state.handle->GetData(); + args.task_states.push_back(local_state.handle); + if (input.global_state) { + args.task_states.push_back(input.global_state->Cast().handle); + } + if (bind_data.handle) { + args.task_states.push_back(bind_data.handle); + } reference target(output); if (output.ColumnCount() == 0) { // the scan requests no columns (e.g. for count(*)), only rows - the function writes them into its first column @@ -678,6 +788,8 @@ static auto CV2TableExecBatchOnce(ClientContext &context, TableFunctionInput &in CV2CallbackContext callback_context(context); info.exec_cb(Convert(&args), Convert(&callback_context), &err_ptr); + local_state.result = args.out_result; + local_state.tasks = std::move(args.out_tasks); if (err.HasError()) { err.ThrowAsException(); } @@ -686,6 +798,7 @@ static auto CV2TableExecBatchOnce(ClientContext &context, TableFunctionInput &in // only the first vector and write the rest through direct buffer writes, so take the first vector's size as the // batch's row count and propagate it to the others. A table function always has at least one result column. auto row_count = target.get().data[0].size(); + CheckDeclaredResult(local_state, row_count); if (output.ColumnCount() == 0) { output.SetCardinalityUnsafe(row_count); return; @@ -703,7 +816,7 @@ static auto CV2DataSourceProgress(ClientContext &context, const FunctionData *bi args.in_bind_data = data.handle ? data.handle->GetData() : nullptr; if (global_state) { // The callback runs concurrently with the scan, so the state it reads is the shared one, unsynchronized. - args.in_global_state = global_state->Cast().handle.GetData(); + args.in_global_state = global_state->Cast().handle->GetData(); } CV2ErrorInfo err = {}; @@ -731,7 +844,7 @@ static auto CV2DataSourceGetMetrics(TableFunctionGetMetricsInput &input) -> void args.in_bind_data = data.handle ? data.handle->GetData() : nullptr; if (input.global_state) { // The callback can run while the scan does, so the state it reads is the shared one, unsynchronized. - args.in_global_state = input.global_state->Cast().handle.GetData(); + args.in_global_state = input.global_state->Cast().handle->GetData(); } CV2ErrorInfo err = {}; @@ -779,8 +892,8 @@ static auto CV2DataSourceGetPartitionData(ClientContext &context, TableFunctionG CV2TablePartitionDataInfo args = {}; args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; - args.in_global_state = global_state.handle.GetData(); - args.in_local_state = local_state.handle.GetData(); + args.in_global_state = global_state.handle->GetData(); + args.in_local_state = local_state.handle->GetData(); args.in_partition_info = &input.partition_info; // The planner resolves these to scan positions, unlike get_partition_info's, which it resolves to declared // columns; the callback is promised declared columns in both. @@ -980,6 +1093,42 @@ DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_output_chunk(duckdb_v2_data_sourc return WithErrorHandler(err, [&]() { *chunk = Convert(Convert(info)->output); }); } +DUCKDB_V2_ERROR duckdb_v2_data_source_exec_set_result(duckdb_v2_data_source_exec_info_handle info, + DUCKDB_V2_DATA_SOURCE_RESULT result, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + return WithErrorHandler(err, [&]() { + switch (result) { + case DUCKDB_V2_DATA_SOURCE_RESULT_IMPLICIT: + case DUCKDB_V2_DATA_SOURCE_RESULT_HAVE_MORE_OUTPUT: + case DUCKDB_V2_DATA_SOURCE_RESULT_FINISHED: + case DUCKDB_V2_DATA_SOURCE_RESULT_BLOCKED: + Convert(info)->out_result = result; + break; + default: + throw duckdb::InvalidInputException("Unknown data source result: %d", static_cast(result)); + } + }); +} + +DUCKDB_V2_ERROR duckdb_v2_data_source_exec_add_task(duckdb_v2_data_source_exec_info_handle info, + duckdb_v2_data_source_task_callback_fn task, duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err) { + // the data is taken over, also when the call fails + CV2UserData task_data; + if (data) { + task_data = CV2UserData(data->ptr, data->destroy); + } + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(task); + return WithErrorHandler(err, [&]() { + auto &exec_info = *Convert(info); + exec_info.out_tasks.push_back( + duckdb::make_uniq(task, std::move(task_data), exec_info.task_states)); + exec_info.out_result = DUCKDB_V2_DATA_SOURCE_RESULT_BLOCKED; + }); +} + DUCKDB_V2_ERROR duckdb_v2_data_source_exec_get_column_count(duckdb_v2_data_source_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp b/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp index 1290bd775..512f31464 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_file_system.cpp @@ -3,7 +3,7 @@ #include "duckdb/common/file_open_flags.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/open_file_info.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" namespace duckdb::capiv2 { @@ -28,8 +28,11 @@ class CV2FileOpenOptions { // An open file, owned. Carries the context for the same reason the file system handle does. class CV2File { public: + explicit CV2File(Context &query_p) : query(query_p) { + } + unique_ptr handle; - QueryContext query; + Context &query; auto Handle() const -> FileHandle & { return *handle; @@ -193,15 +196,14 @@ DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_handle file_sys duckdb::OpenFileInfo info(duckdb::string(Convert(file_path, file_path_length))); info.extended_info = opts.extended_info; - // FileSystem::GetFileSystem hands back the context's own bound FileSystem, which pushes the opener itself -- - // which is how a remote file system reaches settings and secrets. + // The context's own FileSystem passes its context itself, which is how a remote file system reaches + // settings and secrets. auto handle = slot.fs.OpenFile(info, opts.flags); if (!handle) { throw duckdb::IOException("Failed to open file: %s", info.path); } - auto file = duckdb::make_uniq(); + auto file = duckdb::make_uniq(slot.query); file->handle = std::move(handle); - file->query = slot.query; *out_file_handle = Convert(file.release()); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp b/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp index 95ff8da45..a73bc0e75 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp @@ -16,12 +16,12 @@ namespace capiv2 { // detected across instances, while no instance is memoized. CV2Instance::CV2Instance(CV2Environment &env, DBConfig &startup_config) : database(env.cache->CreateEmptyInstance(startup_config)), env(env), factory(*this), config_handle(*this), - file_system(FileSystem::GetFileSystem(*database->instance), QueryContext()) { + file_system(FileSystem::GetFileSystem(*database->instance), database->instance->GetContext()) { } CV2Instance::CV2Instance(CV2Environment &env, shared_ptr shared_database) : database(std::move(shared_database)), env(env), factory(*this), config_handle(*this), - file_system(FileSystem::GetFileSystem(*database->instance), QueryContext()) { + file_system(FileSystem::GetFileSystem(*database->instance), database->instance->GetContext()) { } DatabaseInstance &CV2InstanceFactory::GetDatabase() { @@ -73,7 +73,7 @@ void CV2Instance::Attach(const string &path, const Identifier &name, // The host opening a file is not external access: allow it the way the main database path is allowed. if (options.db_type.empty() && !DBConfig::IsInMemoryDatabase(info.path.c_str()) && !FileSystem::IsRemoteFile(info.path) && !Settings::Get(instance)) { - instance.config.AddAllowedDatabasePath(info.path); + instance.config.AddAllowedDatabasePath(instance.GetContext(), info.path); } auto &db_manager = DatabaseManager::Get(instance); auto attached = db_manager.AttachDatabase(context, info, options); diff --git a/src/duckdb/src/main/client_context.cpp b/src/duckdb/src/main/client_context.cpp index 1d02ca552..442c383a7 100644 --- a/src/duckdb/src/main/client_context.cpp +++ b/src/duckdb/src/main/client_context.cpp @@ -13,7 +13,6 @@ #include "duckdb/execution/physical_plan_generator.hpp" #include "duckdb/main/appender.hpp" #include "duckdb/main/attached_database.hpp" -#include "duckdb/main/client_context_file_opener.hpp" #include "duckdb/main/active_query_context.hpp" #include "duckdb/main/client_context_state.hpp" #include "duckdb/main/client_data.hpp" @@ -890,8 +889,8 @@ void ClientContext::LogQueryInternal(ClientContextLock &, const string &query) { #ifdef DUCKDB_FORCE_QUERY_LOG try { string log_path(DUCKDB_FORCE_QUERY_LOG); - client_data->log_query_writer = make_uniq(FileSystem::GetFileSystem(*this), log_path, - BufferedFileWriter::DEFAULT_OPEN_FLAGS); + client_data->log_query_writer = make_uniq( + FileSystem::GetFileSystem(*this), GetContext(), log_path, BufferedFileWriter::DEFAULT_OPEN_FLAGS); } catch (...) { return; } diff --git a/src/duckdb/src/main/client_context_execution.cpp b/src/duckdb/src/main/client_context_execution.cpp index cf78d0935..7f230d89c 100644 --- a/src/duckdb/src/main/client_context_execution.cpp +++ b/src/duckdb/src/main/client_context_execution.cpp @@ -49,7 +49,13 @@ void ClientContext::BeginQueryInternal(ClientContextLock &lock, PreprocessedStat active_query->retention = ResultLifetime::RETAINED; } if (transaction.IsAutoCommit() && !transaction.HasActiveTransaction()) { - transaction.BeginTransaction(); + try { + transaction.BeginTransaction(); + } catch (...) { + // no state saw the query begin, so none is to see it end + active_query.reset(); + throw; + } } BeginStatementInternal(lock, query); @@ -68,9 +74,21 @@ void ClientContext::BeginQueryInternal(ClientContextLock &lock, PreprocessedStat } else { query_deadline.SetInvalid(); } - // Notify any registered state of query begin + // Notify any registered state of query begin - all of them, also when one of them fails, so that all see it end + ErrorData begin_error; for (auto &state : context->GetRegisteredState().States()) { - state->QueryBegin(*this); + try { + state->QueryBegin(*this); + } catch (std::exception &ex) { + if (!begin_error.HasError()) { + begin_error = ErrorData(ex); + } + } + } + if (begin_error.HasError()) { + // a state rejected the query: end it right away, which rolls back the transaction it started + EndQueryInternal(lock, false, false, &begin_error); + begin_error.Throw(); } RefreshLoggerInternal(); } diff --git a/src/duckdb/src/main/client_context_file_opener.cpp b/src/duckdb/src/main/client_context_file_opener.cpp deleted file mode 100644 index 0261a802c..000000000 --- a/src/duckdb/src/main/client_context_file_opener.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include "duckdb/main/client_context_file_opener.hpp" -#include "duckdb/catalog/catalog_transaction.hpp" - -#include "duckdb/main/database.hpp" -#include "duckdb/common/file_opener.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/main/context.hpp" -#include "duckdb/logging/log_manager.hpp" -#include "duckdb/main/http/http_util.hpp" - -namespace duckdb { - -SettingLookupResult ClientContextFileOpener::TryGetCurrentSetting(const Identifier &key, Value &result) { - return context.TryGetCurrentSetting(key, result); -} - -Logger &ClientContextFileOpener::GetLogger() const { - return context.GetLogger(); -} - -// LCOV_EXCL_START -SettingLookupResult ClientContextFileOpener::TryGetCurrentSetting(const Identifier &key, Value &result, - FileOpenerInfo &) { - return context.TryGetCurrentSetting(key, result); -} - -optional_ptr ClientContextFileOpener::TryGetDatabase() { - return &context.GetDatabase(); -} - -HTTPUtil &ClientContextFileOpener::GetHTTPUtil() { - return HTTPUtil::Get(*TryGetDatabase()); -} - -unique_ptr FileOpener::TryGetCatalogTransaction(optional_ptr opener) { - if (!opener) { - return nullptr; - } - return make_uniq(CatalogTransaction::GetSystemCatalogTransaction(opener->TryGetContext())); -} - -optional_ptr FileOpener::TryGetContext(optional_ptr opener) { - if (!opener) { - return nullptr; - } - return &opener->TryGetContext(); -} - -optional_ptr FileOpener::TryGetDatabase(optional_ptr opener) { - if (!opener) { - return nullptr; - } - return opener->TryGetDatabase(); -} - -optional_ptr FileOpener::TryGetSecretManager(optional_ptr opener) { - if (!opener) { - return nullptr; - } - - auto db = opener->TryGetDatabase(); - if (!db) { - return nullptr; - } - - return &db->GetSecretManager(); -} - -SettingLookupResult FileOpener::TryGetCurrentSetting(optional_ptr opener, const Identifier &key, - Value &result) { - if (!opener) { - return SettingLookupResult(); - } - return opener->TryGetCurrentSetting(key, result); -} - -SettingLookupResult FileOpener::TryGetCurrentSetting(optional_ptr opener, const Identifier &key, - Value &result, FileOpenerInfo &info) { - if (!opener) { - return SettingLookupResult(); - } - return opener->TryGetCurrentSetting(key, result, info); -} - -SettingLookupResult FileOpener::TryGetCurrentSetting(const Identifier &key, Value &result, FileOpenerInfo &info) { - return TryGetCurrentSetting(key, result); -} -// LCOV_EXCL_STOP -} // namespace duckdb diff --git a/src/duckdb/src/main/client_data.cpp b/src/duckdb/src/main/client_data.cpp index dcfe62431..9f995d9d8 100644 --- a/src/duckdb/src/main/client_data.cpp +++ b/src/duckdb/src/main/client_data.cpp @@ -9,7 +9,6 @@ #include "duckdb/main/attached_database.hpp" #include "duckdb/main/client_config.hpp" #include "duckdb/main/client_context.hpp" -#include "duckdb/main/client_context_file_opener.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/main/query_profiler.hpp" @@ -30,7 +29,7 @@ ClientData::ClientData(ClientContext &context) : catalog_search_path(make_uniq opener) const { - auto &fs = file_system->FindFileSystem(path_p, opener); - auto result = fs.CanonicalizePath(FileSystem::ExpandPath(path_p, opener), opener); +string DBConfig::SanitizeAllowedPath(Context &context, const string &path_p) const { + // canonicalizing does not need the file system extension of the path, so it is not autoloaded + auto &fs = file_system->FindFileSystem(path_p); + auto result = fs.CanonicalizePath(context, FileSystem::ExpandPath(context, path_p)); // allowed_directories/allowed_path always uses forward slashes regardless of the OS auto path_sep = fs.PathSeparator(path_p); if (path_sep != "/") { @@ -1070,8 +1071,8 @@ void DBConfig::AddAllowedConfig(const Identifier &config_name) { throw InvalidInputException("Unknown configuration option %s in allowed_configs", config_name); } -void DBConfig::AddAllowedDirectory(const string &path) { - auto allowed_directory = SanitizeAllowedPath(path); +void DBConfig::AddAllowedDirectory(Context &context, const string &path) { + auto allowed_directory = SanitizeAllowedPath(context, path); if (allowed_directory.empty()) { throw InvalidInputException("Cannot provide an empty string for allowed_directory"); } @@ -1107,10 +1108,10 @@ void DBConfig::SetDisabledOptimizers(set disabled_optimizers) { has_disabled_optimizers.store(!options.disabled_optimizers.empty()); } -void DBConfig::SetAllowedDirectories(const vector &paths) { +void DBConfig::SetAllowedDirectories(Context &context, const vector &paths) { decltype(options.allowed_directories) new_directories; for (auto &path : paths) { - auto allowed_directory = SanitizeAllowedPath(path); + auto allowed_directory = SanitizeAllowedPath(context, path); if (allowed_directory.empty()) { throw InvalidInputException("Cannot provide an empty string for allowed_directory"); } @@ -1123,10 +1124,10 @@ void DBConfig::SetAllowedDirectories(const vector &paths) { options.allowed_directories = std::move(new_directories); } -void DBConfig::SetAllowedPaths(const vector &paths) { +void DBConfig::SetAllowedPaths(Context &context, const vector &paths) { decltype(options.allowed_paths) new_paths; for (auto &path : paths) { - new_paths.insert(SanitizeAllowedPath(path)); + new_paths.insert(SanitizeAllowedPath(context, path)); } lock_guard guard(allowed_paths_lock); options.allowed_paths = std::move(new_paths); @@ -1142,17 +1143,17 @@ void DBConfig::ResetAllowedPaths() { options.allowed_paths = DBConfigOptions().allowed_paths; } -void DBConfig::AddAllowedPath(const string &path) { - auto allowed_path = SanitizeAllowedPath(path); +void DBConfig::AddAllowedPath(Context &context, const string &path) { + auto allowed_path = SanitizeAllowedPath(context, path); lock_guard guard(allowed_paths_lock); options.allowed_paths.insert(allowed_path); } -void DBConfig::AddAllowedDatabasePath(const string &database_path) { - AddAllowedPath(database_path); - AddAllowedPath(database_path + ".wal"); - AddAllowedPath(database_path + ".wal.checkpoint"); - AddAllowedPath(database_path + ".wal.recovery"); +void DBConfig::AddAllowedDatabasePath(Context &context, const string &database_path) { + AddAllowedPath(context, database_path); + AddAllowedPath(context, database_path + ".wal"); + AddAllowedPath(context, database_path + ".wal.checkpoint"); + AddAllowedPath(context, database_path + ".wal.recovery"); } vector DBConfig::GetAllowedDirectories() const { @@ -1197,7 +1198,7 @@ static bool HasRemotePathTraversal(const string &path) { return false; } -bool DBConfig::CanAccessFile(const string &input_path, FileType type, optional_ptr opener) { +bool DBConfig::CanAccessFile(Context &context, const string &input_path, FileType type) { if (Settings::Get(*this)) { // all external access is allowed return true; @@ -1206,7 +1207,7 @@ bool DBConfig::CanAccessFile(const string &input_path, FileType type, optional_p if (HasRemotePathTraversal(input_path)) { return false; } - string path = SanitizeAllowedPath(input_path, opener); + string path = SanitizeAllowedPath(context, input_path); lock_guard guard(allowed_paths_lock); if (options.allowed_paths.count(path) > 0) { diff --git a/src/duckdb/src/main/context.cpp b/src/duckdb/src/main/context.cpp index 8179b48a6..43f38d525 100644 --- a/src/duckdb/src/main/context.cpp +++ b/src/duckdb/src/main/context.cpp @@ -6,7 +6,6 @@ #include "duckdb/logging/logger.hpp" #include "duckdb/main/client_config.hpp" #include "duckdb/main/client_context.hpp" -#include "duckdb/main/client_context_file_opener.hpp" #include "duckdb/main/client_context_state.hpp" #include "duckdb/main/config.hpp" #include "duckdb/main/database.hpp" @@ -18,7 +17,7 @@ namespace duckdb { -//! The file system of a client: the database file system with the client file opener +//! The file system of a client: the database file system with the context of the client class ClientFileSystem : public FileSystem { public: explicit ClientFileSystem(ClientContext &context_p) : context(context_p) { @@ -28,8 +27,8 @@ class ClientFileSystem : public FileSystem { return VirtualFileSystem::Get(context); } - optional_ptr GetOpener() const override { - return context.GetContext().TryGetFileOpener(); + Context &GetContext() const override { + return context.GetContext(); } ClientContext &context; @@ -60,7 +59,7 @@ class ContextBufferManager : public BufferManager { return result; } BufferHandle Allocate(MemoryTag tag, idx_t block_size, bool can_destroy = true) override { - auto result = Inner().Allocate(QueryContext(context), tag, block_size, can_destroy); + auto result = Inner().Allocate(context, tag, block_size, can_destroy); // Track allocation based on actual allocated size from the handle if (result.GetBlockHandle()) { TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); @@ -68,21 +67,21 @@ class ContextBufferManager : public BufferManager { return result; } BufferHandle Allocate(MemoryTag tag, BlockManager *block_manager, bool can_destroy = true) override { - auto result = Inner().Allocate(QueryContext(context), tag, block_manager, can_destroy); + auto result = Inner().Allocate(context, tag, block_manager, can_destroy); // Track allocation based on actual allocated size from the handle if (result.GetBlockHandle()) { TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); } return result; } - BufferHandle Allocate(QueryContext context, MemoryTag tag, idx_t block_size, bool can_destroy = true) override { + BufferHandle Allocate(Context &context, MemoryTag tag, idx_t block_size, bool can_destroy = true) override { auto result = Inner().Allocate(context, tag, block_size, can_destroy); if (result.GetBlockHandle()) { TrackMemoryAllocation(result.GetBlockHandle()->GetMemory().GetMemoryUsage()); } return result; } - BufferHandle Allocate(QueryContext context, MemoryTag tag, BlockManager *block_manager, + BufferHandle Allocate(Context &context, MemoryTag tag, BlockManager *block_manager, bool can_destroy = true) override { auto result = Inner().Allocate(context, tag, block_manager, can_destroy); if (result.GetBlockHandle()) { @@ -91,12 +90,12 @@ class ContextBufferManager : public BufferManager { return result; } BufferHandle Pin(shared_ptr &handle) override { - return Pin(QueryContext(context), handle); + return Pin(context, handle); } - BufferHandle Pin(const QueryContext &context, shared_ptr &handle) override { + BufferHandle Pin(Context &context, shared_ptr &handle) override { return Inner().Pin(context, handle); } - void Prefetch(QueryContext context, vector> &handles) override { + void Prefetch(Context &context, vector> &handles) override { return Inner().Prefetch(context, handles); } void Unpin(shared_ptr &handle) override { @@ -207,10 +206,10 @@ class ContextBufferManager : public BufferManager { void AddToEvictionQueue(shared_ptr &handle) override { return Inner().AddToEvictionQueue(handle); } - void WriteTemporaryBuffer(QueryContext context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer) override { + void WriteTemporaryBuffer(Context &context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer) override { return Inner().WriteTemporaryBuffer(context, tag, block_id, buffer); } - unique_ptr ReadTemporaryBuffer(QueryContext context, MemoryTag tag, BlockHandle &block, + unique_ptr ReadTemporaryBuffer(Context &context, MemoryTag tag, BlockHandle &block, unique_ptr buffer) override { return Inner().ReadTemporaryBuffer(context, tag, block, std::move(buffer)); } @@ -244,7 +243,6 @@ void Context::InitializeClient(ClientContext &context_p) { D_ASSERT(!context); context = &context_p; config = make_uniq(); - file_opener = make_uniq(*this); client_file_system = make_uniq(context_p); profiler = make_shared_ptr(context_p); registered_state = make_uniq(); @@ -265,6 +263,10 @@ optional_ptr Context::TryGetClientContext(optional_ptr c return context->TryGetClientContext(); } +Context &Context::GetOrDatabase(optional_ptr client, DatabaseInstance &db) { + return client ? client->GetContext() : db.GetContext(); +} + optional_ptr Context::TryGetQueryProfiler(optional_ptr context) { if (!context) { return nullptr; @@ -345,10 +347,6 @@ FileSystem &Context::GetFileSystem() const { return FileSystem::GetFileSystem(db); } -optional_ptr Context::TryGetFileOpener() const { - return file_opener.get(); -} - BufferManager &Context::GetBufferManager() const { return *buffer_manager; } diff --git a/src/duckdb/src/main/database.cpp b/src/duckdb/src/main/database.cpp index a0834d665..70cd6730e 100644 --- a/src/duckdb/src/main/database.cpp +++ b/src/duckdb/src/main/database.cpp @@ -19,10 +19,11 @@ #include "duckdb/logging/logger.hpp" #include "duckdb/main/attached_database.hpp" #include "duckdb/main/capi/extension_api.hpp" +#include "duckdb/common/multi_file/table_function_query_filter.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/context.hpp" #include "duckdb/main/connection_manager.hpp" -#include "duckdb/main/database_file_opener.hpp" +#include "duckdb/main/database_file_system.hpp" #include "duckdb/main/database_file_path_manager.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/main/external_resource_type_registry.hpp" @@ -87,6 +88,7 @@ DatabaseInstance::DatabaseInstance() : db_validity(*this) { config.is_user_config = false; create_api_v1 = nullptr; invoke_capi_v2 = nullptr; + create_file_filter = nullptr; parser_cache = make_uniq(); services = make_uniq(*this); } @@ -356,6 +358,9 @@ void DatabaseInstance::InitializeInstance(const char *database_path, DBConfig *u } Configure(*config_ptr, database_path); + // the log manager comes first: opening a file (e.g. from an extension callback) logs through it + log_manager = make_uniq(*this, LogConfig()); + log_manager->Initialize(); // publish what this binary links, unless the config already carries a set handed to us ExtensionHelper::RegisterLinkedExtensions(config); for (auto &linked : config.linked_extensions) { @@ -366,6 +371,7 @@ void DatabaseInstance::InitializeInstance(const char *database_path, DBConfig *u create_api_v1 = CreateAPIv1Wrapper; invoke_capi_v2 = InvokeCAPIV2Entrypoint; + create_file_filter = TableFunctionQueryFilter::TryCreate; db_file_system = make_uniq(*this); local_db_file_system = make_uniq(*this); @@ -378,9 +384,6 @@ void DatabaseInstance::InitializeInstance(const char *database_path, DBConfig *u buffer_manager = make_uniq(*this, config.options.temporary_directory); } - log_manager = make_uniq(*this, LogConfig()); - log_manager->Initialize(); - metrics_manager = make_uniq(); bool enable_external_file_cache = Settings::Get(config); @@ -401,7 +404,7 @@ void DatabaseInstance::InitializeInstance(const char *database_path, DBConfig *u // resolve the type of the database we are opening auto &fs = FileSystem::GetFileSystem(*this); - DBPathAndType::ResolveDatabaseType(fs, config.options.database_path, config.options.database_type); + DBPathAndType::ResolveDatabaseType(GetContext(), fs, config.options.database_path, config.options.database_type); if (!config.options.database_type.empty() && !StringUtil::CIEquals(config.options.database_type, "duckdb")) { // if we are opening an extension database - load the extension @@ -482,7 +485,7 @@ FileSystem &DatabaseInstance::GetLocalFileSystem() { } LocalDatabaseFileSystem::LocalDatabaseFileSystem(DatabaseInstance &db_p) - : file_system(VirtualFileSystem::Get(db_p)), database_opener(db_p) { + : file_system(VirtualFileSystem::Get(db_p)), context(db_p.GetContext()) { if (!file_system.GetDefaultFileSystem().IsLocalFileSystem()) { owned_file_system = make_uniq(); } @@ -562,9 +565,9 @@ void DatabaseInstance::Configure(DBConfig &new_config, const char *database_path } config.http_transport_manager->Initialize(config); if (database_path && !Settings::Get(*this)) { - config.AddAllowedDatabasePath(database_path); + config.AddAllowedDatabasePath(GetContext(), database_path); if (!config.options.temporary_directory.empty()) { - config.AddAllowedDirectory(config.options.temporary_directory); + config.AddAllowedDirectory(GetContext(), config.options.temporary_directory); } } if (new_config.secret_manager) { @@ -705,6 +708,11 @@ void DatabaseInstance::InvokeExtensionEntrypointV2(const ExtensionInitResult &in invoke_capi_v2(*this, init_result, extension_name, init_fun, context, statically_linked); } +unique_ptr DatabaseInstance::CreateFileFilter(ClientContext &context, BaseFileReader &reader) { + D_ASSERT(create_file_filter); + return create_file_filter(context, reader); +} + LogManager &DatabaseInstance::GetLogManager() const { return *log_manager; } diff --git a/src/duckdb/src/main/database_path_and_type.cpp b/src/duckdb/src/main/database_path_and_type.cpp index 7d07924ec..5abda879b 100644 --- a/src/duckdb/src/main/database_path_and_type.cpp +++ b/src/duckdb/src/main/database_path_and_type.cpp @@ -19,7 +19,7 @@ void DBPathAndType::ExtractExtensionPrefix(string &path, string &db_type) { } } -void DBPathAndType::CheckMagicBytes(QueryContext context, FileSystem &fs, string &path, string &db_type, +void DBPathAndType::CheckMagicBytes(Context &context, FileSystem &fs, string &path, string &db_type, optional_ptr out_prefetch) { // if there isn't - check the magic bytes of the file (if any) auto file_type = MagicBytes::CheckMagicBytes(context, fs, path, out_prefetch); @@ -43,7 +43,7 @@ void DBPathAndType::CheckMagicBytes(QueryContext context, FileSystem &fs, string } } -void DBPathAndType::ResolveDatabaseType(FileSystem &fs, string &path, string &db_type, +void DBPathAndType::ResolveDatabaseType(Context &context, FileSystem &fs, string &path, string &db_type, optional_ptr out_prefetch) { if (!db_type.empty()) { // database type specified explicitly - no need to check @@ -56,7 +56,7 @@ void DBPathAndType::ResolveDatabaseType(FileSystem &fs, string &path, string &db return; } // check database type by reading the magic bytes of a file - DBPathAndType::CheckMagicBytes(QueryContext(), fs, path, db_type, out_prefetch); + DBPathAndType::CheckMagicBytes(context, fs, path, db_type, out_prefetch); } } // namespace duckdb diff --git a/src/duckdb/src/main/db_instance_cache.cpp b/src/duckdb/src/main/db_instance_cache.cpp index 3b672ce75..c63963f6b 100644 --- a/src/duckdb/src/main/db_instance_cache.cpp +++ b/src/duckdb/src/main/db_instance_cache.cpp @@ -1,4 +1,6 @@ #include "duckdb/main/db_instance_cache.hpp" +#include "duckdb/common/local_file_system.hpp" +#include "duckdb/common/virtual_file_system.hpp" #include "duckdb/main/extension_helper.hpp" #include "duckdb/main/database_file_path_manager.hpp" @@ -14,7 +16,7 @@ DatabaseCacheEntry::~DatabaseCacheEntry() { } static string GetDBAbsolutePath(const string &database_p, VirtualFileSystem &fs) { - auto database = FileSystem::ExpandPath(database_p, nullptr); + auto database = FileSystem::ExpandPathWithHome(database_p, FileSystem::GetDefaultHomeDirectory()); if (database.empty()) { return IN_MEMORY_PATH; } @@ -26,8 +28,14 @@ static string GetDBAbsolutePath(const string &database_p, VirtualFileSystem &fs) // this database path is handled by a replacement open and is not a file path return database; } - // canonicalize the path - return fs.FindFileSystem(database, nullptr).CanonicalizePath(database, nullptr); + auto &path_fs = fs.FindFileSystem(database); + if (!path_fs.IsLocalFileSystem()) { + // there is no context yet: canonicalize without consulting the file system + return path_fs.GenericCanonicalizePath(database); + } + // there is no database yet, so only the default home directory is available + LocalFileSystem local_fs; + return local_fs.CanonicalizePathWithHome(database, FileSystem::GetDefaultHomeDirectory()); } 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 559b123f1..fc6219e1f 100644 --- a/src/duckdb/src/main/extension/extension_helper.cpp +++ b/src/duckdb/src/main/extension/extension_helper.cpp @@ -12,7 +12,7 @@ #include "duckdb/logging/logger.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/database.hpp" -#include "duckdb/main/database_file_opener.hpp" +#include "duckdb/main/database_file_system.hpp" #include "duckdb/main/extension.hpp" #include "duckdb/main/extension_install_info.hpp" #include "duckdb/main/extension_repository_manager.hpp" @@ -283,7 +283,8 @@ static bool PrepareExtensionUpdateInternal(ClientContext &context, DatabaseInsta result.prev_version = parsed_metadata.AppearsValid() ? parsed_metadata.extension_version : ""; - auto extension_install_info = ExtensionInstallInfo::TryReadInfoFile(fs, info_file_path, extension_name); + auto extension_install_info = + ExtensionInstallInfo::TryReadInfoFile(db.GetContext(), fs, info_file_path, extension_name); // Early out: no info file found if (extension_install_info->mode == ExtensionInstallMode::UNKNOWN) { diff --git a/src/duckdb/src/main/extension/extension_install.cpp b/src/duckdb/src/main/extension/extension_install.cpp index 81a206813..a7ce83ebe 100644 --- a/src/duckdb/src/main/extension/extension_install.cpp +++ b/src/duckdb/src/main/extension/extension_install.cpp @@ -4,7 +4,7 @@ #include "duckdb/main/http/http_transport_manager.hpp" #include "duckdb/main/http/http_util.hpp" #include "duckdb/common/local_file_system.hpp" -#include "duckdb/main/database_file_opener.hpp" +#include "duckdb/main/database_file_system.hpp" #include "duckdb/common/serializer/binary_serializer.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/types/uuid.hpp" diff --git a/src/duckdb/src/main/extension/extension_install_dynamic.cpp b/src/duckdb/src/main/extension/extension_install_dynamic.cpp index 339b3c3ca..9f1adac83 100644 --- a/src/duckdb/src/main/extension/extension_install_dynamic.cpp +++ b/src/duckdb/src/main/extension/extension_install_dynamic.cpp @@ -4,7 +4,7 @@ #include "duckdb/main/http/http_transport_manager.hpp" #include "duckdb/main/http/http_util.hpp" #include "duckdb/common/local_file_system.hpp" -#include "duckdb/main/database_file_opener.hpp" +#include "duckdb/main/database_file_system.hpp" #include "duckdb/common/serializer/binary_serializer.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/types/uuid.hpp" @@ -21,16 +21,17 @@ namespace duckdb { -static unsafe_unique_array ReadExtensionFileFromDisk(FileSystem &fs, const string &path, idx_t &file_size) { +static unsafe_unique_array ReadExtensionFileFromDisk(Context &context, FileSystem &fs, const string &path, + idx_t &file_size) { auto source_file = fs.OpenFile(path, FileFlags::FILE_FLAGS_READ); file_size = source_file->GetFileSize(); auto in_buffer = make_unsafe_uniq_array(file_size); - source_file->Read(QueryContext(), in_buffer.get(), file_size, 0); + source_file->Read(context, in_buffer.get(), file_size, 0); source_file->Close(); return in_buffer; } -static void WriteExtensionFileToDisk(QueryContext &query_context, FileSystem &fs, const string &path, void *data, +static void WriteExtensionFileToDisk(Context &query_context, FileSystem &fs, const string &path, void *data, idx_t data_size, DatabaseInstance &db, ExtensionInstallInfo &info) { if (!Settings::Get(db)) { string signature_key_fingerprint; @@ -58,10 +59,11 @@ static void WriteExtensionFileToDisk(QueryContext &query_context, FileSystem &fs target_file.reset(); } -static void WriteExtensionMetadataFileToDisk(FileSystem &fs, const string &path, ExtensionInstallInfo &metadata) { +static void WriteExtensionMetadataFileToDisk(Context &context, FileSystem &fs, const string &path, + ExtensionInstallInfo &metadata) { // the metadata file records which repository the extension came from, and thereby which keys may have signed it, // so it is part of the extension trust domain and reserved from other writers - auto file_writer = BufferedFileWriter(fs, path, + auto file_writer = BufferedFileWriter(fs, context, path, FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE_NEW | FileFlags::FILE_FLAGS_ENABLE_EXTENSION_INSTALL); BinarySerializer::Serialize(metadata, file_writer); @@ -91,7 +93,7 @@ static void CheckExtensionMetadataOnInstall(DatabaseInstance &db, void *in_buffe // 1. Crash after extension removal: extension is now uninstalled, metadata file still present // 2. Crash after metadata removal: extension is now uninstalled, extension dir is clean // 3. Crash after extension move: extension is now uninstalled, new metadata file present -static void WriteExtensionFiles(QueryContext &query_context, FileSystem &fs, const string &temp_path, +static void WriteExtensionFiles(Context &query_context, FileSystem &fs, const string &temp_path, const string &local_extension_path, void *in_buffer, idx_t file_size, ExtensionInstallInfo &info, DatabaseInstance &db) { // temp_path ends with '.duckdb_extension' @@ -115,7 +117,7 @@ static void WriteExtensionFiles(QueryContext &query_context, FileSystem &fs, con // Write metadata to tmp file auto metadata_tmp_path = temp_path + ".info"; auto metadata_file_path = local_extension_path + ".info"; - WriteExtensionMetadataFileToDisk(fs, metadata_tmp_path, info); + WriteExtensionMetadataFileToDisk(db.GetContext(), fs, metadata_tmp_path, info); fs.MoveFile(metadata_tmp_path, metadata_file_path); fs.MoveFile(temp_path, local_extension_path); @@ -164,7 +166,7 @@ static unique_ptr DirectInstallExtension(DatabaseInstance } idx_t file_size; - auto in_buffer = ReadExtensionFileFromDisk(fs, file, file_size); + auto in_buffer = ReadExtensionFileFromDisk(Context::GetOrDatabase(context, db), fs, file, file_size); ExtensionInstallInfo info; @@ -194,7 +196,7 @@ static unique_ptr DirectInstallExtension(DatabaseInstance info.repository_name = options.repository->name; } - QueryContext query_context(context); + Context &query_context = Context::GetOrDatabase(context, db); WriteExtensionFiles(query_context, fs, temp_path, local_extension_path, extension_decompressed, extension_decompressed_size, info, db); @@ -206,12 +208,12 @@ static void VerifyCanDownloadExtension(DatabaseInstance &db, const string &url) if (Settings::Get(db) || ExtensionRepository::IsOfficialRepositoryUrl(url)) { return; } - if (db.config.CanAccessFile(url, FileType::FILE_TYPE_REGULAR)) { + if (db.config.CanAccessFile(db.GetContext(), url, FileType::FILE_TYPE_REGULAR)) { return; } // with httpfs loaded http repositories are bumped to https: allow them if the http url is allowed if (StringUtil::StartsWith(url, "https://") && - db.config.CanAccessFile("http://" + url.substr(8), FileType::FILE_TYPE_REGULAR)) { + db.config.CanAccessFile(db.GetContext(), "http://" + url.substr(8), FileType::FILE_TYPE_REGULAR)) { return; } throw PermissionException("Cannot download extension from \"%s\" - external access is disabled by " @@ -261,8 +263,8 @@ InstallFromHttpUrl(DatabaseInstance &db, const string &url, const string &extens auto &fs = FileSystem::GetLocal(db); if (fs.FileExists(local_extension_path + ".info")) { try { - install_info = - ExtensionInstallInfo::TryReadInfoFile(fs, local_extension_path + ".info", extension_name); + install_info = ExtensionInstallInfo::TryReadInfoFile(db.GetContext(), fs, + local_extension_path + ".info", extension_name); } catch (...) { if (!options.force_install) { // We are going to rewrite the file anyhow, so this is fine @@ -340,7 +342,7 @@ InstallFromHttpUrl(DatabaseInstance &db, const string &url, const string &extens info.full_path = download_url; } - QueryContext query_context(context); + Context &query_context = Context::GetOrDatabase(context, db); auto &fs = FileSystem::GetLocal(db); WriteExtensionFiles(query_context, fs, temp_path, local_extension_path, extension_data, extension_size, info, db); @@ -379,10 +381,11 @@ static unique_ptr InstallFromRepository(DatabaseInstance & context); } -static void ThrowErrorOnMismatchingExtensionOrigin(FileSystem &fs, const string &local_extension_path, +static void ThrowErrorOnMismatchingExtensionOrigin(Context &context, FileSystem &fs, const string &local_extension_path, const string &extension_name, const string &extension, optional_ptr repository) { - auto install_info = ExtensionInstallInfo::TryReadInfoFile(fs, local_extension_path + ".info", extension_name); + auto install_info = + ExtensionInstallInfo::TryReadInfoFile(context, fs, local_extension_path + ".info", extension_name); string format_string = "Installing extension '%s' failed. The extension is already installed " "but the origin is different.\n" @@ -447,7 +450,7 @@ unique_ptr InstallExternalExtension(DatabaseInstance &db, // File exists: throw error if origin mismatches if (options.throw_on_origin_mismatch && !Settings::Get(db) && fs.FileExists(local_extension_path + ".info")) { - ThrowErrorOnMismatchingExtensionOrigin(fs, local_extension_path, extension_name, extension, + ThrowErrorOnMismatchingExtensionOrigin(db.GetContext(), fs, local_extension_path, extension_name, extension, options.repository); } diff --git a/src/duckdb/src/main/extension/extension_load.cpp b/src/duckdb/src/main/extension/extension_load.cpp index f2262ba83..b6e096280 100644 --- a/src/duckdb/src/main/extension/extension_load.cpp +++ b/src/duckdb/src/main/extension/extension_load.cpp @@ -680,7 +680,8 @@ bool ExtensionHelper::TryInitialLoad(DatabaseInstance &db, FileSystem &fs, const // Extensions that are loaded directly have no install info: those are verified against the core keys unique_ptr install_info; if (!direct_load) { - install_info = ExtensionInstallInfo::TryReadInfoFile(fs, filename + ".info", lowercase_extension_name); + install_info = + ExtensionInstallInfo::TryReadInfoFile(db.GetContext(), fs, filename + ".info", lowercase_extension_name); } // a load with an explicit FROM (LOAD x FROM core, LOAD x FROM myrepo) asserts that the extension really came from diff --git a/src/duckdb/src/main/extension/extension_repository_manager.cpp b/src/duckdb/src/main/extension/extension_repository_manager.cpp index 477e8a622..60b5942e9 100644 --- a/src/duckdb/src/main/extension/extension_repository_manager.cpp +++ b/src/duckdb/src/main/extension/extension_repository_manager.cpp @@ -890,7 +890,7 @@ ExtensionRepository ExtensionRepositoryManager::CreateRepository(DatabaseInstanc auto temp_path = file_path + ".tmp-" + UUID::ToString(UUID::GenerateRandomUUID()); fs.TryRemoveFile(temp_path); { - auto file_writer = BufferedFileWriter(fs, temp_path, + auto file_writer = BufferedFileWriter(fs, db.GetContext(), temp_path, FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE_NEW | FileFlags::FILE_FLAGS_ENABLE_EXTENSION_INSTALL); file_writer.WriteData(const_data_ptr_cast(contents.c_str()), contents.size()); diff --git a/src/duckdb/src/main/extension_install_info.cpp b/src/duckdb/src/main/extension_install_info.cpp index 62a1a26c7..c9ed48cbb 100644 --- a/src/duckdb/src/main/extension_install_info.cpp +++ b/src/duckdb/src/main/extension_install_info.cpp @@ -143,7 +143,7 @@ string ExtensionRepository::ToReadableString() { return path; } -unique_ptr ExtensionInstallInfo::TryReadInfoFile(FileSystem &fs, +unique_ptr ExtensionInstallInfo::TryReadInfoFile(Context &context, FileSystem &fs, const std::string &info_file_path, const std::string &extension_name) { unique_ptr result; diff --git a/src/duckdb/src/main/http/http_transport_manager.cpp b/src/duckdb/src/main/http/http_transport_manager.cpp index 695b3b6d8..9117aac76 100644 --- a/src/duckdb/src/main/http/http_transport_manager.cpp +++ b/src/duckdb/src/main/http/http_transport_manager.cpp @@ -1,7 +1,7 @@ #include "duckdb/main/http/http_transport_manager.hpp" +#include "duckdb/main/http/http_transport_manager_state.hpp" #include "duckdb/common/exception.hpp" -#include "duckdb/common/file_opener.hpp" #include "duckdb/common/limits.hpp" #include "duckdb/main/config.hpp" #include "duckdb/main/database.hpp" @@ -11,25 +11,6 @@ namespace duckdb { static constexpr idx_t HTTP_TRANSPORT_MAX_CAPACITY = 256; -class HTTPTransportManagerState { -public: - HTTPTransportManagerState(shared_ptr http_util_p, HTTPTransportReusePolicy reuse_policy_p, - idx_t provider_epoch_p) - : http_util(std::move(http_util_p)), reuse_policy(reuse_policy_p), provider_epoch(provider_epoch_p) { - } - - //! Provider retained for this publication. - const shared_ptr http_util; - //! Client reuse contract reported by the provider. - const HTTPTransportReusePolicy reuse_policy; - //! Stable manager-issued provider identity. - const idx_t provider_epoch; - //! Current connection generation for explicit invalidation. - uint64_t connection_epoch = 0; - //! Whether epoch exhaustion permanently disabled reuse. - bool reuse_poisoned = false; -}; - class HTTPTransportCapacityGuard; class HTTPTransportCapacityGuard { @@ -339,14 +320,10 @@ HTTPTransportManager::Session HTTPTransportManager::CreateSession(ClientContext return FinishSession(reservation, reservation.state->http_util->InitializeParameters(context, path)); } -HTTPTransportManager::Session HTTPTransportManager::CreateSession(optional_ptr opener, - optional_ptr info) { - auto opener_db = FileOpener::TryGetDatabase(opener); - if (opener_db) { - ValidateDatabase(*opener_db); - } +HTTPTransportManager::Session HTTPTransportManager::CreateSession(Context &context, optional_ptr info) { + ValidateDatabase(context.GetDatabase()); auto reservation = ReserveSession(); - return FinishSession(reservation, reservation.state->http_util->InitializeParameters(opener, info)); + return FinishSession(reservation, reservation.state->http_util->InitializeParameters(context, info)); } void HTTPTransportManager::SetHTTPUtil(const shared_ptr &new_http_util) { diff --git a/src/duckdb/src/main/http/http_util.cpp b/src/duckdb/src/main/http/http_util.cpp index 90c4c8ae1..f7cad5167 100644 --- a/src/duckdb/src/main/http/http_util.cpp +++ b/src/duckdb/src/main/http/http_util.cpp @@ -6,11 +6,11 @@ #include "duckdb/common/operator/cast_operators.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/main/client_context.hpp" -#include "duckdb/main/client_context_file_opener.hpp" #include "duckdb/main/client_data.hpp" #include "duckdb/main/database.hpp" -#include "duckdb/main/database_file_opener.hpp" +#include "duckdb/main/database_file_system.hpp" #include "duckdb/main/http/http_util.hpp" +#include "duckdb/common/file_lookup_info.hpp" #include "duckdb/main/http/http_retry_budget.hpp" #include "duckdb/main/settings.hpp" @@ -208,7 +208,8 @@ unique_ptr HTTPUtil::Request(BaseRequest &request, unique_ptrconfig; auto &access_path = request.params.access_path.empty() ? request.url : request.params.access_path; - if (!config.CanAccessFile(access_path, FileType::FILE_TYPE_REGULAR)) { + auto &services = request.params.db->GetContext(); + if (!config.CanAccessFile(services, access_path, FileType::FILE_TYPE_REGULAR)) { throw PermissionException("Cannot access \"%s\" - file system operations are disabled by configuration", access_path); } @@ -587,50 +588,40 @@ HTTPUtil::RunRequestWithRetry(const std::function(void) throw IOException("%s error for HTTP %s to '%s'%s", error, method, request.url, quota_note); } -void HTTPParams::Initialize(optional_ptr opener) { - db = FileOpener::TryGetDatabase(opener); - if (db) { - auto http_proxy_setting = Settings::Get(db->config); - if (!http_proxy_setting.empty()) { - idx_t port; - string host; - HTTPUtil::ParseHTTPProxyHost(http_proxy_setting, host, port); - http_proxy = host; - http_proxy_port = port; - } - http_proxy_username = Settings::Get(*db); - http_proxy_password = Settings::Get(*db); - retry_quota_throttled = Settings::Get(*db); - retry_throttled_wait_ms = Settings::Get(*db); +void HTTPParams::Initialize(Context &context) { + db = &context.GetDatabase(); + auto http_proxy_setting = Settings::Get(db->config); + if (!http_proxy_setting.empty()) { + idx_t port; + string host; + HTTPUtil::ParseHTTPProxyHost(http_proxy_setting, host, port); + http_proxy = host; + http_proxy_port = port; } + http_proxy_username = Settings::Get(*db); + http_proxy_password = Settings::Get(*db); - auto context = FileOpener::TryGetContext(opener); - if (context && context->IsClient()) { - logger = context->GetLoggerPtr(); - } - if (context) { - // A session's own value wins over the database's - retry_quota_throttled = Settings::Get(*context); - retry_throttled_wait_ms = Settings::Get(*context); + if (context.IsClient()) { + logger = context.GetLoggerPtr(); } + // a session's own value wins over the database's + retry_quota_throttled = Settings::Get(context); + retry_throttled_wait_ms = Settings::Get(context); } unique_ptr HTTPUtil::InitializeParameters(DatabaseInstance &db, const string &url) { - DatabaseFileOpener opener(db); - FileOpenerInfo info(url); - return InitializeParameters(&opener, &info); + FileLookupInfo info(url); + return InitializeParameters(db.GetContext(), &info); } unique_ptr HTTPUtil::InitializeParameters(ClientContext &context, const string &url) { - ClientContextFileOpener opener(context.GetContext()); - FileOpenerInfo info(url); - return InitializeParameters(&opener, &info); + FileLookupInfo info(url); + return InitializeParameters(context.GetContext(), &info); } -unique_ptr HTTPUtil::InitializeParameters(optional_ptr opener, - optional_ptr info) { +unique_ptr HTTPUtil::InitializeParameters(Context &context, optional_ptr info) { auto result = make_uniq(*this); - result->Initialize(opener); + result->Initialize(context); return result; } diff --git a/src/duckdb/src/main/secret/secret.cpp b/src/duckdb/src/main/secret/secret.cpp index 2bda1d123..fea6216b2 100644 --- a/src/duckdb/src/main/secret/secret.cpp +++ b/src/duckdb/src/main/secret/secret.cpp @@ -1,7 +1,7 @@ #include "duckdb/main/secret/secret.hpp" +#include "duckdb/common/file_lookup_info.hpp" #include "duckdb/common/case_insensitive_map.hpp" -#include "duckdb/common/file_opener.hpp" #include "duckdb/common/pair.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/secret/secret_manager.hpp" @@ -182,9 +182,9 @@ KeyValueSecretReader::KeyValueSecretReader(ClientContext &context_p, const char : KeyValueSecretReader(context_p, &secret_type, 1, std::move(path)) { } -KeyValueSecretReader::KeyValueSecretReader(FileOpener &opener_p, optional_ptr info, +KeyValueSecretReader::KeyValueSecretReader(Context &context_p, optional_ptr info, const char *secret_type) - : KeyValueSecretReader(opener_p, info, &secret_type, 1) { + : KeyValueSecretReader(context_p, info, &secret_type, 1) { } void KeyValueSecretReader::Initialize(const char **secret_types, idx_t secret_types_len) { @@ -211,15 +211,15 @@ void KeyValueSecretReader::Initialize(const char **secret_types, idx_t secret_ty } } -KeyValueSecretReader::KeyValueSecretReader(const KeyValueSecret &secret_p, FileOpener &opener_p) : secret(secret_p) { - db = opener_p.TryGetDatabase(); - context = &opener_p.TryGetContext(); +KeyValueSecretReader::KeyValueSecretReader(const KeyValueSecret &secret_p, Context &context_p) : secret(secret_p) { + db = &context_p.GetDatabase(); + context = &context_p; } -KeyValueSecretReader::KeyValueSecretReader(FileOpener &opener_p, optional_ptr info, +KeyValueSecretReader::KeyValueSecretReader(Context &context_p, optional_ptr info, const char **secret_types, idx_t secret_types_len) { - db = opener_p.TryGetDatabase(); - context = &opener_p.TryGetContext(); + db = &context_p.GetDatabase(); + context = &context_p; if (info) { path = info->file.path; diff --git a/src/duckdb/src/main/secret/secret_manager.cpp b/src/duckdb/src/main/secret/secret_manager.cpp index f401c5cf7..8eac569b4 100644 --- a/src/duckdb/src/main/secret/secret_manager.cpp +++ b/src/duckdb/src/main/secret/secret_manager.cpp @@ -4,7 +4,7 @@ #include "duckdb/catalog/catalog_entry.hpp" #include "duckdb/common/common.hpp" #include "duckdb/common/file_system.hpp" -#include "duckdb/main/database_file_opener.hpp" +#include "duckdb/main/database_file_system.hpp" #include "duckdb/common/local_file_system.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/serializer/binary_deserializer.hpp" @@ -838,7 +838,7 @@ unique_ptr DefaultSecretGenerator::CreateDefaultEntryInternal(cons try { auto file_reader = BufferedFileReader(fs, secret_path.c_str()); - if (!LocalFileSystem::IsPrivateFile(secret_path, nullptr)) { + if (!LocalFileSystem::IsPrivateFile(secret_path)) { throw IOException( "The secret file '%s' has incorrect permissions! Please set correct permissions or remove file", secret_path); diff --git a/src/duckdb/src/main/secret/secret_storage.cpp b/src/duckdb/src/main/secret/secret_storage.cpp index 7db38640e..e4cccbc12 100644 --- a/src/duckdb/src/main/secret/secret_storage.cpp +++ b/src/duckdb/src/main/secret/secret_storage.cpp @@ -2,7 +2,7 @@ #include "duckdb/common/multi_file/multi_file_list.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/local_file_system.hpp" -#include "duckdb/main/database_file_opener.hpp" +#include "duckdb/main/database_file_system.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/serializer/binary_deserializer.hpp" #include "duckdb/common/serializer/binary_serializer.hpp" @@ -252,7 +252,7 @@ bool PersistentSecretFiles::TryGetOtherSecretAt(const string &path, const Identi } //! Reads the name that is stored in a secret file, without loading the secret -static bool TryReadSecretName(FileSystem &fs, const string &path, string &name) { +static bool TryReadSecretName(Context &context, FileSystem &fs, const string &path, string &name) { try { BufferedFileReader reader(fs, path.c_str()); if (reader.Finished()) { @@ -272,7 +272,7 @@ static bool TryReadSecretName(FileSystem &fs, const string &path, string &name) LocalFileSecretStorage::LocalFileSecretStorage(SecretManager &manager, DatabaseInstance &db_p, const string &name_p, const string &secret_path_p) : CatalogSetSecretStorage(db_p, name_p, LOCAL_FILE_STORAGE_OFFSET), files(make_shared_ptr()), - secret_path(FileSystem::ExpandPath(secret_path_p, nullptr)) { + secret_path(FileSystem::ExpandPathWithHome(secret_path_p, FileSystem::GetDefaultHomeDirectory())) { persistent = true; // Check existence of persistent secret dir @@ -288,7 +288,7 @@ LocalFileSecretStorage::LocalFileSecretStorage(SecretManager &manager, DatabaseI if (secret_name != file_stem) { // the file is either the escaped file of a secret, or a file written before names were // escaped that is named after a secret that looks escaped: the file tells which - TryReadSecretName(fs, full_path, secret_name); + TryReadSecretName(db.GetContext(), fs, full_path, secret_name); } persistent_secrets.insert(Identifier(secret_name)); files->Set(Identifier(secret_name), full_path); @@ -321,14 +321,14 @@ CatalogTransaction CatalogSetSecretStorage::GetTransactionOrDefault(optional_ptr return CatalogTransaction::GetSystemTransaction(db); } -static void WriteSecretFileToDisk(FileSystem &fs, const string &path, const BaseSecret &secret) { +static void WriteSecretFileToDisk(Context &context, FileSystem &fs, const string &path, const BaseSecret &secret) { auto open_flags = FileFlags::FILE_FLAGS_WRITE; // Ensure we are writing to a private file with 600 permission open_flags |= FileFlags::FILE_FLAGS_PRIVATE; // Create the file, which must not exist yet open_flags |= FileFlags::FILE_FLAGS_FILE_CREATE_NEW; - auto file_writer = BufferedFileWriter(fs, path, open_flags); + auto file_writer = BufferedFileWriter(fs, context, path, open_flags); auto serializer = BinarySerializer(file_writer); serializer.Begin(); @@ -421,7 +421,7 @@ void LocalFileSecretStorage::WriteSecret(const BaseSecret &secret, OnCreateConfl // the complete file is renamed over the secret's file in one step, so a crash leaves the old file or the new one try { - WriteSecretFileToDisk(fs, temp_path, secret); + WriteSecretFileToDisk(db.GetContext(), fs, temp_path, secret); fs.MoveFile(temp_path, file_path); } catch (...) { // the secret is not stored, so the temporary file goes, and its error cannot replace the one being reported diff --git a/src/duckdb/src/main/settings/custom_settings.cpp b/src/duckdb/src/main/settings/custom_settings.cpp index 8a47eaea1..233815cf2 100644 --- a/src/duckdb/src/main/settings/custom_settings.cpp +++ b/src/duckdb/src/main/settings/custom_settings.cpp @@ -307,7 +307,7 @@ void AllowedDirectoriesSetting::SetGlobal(DatabaseInstance *db, DBConfig &config for (auto &val : ListValue::GetChildren(input)) { directories.push_back(val.GetValue()); } - config.SetAllowedDirectories(directories); + config.SetAllowedDirectories(db->GetContext(), directories); } void AllowedDirectoriesSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { @@ -344,7 +344,7 @@ void AllowedPathsSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, cons for (auto &val : ListValue::GetChildren(input)) { paths.push_back(val.GetValue()); } - config.SetAllowedPaths(paths); + config.SetAllowedPaths(db->GetContext(), paths); } void AllowedPathsSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { @@ -734,20 +734,21 @@ void EnableExternalAccessSetting::OnSet(SettingCallbackInfo &info, Value &input) throw InvalidInputException("Cannot enable external access while database is running"); } auto &config = info.config; + auto &services = info.db->GetContext(); if (info.db && Settings::Get(*info.db)) { // we are turning off external access - add any already attached databases to the list of accepted paths auto &db_manager = DatabaseManager::Get(*info.db); auto attached_paths = db_manager.GetAttachedDatabasePaths(); for (auto &path : attached_paths) { - config.AddAllowedPath(path); - config.AddAllowedPath(path + ".wal"); - config.AddAllowedPath(path + ".wal.checkpoint"); - config.AddAllowedPath(path + ".wal.recovery"); + config.AddAllowedPath(services, path); + config.AddAllowedPath(services, path + ".wal"); + config.AddAllowedPath(services, path + ".wal.checkpoint"); + config.AddAllowedPath(services, path + ".wal.recovery"); } } if (config.options.use_temporary_directory && !config.options.temporary_directory.empty()) { // if temp directory is enabled we can also write there - config.AddAllowedDirectory(config.options.temporary_directory); + config.AddAllowedDirectory(services, config.options.temporary_directory); } } @@ -1246,8 +1247,9 @@ void LogQueryPathSetting::OnSet(SettingCallbackInfo &info, Value &input) { // empty path: clean up query writer client_data.log_query_writer = nullptr; } else { - client_data.log_query_writer = make_uniq(FileSystem::GetFileSystem(*info.context), path, - BufferedFileWriter::DEFAULT_OPEN_FLAGS); + client_data.log_query_writer = + make_uniq(FileSystem::GetFileSystem(*info.context), info.context->GetContext(), path, + BufferedFileWriter::DEFAULT_OPEN_FLAGS); } } diff --git a/src/duckdb/src/storage/block_allocator.cpp b/src/duckdb/src/storage/block_allocator.cpp index bbb60a348..d1417c449 100644 --- a/src/duckdb/src/storage/block_allocator.cpp +++ b/src/duckdb/src/storage/block_allocator.cpp @@ -517,6 +517,18 @@ class BlockAllocatorThreadLocalState { static thread_local bool thread_local_state_created = false; // NOLINT //! The state of the worker thread running on this thread, if any. A pointer needs no thread_local destructor either static thread_local BlockAllocatorThreadLocalState *worker_local_state = nullptr; // NOLINT + +//! Clears thread_local_state_created when the state is destroyed, e.g. before static destructors run at exit +struct BlockAllocatorThreadLocalStateHolder { + explicit BlockAllocatorThreadLocalStateHolder(const BlockAllocator &block_allocator) : state(block_allocator) { + thread_local_state_created = true; + } + ~BlockAllocatorThreadLocalStateHolder() { + thread_local_state_created = false; + } + + BlockAllocatorThreadLocalState state; +}; #endif BlockAllocatorWorkerState::BlockAllocatorWorkerState() { @@ -554,10 +566,9 @@ BlockAllocatorThreadLocalState &GetBlockAllocatorThreadLocalState(const BlockAll worker_local_state->TryInitialize(block_allocator); return *worker_local_state; } - thread_local BlockAllocatorThreadLocalState local_state(block_allocator); - thread_local_state_created = true; - local_state.TryInitialize(block_allocator); - return local_state; + thread_local BlockAllocatorThreadLocalStateHolder local_state(block_allocator); + local_state.state.TryInitialize(block_allocator); + return local_state.state; #endif } diff --git a/src/duckdb/src/storage/buffer/block_handle.cpp b/src/duckdb/src/storage/buffer/block_handle.cpp index 973483870..118f4b363 100644 --- a/src/duckdb/src/storage/buffer/block_handle.cpp +++ b/src/duckdb/src/storage/buffer/block_handle.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/database.hpp" #include "duckdb/storage/buffer/block_handle.hpp" #include "duckdb/common/file_buffer.hpp" @@ -120,7 +121,7 @@ CanUnloadResult BlockMemory::CanUnload() const { return CanUnloadResult::CAN_UNLOAD; } -unique_ptr BlockMemory::UnloadAndTakeBlock(BlockLock &l, QueryContext context) { +unique_ptr BlockMemory::UnloadAndTakeBlock(BlockLock &l, Context &context) { VerifyMutex(l); if (GetState() == BlockState::BLOCK_UNLOADED) { @@ -139,7 +140,15 @@ unique_ptr BlockMemory::UnloadAndTakeBlock(BlockLock &l, QueryContex return std::move(GetBuffer()); } -void BlockMemory::Unload(BlockLock &l, QueryContext context) { +void BlockMemory::Unload(BlockLock &l) { + Unload(l, buffer_manager.GetDatabase().GetContext()); +} + +unique_ptr BlockMemory::UnloadAndTakeBlock(BlockLock &l) { + return UnloadAndTakeBlock(l, buffer_manager.GetDatabase().GetContext()); +} + +void BlockMemory::Unload(BlockLock &l, Context &context) { auto block = UnloadAndTakeBlock(l, context); block.reset(); } @@ -211,7 +220,7 @@ BufferHandle BlockHandle::LoadFromBuffer(BlockLock &l, data_ptr_t data, unique_p return BufferHandle(shared_from_this(), memory.GetBuffer()); } -BufferHandle BlockHandle::Load(BlockLock &l, QueryContext context, unique_ptr reusable_buffer) { +BufferHandle BlockHandle::Load(BlockLock &l, Context &context, unique_ptr reusable_buffer) { memory.VerifyMutex(l); if (memory.GetState() == BlockState::BLOCK_LOADED) { // The block has already been loaded. diff --git a/src/duckdb/src/storage/buffer/block_manager.cpp b/src/duckdb/src/storage/buffer/block_manager.cpp index 25b49a69f..6d78b0341 100644 --- a/src/duckdb/src/storage/buffer/block_manager.cpp +++ b/src/duckdb/src/storage/buffer/block_manager.cpp @@ -57,7 +57,7 @@ shared_ptr BlockManager::RegisterBlock(block_id_t block_id, MemoryT return result; } -shared_ptr BlockManager::ConvertToPersistent(QueryContext context, block_id_t block_id, +shared_ptr BlockManager::ConvertToPersistent(Context &context, block_id_t block_id, shared_ptr old_block, BufferHandle old_handle, ConvertToPersistentMode mode, optional tag) { auto default_tag = old_block->GetMemory().GetMemoryTag(); @@ -123,7 +123,7 @@ shared_ptr BlockManager::ConvertToPersistent(QueryContext context, return new_block; } -shared_ptr BlockManager::ConvertToPersistent(QueryContext context, block_id_t block_id, +shared_ptr BlockManager::ConvertToPersistent(Context &context, block_id_t block_id, shared_ptr old_block, ConvertToPersistentMode mode, optional tag) { // pin the old block to ensure we have it loaded in memory @@ -167,7 +167,7 @@ MetadataManager &BlockManager::GetMetadataManager() { return *metadata_manager; } -void BlockManager::Write(QueryContext context, FileBuffer &block, block_id_t block_id) { +void BlockManager::Write(Context &context, FileBuffer &block, block_id_t block_id) { // Fallback to the old Write. Write(block, block_id); } diff --git a/src/duckdb/src/storage/buffer/buffer_pool.cpp b/src/duckdb/src/storage/buffer/buffer_pool.cpp index 1c717703e..4134bdb97 100644 --- a/src/duckdb/src/storage/buffer/buffer_pool.cpp +++ b/src/duckdb/src/storage/buffer/buffer_pool.cpp @@ -416,7 +416,7 @@ void BufferPool::FlushForAllocation(const idx_t extra_memory, const idx_t memory } } -BufferPool::EvictionResult BufferPool::EvictBlocks(QueryContext context, MemoryTag tag, idx_t extra_memory, +BufferPool::EvictionResult BufferPool::EvictBlocks(Context &context, MemoryTag tag, idx_t extra_memory, idx_t memory_limit, unique_ptr *buffer) { for (auto &queue : queues) { auto block_result = EvictBlocksInternal(context, *queue, tag, extra_memory, memory_limit, buffer); @@ -430,7 +430,7 @@ BufferPool::EvictionResult BufferPool::EvictBlocks(QueryContext context, MemoryT return EvictObjectCacheEntries(tag, extra_memory, memory_limit); } -BufferPool::EvictionResult BufferPool::EvictBlocksInternal(QueryContext context, EvictionQueue &queue, MemoryTag tag, +BufferPool::EvictionResult BufferPool::EvictBlocksInternal(Context &context, EvictionQueue &queue, MemoryTag tag, idx_t extra_memory, idx_t memory_limit, unique_ptr *buffer) { TempBufferPoolReservation r(tag, *this, extra_memory); @@ -580,10 +580,10 @@ void BufferPool::PurgeQueue(const BlockHandle &block) { eviction_queue.Purge(); } -void BufferPool::SetLimit(idx_t limit, const char *exception_postscript) { +void BufferPool::SetLimit(Context &context, idx_t limit, const char *exception_postscript) { lock_guard l_lock(limit_lock); // try to evict until the limit is reached - if (!EvictBlocks(QueryContext(), MemoryTag::EXTENSION, 0, limit).success) { + if (!EvictBlocks(context, MemoryTag::EXTENSION, 0, limit).success) { throw OutOfMemoryException( "Failed to change memory limit to %lld: could not free up enough memory for the new limit%s", limit, exception_postscript); @@ -592,7 +592,7 @@ void BufferPool::SetLimit(idx_t limit, const char *exception_postscript) { // set the global maximum memory to the new limit if successful maximum_memory = limit; // evict again - if (!EvictBlocks(QueryContext(), MemoryTag::EXTENSION, 0, limit).success) { + if (!EvictBlocks(context, MemoryTag::EXTENSION, 0, limit).success) { // failed: go back to old limit maximum_memory = old_limit; throw OutOfMemoryException( diff --git a/src/duckdb/src/storage/buffer_manager.cpp b/src/duckdb/src/storage/buffer_manager.cpp index 181cb0f68..1d4de862d 100644 --- a/src/duckdb/src/storage/buffer_manager.cpp +++ b/src/duckdb/src/storage/buffer_manager.cpp @@ -109,26 +109,25 @@ void BufferManager::AddToEvictionQueue(shared_ptr &handle) { throw NotImplementedException("This type of BufferManager does not support 'AddToEvictionQueue"); } -BufferHandle BufferManager::Allocate(QueryContext context, MemoryTag tag, idx_t block_size, bool can_destroy) { +BufferHandle BufferManager::Allocate(Context &context, MemoryTag tag, idx_t block_size, bool can_destroy) { return Allocate(tag, block_size, can_destroy); } -BufferHandle BufferManager::Allocate(QueryContext context, MemoryTag tag, BlockManager *block_manager, - bool can_destroy) { +BufferHandle BufferManager::Allocate(Context &context, MemoryTag tag, BlockManager *block_manager, bool can_destroy) { return Allocate(tag, block_manager, can_destroy); } -vector> BufferManager::CreatePrefetchTasks(QueryContext context, +vector> BufferManager::CreatePrefetchTasks(Context &context, vector> &handles) { Prefetch(context, handles); return vector>(); } -void BufferManager::WriteTemporaryBuffer(QueryContext context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer) { +void BufferManager::WriteTemporaryBuffer(Context &context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer) { throw NotImplementedException("This type of BufferManager does not support 'WriteTemporaryBuffer"); } -unique_ptr BufferManager::ReadTemporaryBuffer(QueryContext context, MemoryTag tag, BlockHandle &block, +unique_ptr BufferManager::ReadTemporaryBuffer(Context &context, MemoryTag tag, BlockHandle &block, unique_ptr buffer) { throw NotImplementedException("This type of BufferManager does not support 'ReadTemporaryBuffer"); } diff --git a/src/duckdb/src/storage/checkpoint/write_overflow_strings_to_disk.cpp b/src/duckdb/src/storage/checkpoint/write_overflow_strings_to_disk.cpp index d732182bf..ed5e94630 100644 --- a/src/duckdb/src/storage/checkpoint/write_overflow_strings_to_disk.cpp +++ b/src/duckdb/src/storage/checkpoint/write_overflow_strings_to_disk.cpp @@ -129,7 +129,7 @@ void WriteOverflowStringsToDisk::Flush() { } // write to disk auto &block_manager = partial_block_manager.GetBlockManager(); - block_manager.Write(QueryContext(context), handle.GetFileBuffer(), block_id); + block_manager.Write(context, handle.GetFileBuffer(), block_id); } block_id = INVALID_BLOCK; offset = 0; diff --git a/src/duckdb/src/storage/checkpoint_manager.cpp b/src/duckdb/src/storage/checkpoint_manager.cpp index 0d070b48e..ecf3cdbd8 100644 --- a/src/duckdb/src/storage/checkpoint_manager.cpp +++ b/src/duckdb/src/storage/checkpoint_manager.cpp @@ -94,10 +94,9 @@ void ActiveCheckpointWrapper::Commit() { checkpoint_transaction = nullptr; } -CheckpointWriter::CheckpointWriter(AttachedDatabase &db_p, QueryContext query_context, +CheckpointWriter::CheckpointWriter(AttachedDatabase &db_p, Context &context_p, optional_ptr checkpoint_context_p) - : db(db_p), context(query_context.Valid() ? *query_context.GetContext() : db_p.GetDatabase().GetContext()), - checkpoint_context(checkpoint_context_p) { + : db(db_p), context(context_p), checkpoint_context(checkpoint_context_p) { } CheckpointWriter::~CheckpointWriter() { @@ -105,7 +104,7 @@ CheckpointWriter::~CheckpointWriter() { void ReorderTableEntries(catalog_entry_vector_t &tables); -SingleFileCheckpointWriter::SingleFileCheckpointWriter(QueryContext context, AttachedDatabase &db, +SingleFileCheckpointWriter::SingleFileCheckpointWriter(Context &context, AttachedDatabase &db, BlockManager &block_manager, CheckpointOptions options_p, optional_ptr checkpoint_context) : CheckpointWriter(db, context, checkpoint_context), @@ -338,8 +337,7 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { header.vector_size = STANDARD_VECTOR_SIZE; transaction_t read_stamp, lowest_active_start; transaction_manager.GetStartTimes(read_stamp, lowest_active_start); - block_manager.WriteHeader(QueryContext(GetContext()), header, options.visibility_bound, read_stamp, - lowest_active_start); + block_manager.WriteHeader(GetContext(), header, options.visibility_bound, read_stamp, lowest_active_start); auto debug_verify_blocks = Settings::Get(db.GetDatabase()); if (debug_verify_blocks) { @@ -355,7 +353,7 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { } auto &table = entry.Cast(); auto &storage = table.GetStorage(); - auto segment_info = storage.GetColumnSegmentInfo(QueryContext(GetContext())); + auto segment_info = storage.GetColumnSegmentInfo(GetContext()); for (auto &segment : segment_info) { verify_block_usage_count[segment.block_id]++; if (StringUtil::Contains(segment.segment_info, "Overflow String Block Ids: ")) { @@ -445,8 +443,8 @@ void SingleFileCheckpointReader::LoadFromStorage() { if (block_manager.Prefetch()) { auto metadata_blocks = metadata_manager.GetBlocks(); auto &buffer_manager = BufferManager::GetBufferManager(storage.GetDatabase()); - // Database load happens before any query is running, so there is no query context to attribute to. - buffer_manager.Prefetch(QueryContext(), metadata_blocks); + // Database load happens before any query is running, so the database-wide context is used. + buffer_manager.Prefetch(storage.GetDatabase().GetContext(), metadata_blocks); } // create the MetadataReader to read from the storage diff --git a/src/duckdb/src/storage/compression/bitpacking.cpp b/src/duckdb/src/storage/compression/bitpacking.cpp index de516c1e3..174542d34 100644 --- a/src/duckdb/src/storage/compression/bitpacking.cpp +++ b/src/duckdb/src/storage/compression/bitpacking.cpp @@ -1114,7 +1114,7 @@ struct BitpackingScanState : public SegmentScanState { }; template -unique_ptr BitpackingInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr BitpackingInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); auto result = make_uniq>(std::move(handle), segment); @@ -1446,7 +1446,7 @@ void BitpackingSkip(ColumnSegment &segment, ColumnScanState &state, idx_t skip_c // GetSegmentInfo //===--------------------------------------------------------------------===// template -InsertionOrderPreservingMap BitpackingGetSegmentInfo(QueryContext context, ColumnSegment &segment) { +InsertionOrderPreservingMap BitpackingGetSegmentInfo(Context &context, ColumnSegment &segment) { map counts; auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); diff --git a/src/duckdb/src/storage/compression/dict_fsst.cpp b/src/duckdb/src/storage/compression/dict_fsst.cpp index 22dd2dc21..b7a53f61d 100644 --- a/src/duckdb/src/storage/compression/dict_fsst.cpp +++ b/src/duckdb/src/storage/compression/dict_fsst.cpp @@ -61,7 +61,7 @@ struct DictFSSTCompressionStorage { static void Compress(CompressionState &state_p, const Vector &scan_vector); static void FinalizeCompress(CompressionState &state_p); - static unique_ptr StringInitScan(const QueryContext &context, ColumnSegment &segment); + static unique_ptr StringInitScan(Context &context, ColumnSegment &segment); template static void StringScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset); @@ -113,8 +113,7 @@ void DictFSSTCompressionStorage::FinalizeCompress(CompressionState &state_p) { //===--------------------------------------------------------------------===// // Scan //===--------------------------------------------------------------------===// -unique_ptr DictFSSTCompressionStorage::StringInitScan(const QueryContext &context, - ColumnSegment &segment) { +unique_ptr DictFSSTCompressionStorage::StringInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto state = make_uniq(segment, buffer_manager.Pin(segment.GetBlockHandle())); state->Initialize(); @@ -262,7 +261,7 @@ static string DictFSSTModeToString(const DictFSSTMode mode) { //===--------------------------------------------------------------------===// // GetSegmentInfo //===--------------------------------------------------------------------===// -static InsertionOrderPreservingMap DictFSSTGetSegmentInfo(QueryContext, ColumnSegment &segment) { +static InsertionOrderPreservingMap DictFSSTGetSegmentInfo(Context &, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto state = make_uniq(segment, buffer_manager.Pin(segment.GetBlockHandle())); state->Initialize(); diff --git a/src/duckdb/src/storage/compression/dictionary_compression.cpp b/src/duckdb/src/storage/compression/dictionary_compression.cpp index 40bf602f3..951e7a8f6 100644 --- a/src/duckdb/src/storage/compression/dictionary_compression.cpp +++ b/src/duckdb/src/storage/compression/dictionary_compression.cpp @@ -56,7 +56,7 @@ struct DictionaryCompressionStorage { static void Compress(CompressionState &state_p, const Vector &scan_vector); static void FinalizeCompress(CompressionState &state_p); - static unique_ptr StringInitScan(const QueryContext &context, ColumnSegment &segment); + static unique_ptr StringInitScan(Context &context, ColumnSegment &segment); template static void StringScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset); @@ -118,8 +118,7 @@ void DictionaryCompressionStorage::FinalizeCompress(CompressionState &state_p) { //===--------------------------------------------------------------------===// // Scan //===--------------------------------------------------------------------===// -unique_ptr DictionaryCompressionStorage::StringInitScan(const QueryContext &context, - ColumnSegment &segment) { +unique_ptr DictionaryCompressionStorage::StringInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); return make_uniq(buffer_manager.Pin(context, segment.GetBlockHandle()), segment); } diff --git a/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp b/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp index 33e2f4160..58e4551dc 100644 --- a/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp +++ b/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp @@ -154,7 +154,7 @@ struct FixedSizeScanState : public SegmentScanState { CompressionSegmentReader reader; }; -unique_ptr FixedSizeInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr FixedSizeInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); return make_uniq(std::move(handle), segment); diff --git a/src/duckdb/src/storage/compression/fsst.cpp b/src/duckdb/src/storage/compression/fsst.cpp index 75b2de909..caf96c2da 100644 --- a/src/duckdb/src/storage/compression/fsst.cpp +++ b/src/duckdb/src/storage/compression/fsst.cpp @@ -48,7 +48,7 @@ struct FSSTStorage { static void Compress(CompressionState &state_p, const Vector &scan_vector); static void FinalizeCompress(CompressionState &state_p); - static unique_ptr StringInitScan(const QueryContext &context, ColumnSegment &segment); + static unique_ptr StringInitScan(Context &context, ColumnSegment &segment); template static void StringScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset); @@ -606,7 +606,7 @@ struct FSSTScanState : public SegmentScanState { } }; -unique_ptr FSSTStorage::StringInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr FSSTStorage::StringInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); auto layout = FSSTScanState::ParseFSSTSegmentHeader(CompressionSegmentReader::FromSegment(handle, segment, "FSST"), diff --git a/src/duckdb/src/storage/compression/numeric_constant.cpp b/src/duckdb/src/storage/compression/numeric_constant.cpp index a9dcd1a97..55ad36ca3 100644 --- a/src/duckdb/src/storage/compression/numeric_constant.cpp +++ b/src/duckdb/src/storage/compression/numeric_constant.cpp @@ -167,7 +167,7 @@ static bool TryExpressionFiltersNullValues(const Expression &expression, bool &f //===--------------------------------------------------------------------===// // Scan //===--------------------------------------------------------------------===// -unique_ptr ConstantInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr ConstantInitScan(Context &context, ColumnSegment &segment) { return nullptr; } diff --git a/src/duckdb/src/storage/compression/rle.cpp b/src/duckdb/src/storage/compression/rle.cpp index c3354cf93..69e7a02d8 100644 --- a/src/duckdb/src/storage/compression/rle.cpp +++ b/src/duckdb/src/storage/compression/rle.cpp @@ -535,7 +535,7 @@ struct RLEScanState : public SegmentScanState { }; template -unique_ptr RLEInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr RLEInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); auto result = make_uniq>(std::move(handle), segment); diff --git a/src/duckdb/src/storage/compression/roaring/common.cpp b/src/duckdb/src/storage/compression/roaring/common.cpp index 6857ecf42..94399b63f 100644 --- a/src/duckdb/src/storage/compression/roaring/common.cpp +++ b/src/duckdb/src/storage/compression/roaring/common.cpp @@ -210,7 +210,7 @@ void RoaringFinalizeCompress(CompressionState &state_p) { state.Finalize(); } -unique_ptr RoaringInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr RoaringInitScan(Context &context, ColumnSegment &segment) { auto result = make_uniq(context, segment); return std::move(result); } diff --git a/src/duckdb/src/storage/compression/roaring/scan.cpp b/src/duckdb/src/storage/compression/roaring/scan.cpp index 2fa9a8405..5c5e72a26 100644 --- a/src/duckdb/src/storage/compression/roaring/scan.cpp +++ b/src/duckdb/src/storage/compression/roaring/scan.cpp @@ -232,7 +232,7 @@ RoaringScanState::SegmentLayout RoaringScanState::ReadLayout(const BufferHandle return {data, metadata}; } -RoaringScanState::RoaringScanState(const QueryContext &context, ColumnSegment &segment) +RoaringScanState::RoaringScanState(Context &context, ColumnSegment &segment) : handle(BufferManager::GetBufferManager(segment.GetDatabase()).Pin(context, segment.GetBlockHandle())), segment(segment), layout(ReadLayout(handle, segment)) { // Deserialize the container metadata for this segment diff --git a/src/duckdb/src/storage/compression/string_uncompressed.cpp b/src/duckdb/src/storage/compression/string_uncompressed.cpp index 086212eed..9d30cd53b 100644 --- a/src/duckdb/src/storage/compression/string_uncompressed.cpp +++ b/src/duckdb/src/storage/compression/string_uncompressed.cpp @@ -121,8 +121,7 @@ void UncompressedStringInitPrefetch(ColumnSegment &segment, PrefetchState &prefe } } -unique_ptr UncompressedStringStorage::StringInitScan(const QueryContext &context, - ColumnSegment &segment) { +unique_ptr UncompressedStringStorage::StringInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); return make_uniq(std::move(handle)); @@ -524,8 +523,8 @@ void UncompressedStringStorage::WriteStringMemory(ColumnSegment &segment, string state.head->offset += total_length; } -string_t UncompressedStringStorage::ReadOverflowString(const QueryContext &context, ColumnSegment &segment, - Vector &result, block_id_t block, int32_t offset) { +string_t UncompressedStringStorage::ReadOverflowString(Context &context, ColumnSegment &segment, Vector &result, + block_id_t block, int32_t offset) { auto &buffer_manager = segment.GetBlockHandle()->GetMemory().GetBufferManager(); auto &state = segment.GetSegmentState()->Cast(); diff --git a/src/duckdb/src/storage/compression/validity_uncompressed.cpp b/src/duckdb/src/storage/compression/validity_uncompressed.cpp index dcf2383f3..39fe0c11d 100644 --- a/src/duckdb/src/storage/compression/validity_uncompressed.cpp +++ b/src/duckdb/src/storage/compression/validity_uncompressed.cpp @@ -244,7 +244,7 @@ static unsafe_array_ptr ValidityScanData(const CompressionSegm return reader.GetArraySlice(0, entry_start, entry_end - entry_start + 1); } -unique_ptr ValidityInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr ValidityInitScan(Context &context, ColumnSegment &segment) { auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(context, segment.GetBlockHandle()); return make_uniq(std::move(handle), segment); diff --git a/src/duckdb/src/storage/compression/zstd.cpp b/src/duckdb/src/storage/compression/zstd.cpp index 3a5ff11c3..9048d956a 100644 --- a/src/duckdb/src/storage/compression/zstd.cpp +++ b/src/duckdb/src/storage/compression/zstd.cpp @@ -81,7 +81,7 @@ struct ZSTDStorage { static void Compress(CompressionState &state_p, const Vector &scan_vector); static void FinalizeCompress(CompressionState &state_p); - static unique_ptr StringInitScan(const QueryContext &context, ColumnSegment &segment); + static unique_ptr StringInitScan(Context &context, ColumnSegment &segment); static void StringScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset); static void StringScan(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result); @@ -301,7 +301,7 @@ class ZSTDCompressionState : public CompressionState { buffer_collection.SetCurrentBuffer(buffer.slot); auto &buffer_handle = buffer_collection.BufferHandleMutable(); if (!buffer_handle.IsValid()) { - buffer_handle = buffer_manager.Allocate(QueryContext(checkpoint_data.GetCheckpointState().GetContext()), + buffer_handle = buffer_manager.Allocate(checkpoint_data.GetCheckpointState().GetContext(), MemoryTag::OVERFLOW_STRINGS, &block_manager); } return; @@ -477,8 +477,7 @@ class ZSTDCompressionState : public CompressionState { // Write the current page to disk auto &block_manager = partial_block_manager.GetBlockManager(); - block_manager.Write(QueryContext(checkpoint_data.GetCheckpointState().GetContext()), buffer.GetFileBuffer(), - block_id); + block_manager.Write(checkpoint_data.GetCheckpointState().GetContext(), buffer.GetFileBuffer(), block_id); } void FlushVector() { @@ -548,9 +547,8 @@ class ZSTDCompressionState : public CompressionState { stats_writer.Clear(); auto &buffer_manager = BufferManager::GetBufferManager(checkpoint_data.GetDatabase()); - buffer_collection.segment_handle = - buffer_manager.Pin(QueryContext(checkpoint_data.GetCheckpointState().GetContext()), - buffer_collection.segment->GetBlockHandle()); + buffer_collection.segment_handle = buffer_manager.Pin(checkpoint_data.GetCheckpointState().GetContext(), + buffer_collection.segment->GetBlockHandle()); } void FlushSegment() { @@ -758,7 +756,7 @@ struct ZSTDScanState : public SegmentScanState { static SegmentLayout ReadLayout(const BufferHandle &handle, const ColumnSegment &segment); - explicit ZSTDScanState(const QueryContext &context, ColumnSegment &segment) + explicit ZSTDScanState(Context &context, ColumnSegment &segment) : state(segment.GetSegmentState()->Cast()), block_manager(segment.GetBlockHandle()->GetBlockManager()), buffer_manager(BufferManager::GetBufferManager(segment.GetDatabase())), context(context), @@ -1009,7 +1007,7 @@ struct ZSTDScanState : public SegmentScanState { UncompressedStringSegmentState &state; BlockManager &block_manager; BufferManager &buffer_manager; - const QueryContext context; + Context &context; duckdb_zstd::ZSTD_DCtx *decompression_context = nullptr; @@ -1049,7 +1047,7 @@ ZSTDScanState::SegmentLayout ZSTDScanState::ReadLayout(const BufferHandle &handl return {page_ids, page_offsets, uncompressed_sizes, compressed_sizes, data, data_offset}; } -unique_ptr ZSTDStorage::StringInitScan(const QueryContext &context, ColumnSegment &segment) { +unique_ptr ZSTDStorage::StringInitScan(Context &context, ColumnSegment &segment) { auto result = make_uniq(context, segment); return std::move(result); } diff --git a/src/duckdb/src/storage/data_table.cpp b/src/duckdb/src/storage/data_table.cpp index e09a5e443..75420de48 100644 --- a/src/duckdb/src/storage/data_table.cpp +++ b/src/duckdb/src/storage/data_table.cpp @@ -291,7 +291,7 @@ void DataTable::InitializeScan(ClientContext &context, DuckTransaction &transact void DataTable::InitializeScanWithOffset(DuckTransaction &transaction, TableScanState &state, const vector &column_ids, idx_t start_row, idx_t end_row) { state.Initialize(column_ids); - row_groups->InitializeScanWithOffset(QueryContext(), state.table_state, column_ids, start_row, end_row); + row_groups->InitializeScanWithOffset(db.GetContext(), state.table_state, column_ids, start_row, end_row); } idx_t DataTable::GetRowGroupSize() const { @@ -525,7 +525,7 @@ void DataTable::RebuildIndexes() { CreateIndexScanState state; auto scan_type = TableScanType::TABLE_SCAN_COMMITTED_ROWS; state.Initialize(scan_column_ids, nullptr); - QueryContext context; + Context &context = db.GetContext(); row_groups->InitializeScan(context, state.table_state, scan_column_ids, nullptr); row_groups->InitializeCreateIndexScan(state); @@ -646,8 +646,7 @@ void DataTable::Fetch(DuckTransaction &transaction, DataChunk &result, const vec local_chunk.Initialize(allocator, result.GetTypes()); Vector local_row_ids(row_identifiers, local_sel, local_count); local_row_ids.Flatten(); - ColumnFetchState local_fetch_state; - local_fetch_state.context = state.context; + ColumnFetchState local_fetch_state(state.context); local_storage.FetchChunk(*this, local_row_ids, local_count, column_ids, local_chunk, local_fetch_state); // Append local rows after committed rows in the result. @@ -1388,9 +1387,8 @@ void DataTable::RevertAppend(DuckTransaction &transaction, idx_t start_row, idx_ //===--------------------------------------------------------------------===// // Indexes //===--------------------------------------------------------------------===// -void DataTable::RemoveFromIndexes(const QueryContext &context, Vector &row_identifiers, idx_t count, - IndexRemovalType removal_type, optional_idx active_checkpoint, - VisibilityBound bound) { +void DataTable::RemoveFromIndexes(Context &context, Vector &row_identifiers, idx_t count, IndexRemovalType removal_type, + optional_idx active_checkpoint, VisibilityBound bound) { row_groups->RemoveFromIndexes(context, info->indexes, row_identifiers, count, removal_type, active_checkpoint, bound); } @@ -1496,7 +1494,7 @@ idx_t DataTable::Delete(TableDeleteState &state, ClientContext &context, DuckTab if (is_transaction_delete) { if (state.has_delete_constraints) { // Verify any delete constraints. - ColumnFetchState fetch_state; + ColumnFetchState fetch_state(context); local_storage.FetchChunk(*this, offset_ids, current_count, state.col_ids, state.verify_chunk, fetch_state); VerifyDeleteConstraints(storage, state, context, state.verify_chunk); @@ -1508,7 +1506,7 @@ idx_t DataTable::Delete(TableDeleteState &state, ClientContext &context, DuckTab // This is a regular DELETE. if (state.has_delete_constraints) { // Verify any delete constraints. - ColumnFetchState fetch_state; + ColumnFetchState fetch_state(context); Fetch(transaction, state.verify_chunk, state.col_ids, offset_ids, current_count, fetch_state); VerifyDeleteConstraints(storage, state, context, state.verify_chunk); } @@ -1841,7 +1839,7 @@ idx_t DataTable::GetRowGroupCountWithLocalStorage(ClientContext &context) { //===--------------------------------------------------------------------===// // Column Segment Info //===--------------------------------------------------------------------===// -vector DataTable::GetColumnSegmentInfo(const QueryContext &context, +vector DataTable::GetColumnSegmentInfo(Context &context, const ColumnSegmentInfoScanOptions &options) { return row_groups->GetColumnSegmentInfo(context, options); } @@ -1850,7 +1848,7 @@ void DataTable::InitializeColumnSegmentInfoScan(ColumnSegmentInfoScanState &stat row_groups->InitializeColumnSegmentInfoScan(state); } -bool DataTable::ScanColumnSegmentInfo(const QueryContext &context, ColumnSegmentInfoScanState &state, +bool DataTable::ScanColumnSegmentInfo(Context &context, ColumnSegmentInfoScanState &state, vector &result) { return row_groups->ScanColumnSegmentInfo(context, state, result); } diff --git a/src/duckdb/src/storage/database_handle.cpp b/src/duckdb/src/storage/database_handle.cpp index 3c69c3ab1..b0d32a70f 100644 --- a/src/duckdb/src/storage/database_handle.cpp +++ b/src/duckdb/src/storage/database_handle.cpp @@ -1,6 +1,6 @@ #include "duckdb/storage/database_handle.hpp" #include "duckdb/storage/single_file_block_manager.hpp" -#include "duckdb/common/query_context.hpp" +#include "duckdb/main/context.hpp" #include @@ -12,17 +12,14 @@ DatabaseHandle::DatabaseHandle(unique_ptr mmap_handle_p) : mma } //! The file system to open the database file with. The handle outlives the statement that opens it, but file systems -//! take what they need from the opener when the file is opened: through the client's file system, a remote database +//! take what they need from the context when the file is opened: through the client's file system, a remote database //! file uses the settings of the session that attached it (http_proxy, ca_cert_file, ...) and reports its requests to //! that session's logger. Without a client, the database-wide file system only sees global settings. -static FileSystem &GetDatabaseFileSystem(QueryContext context, AttachedDatabase &db) { - if (context.Valid()) { - return context.GetContext()->GetFileSystem(); - } - return FileSystem::Get(db); +static FileSystem &GetDatabaseFileSystem(Context &context, AttachedDatabase &db) { + return context.GetFileSystem(); } -unique_ptr DatabaseHandle::Open(QueryContext context, AttachedDatabase &db, const string &path, +unique_ptr DatabaseHandle::Open(Context &context, AttachedDatabase &db, const string &path, const StorageManagerOptions &options, DatabaseOpenMode open_mode) { if (options.io_mode == FileIOMode::MMAP) { // mmap reads are zero-copy from the mapping, so the prefetched header is not needed here. @@ -32,7 +29,7 @@ unique_ptr DatabaseHandle::Open(QueryContext context, AttachedDa } } -unique_ptr DatabaseHandle::OpenFile(QueryContext context, AttachedDatabase &db, const string &path, +unique_ptr DatabaseHandle::OpenFile(Context &context, AttachedDatabase &db, const string &path, const StorageManagerOptions &options, DatabaseOpenMode open_mode) { FileOpenFlags file_flags; if (options.read_only) { @@ -66,7 +63,7 @@ unique_ptr DatabaseHandle::OpenFile(QueryContext context, Attach return result; } -unique_ptr DatabaseHandle::OpenMemoryMap(QueryContext context, AttachedDatabase &db, const string &path, +unique_ptr DatabaseHandle::OpenMemoryMap(Context &context, AttachedDatabase &db, const string &path, const StorageManagerOptions &options, DatabaseOpenMode open_mode) { if (options.encryption_options.encryption_enabled) { @@ -104,7 +101,7 @@ bool DatabaseHandle::OnDiskFile() const { return handle->OnDiskFile(); } -void DatabaseHandle::CheckMagicBytes(QueryContext context) { +void DatabaseHandle::CheckMagicBytes(Context &context) { if (mmap_handle) { MainHeader::CheckMagicBytes(*mmap_handle); return; @@ -121,7 +118,7 @@ void DatabaseHandle::CheckMagicBytes(QueryContext context) { MainHeader::CheckMagicBytes(context, *handle); } -void DatabaseHandle::Read(QueryContext context, FileBuffer &block, uint64_t location) const { +void DatabaseHandle::Read(Context &context, FileBuffer &block, uint64_t location) const { if (mmap_handle) { block.Read(context, *mmap_handle, location); return; @@ -136,7 +133,7 @@ void DatabaseHandle::Read(QueryContext context, FileBuffer &block, uint64_t loca block.Read(context, *handle, location); } -void DatabaseHandle::Write(QueryContext context, FileBuffer &buffer, uint64_t location) { +void DatabaseHandle::Write(Context &context, FileBuffer &buffer, uint64_t location) { if (mmap_handle) { EnsureMappedSize(location + buffer.AllocSize()); buffer.Write(context, *mmap_handle, location); diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp index 7fd3ee93f..ad4e004de 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp @@ -71,17 +71,8 @@ void TightenCacheDeadline(optional &cached, const optional block_p, BufferHandle &result_pin_p) : BaseExecutorTask(executor), caching_file_handle(caching_file_handle_p), context(context_p), buffer_manager(buffer_manager_p), block(std::move(block_p)), result_pin(result_pin_p) { @@ -110,8 +101,8 @@ class FetchBlockTask : public BaseExecutorTask { const idx_t nr_bytes = block->nr_bytes; result_pin = std::move(pin); lk.unlock(); - LogCacheEvent(context, buffer_manager.GetDatabase(), caching_file_handle, - ExternalFileCacheLogType::HIT_EVENT, nr_bytes, block->location); + LogCacheEvent(context, caching_file_handle, ExternalFileCacheLogType::HIT_EVENT, nr_bytes, + block->location); return; } // Evicted by buffer manager, need to re-fetch @@ -137,8 +128,7 @@ class FetchBlockTask : public BaseExecutorTask { auto buf = ExternalFileCache::AllocateCacheBuffer(buffer_manager, caching_file_handle.GetPath(), to_read); caching_file_handle.ReadAndRecord(context, buf.GetDataMutable(), to_read, offset); - LogCacheEvent(context, buffer_manager.GetDatabase(), caching_file_handle, - ExternalFileCacheLogType::MISS_EVENT, to_read, offset); + LogCacheEvent(context, caching_file_handle, ExternalFileCacheLogType::MISS_EVENT, to_read, offset); const bool share_block = !caching_file_handle.IsCacheReuseProhibited(); lk.lock(); @@ -185,7 +175,7 @@ class FetchBlockTask : public BaseExecutorTask { private: CachingFileHandle &caching_file_handle; - QueryContext context; + Context &context; BufferManager &buffer_manager; shared_ptr block; BufferHandle &result_pin; @@ -197,7 +187,7 @@ class FetchBlockTask : public BaseExecutorTask { class ReadRangeTask : public BaseExecutorTask { public: - ReadRangeTask(CachingFileHandle &caching_file_handle_p, TaskExecutor &executor, QueryContext context_p, + ReadRangeTask(CachingFileHandle &caching_file_handle_p, TaskExecutor &executor, Context &context_p, data_ptr_t buffer_p, idx_t nr_bytes_p, idx_t location_p) : BaseExecutorTask(executor), caching_file_handle(caching_file_handle_p), context(context_p), buffer(buffer_p), nr_bytes(nr_bytes_p), location(location_p) { @@ -213,7 +203,7 @@ class ReadRangeTask : public BaseExecutorTask { private: CachingFileHandle &caching_file_handle; - QueryContext context; + Context &context; data_ptr_t buffer; idx_t nr_bytes; idx_t location; @@ -236,14 +226,9 @@ CachingFileSystem CachingFileSystem::Get(ClientContext &context) { return CachingFileSystem(FileSystem::GetFileSystem(context), *context.db); } -unique_ptr CachingFileSystem::OpenFile(const OpenFileInfo &path, const FileOpenFlags &flags, - optional_ptr opener) { - return OpenFile(QueryContext(), path, flags, opener); -} - -unique_ptr CachingFileSystem::OpenFile(QueryContext context, const OpenFileInfo &path, - const FileOpenFlags &flags, optional_ptr opener) { - auto handle = unique_ptr(new CachingFileHandle(context, *this, path, flags, opener)); +unique_ptr CachingFileSystem::OpenFile(Context &context, const OpenFileInfo &path, + const FileOpenFlags &flags) { + auto handle = unique_ptr(new CachingFileHandle(context, *this, path, flags)); if (!handle->Initialize()) { return nullptr; } @@ -337,13 +322,11 @@ void CachingFileHandle::ReconcileCacheAfterRead(CachedFile &cached_file) { external_file_cache.DropBlocks(cached_file); } -CachingFileHandle::CachingFileHandle(QueryContext context, CachingFileSystem &caching_file_system_p, - const OpenFileInfo &path_p, FileOpenFlags flags_p, - optional_ptr opener_p) +CachingFileHandle::CachingFileHandle(Context &context, CachingFileSystem &caching_file_system_p, + const OpenFileInfo &path_p, FileOpenFlags flags_p) : context(context), file_system(caching_file_system_p.file_system), db(caching_file_system_p.db), external_file_cache(caching_file_system_p.external_file_cache), path(path_p), flags(std::move(flags_p)), - opener(opener_p), - validate(ExternalFileCacheUtil::GetCacheValidationMode(path_p, context.GetContext(), caching_file_system_p.db)), + validate(ExternalFileCacheUtil::GetCacheValidationMode(path_p, context, caching_file_system_p.db)), cached_file(external_file_cache.GetOrCreateCachedFile(path_p.path)), position(0) { } @@ -453,7 +436,7 @@ FileBufferHandleGroup CachingFileHandle::Read(const idx_t nr_bytes, const idx_t if (location >= file_size) { return FileBufferHandleGroup(); } - LogCacheEvent(context, db, *this, ExternalFileCacheLogType::READ_EVENT, MinValue(nr_bytes, file_size - location), + LogCacheEvent(context, *this, ExternalFileCacheLogType::READ_EVENT, MinValue(nr_bytes, file_size - location), location); const idx_t max_block_size = external_file_cache.GetCacheMaxBlockSize(current_cached_file->path); const idx_t min_block_size = @@ -581,10 +564,6 @@ string CachingFileHandle::GetPath() const { return path.path; } -optional_ptr CachingFileHandle::GetOpener() const { - return opener; -} - idx_t CachingFileHandle::GetFileSize() { if (!Validate()) { auto current_cached_file = EnsureCachedFileCurrent(); @@ -723,7 +702,7 @@ idx_t CachingFileHandle::GetMaxMemory() const { return external_file_cache.GetBufferManager().GetMaxMemory(); } -void CachingFileHandle::ReadAndRecord(QueryContext context, data_ptr_t buffer, idx_t nr_bytes, idx_t location) { +void CachingFileHandle::ReadAndRecord(Context &context, data_ptr_t buffer, idx_t nr_bytes, idx_t location) { auto handle = GetFileHandle(); if (handle->file_system.IsLocalFileSystem()) { // Pre-fault local read buffers before the kernel fills them. 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 48f5dff99..6ad661148 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 @@ -97,21 +97,20 @@ void CachingFileSystemWrapper::FileSync(FileHandle &handle) { //===----------------------------------------------------------------------===// // OpenFile Operations //===----------------------------------------------------------------------===// -unique_ptr CachingFileSystemWrapper::OpenFile(const string &path, FileOpenFlags flags, - optional_ptr opener) { - return OpenFile(OpenFileInfo(path), flags, opener); +unique_ptr CachingFileSystemWrapper::OpenFile(Context &context, const string &path, FileOpenFlags flags) { + return OpenFile(context, OpenFileInfo(path), flags); } -unique_ptr CachingFileSystemWrapper::OpenFile(const OpenFileInfo &path, FileOpenFlags flags, - optional_ptr opener) { +unique_ptr CachingFileSystemWrapper::OpenFile(Context &context, const OpenFileInfo &path, + FileOpenFlags flags) { if (SupportsOpenFileExtended()) { - return OpenFileExtended(path, std::move(flags), opener); + return OpenFileExtended(context, path, std::move(flags)); } throw NotImplementedException("CachingFileSystemWrapper: OpenFile is not implemented!"); } -unique_ptr CachingFileSystemWrapper::OpenFileExtended(const OpenFileInfo &path, FileOpenFlags flags, - optional_ptr opener) { +unique_ptr CachingFileSystemWrapper::OpenFileExtended(Context &context, const OpenFileInfo &path, + FileOpenFlags flags) { if (flags.OpenForWriting()) { throw NotImplementedException("CachingFileSystemWrapper: Cannot open file for writing. " "CachingFileSystemWrapper is a read-only caching filesystem."); @@ -122,7 +121,7 @@ unique_ptr CachingFileSystemWrapper::OpenFileExtended(const OpenFile } if (ShouldUseCache(path.path)) { - auto caching_handle = caching_file_system.OpenFile(path, flags, opener); + auto caching_handle = caching_file_system.OpenFile(context, path, flags); if (!caching_handle) { return nullptr; } @@ -208,49 +207,46 @@ FileMetadata CachingFileSystemWrapper::Stats(FileHandle &handle) { return underlying_file_system.Stats(*file_handle); } -optional CachingFileSystemWrapper::GetStatsIfExists(const OpenFileInfo &file, - optional_ptr opener) { +optional CachingFileSystemWrapper::GetStatsIfExists(Context &context, const OpenFileInfo &file) { return underlying_file_system.GetStatsIfExists(file); } //===----------------------------------------------------------------------===// // Directory Operations //===----------------------------------------------------------------------===// -bool CachingFileSystemWrapper::DirectoryExists(const string &directory, optional_ptr opener) { +bool CachingFileSystemWrapper::DirectoryExists(Context &context, const string &directory) { return underlying_file_system.DirectoryExists(directory); } -void CachingFileSystemWrapper::CreateDirectory(const string &directory, optional_ptr opener) { - CreateDirectoryExtended(directory, {CreateDirectoryMode::SINGLE}, opener); +void CachingFileSystemWrapper::CreateDirectory(Context &context, const string &directory) { + CreateDirectoryExtended(context, directory, {CreateDirectoryMode::SINGLE}); } -bool CachingFileSystemWrapper::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener) { +bool CachingFileSystemWrapper::CreateDirectoryExtended(Context &context, const string &directory, + const CreateDirectoryOptions &options) { return underlying_file_system.CreateDirectoryExtended(directory, options); } -void CachingFileSystemWrapper::CreateDirectoriesRecursive(const string &path, optional_ptr opener) { - CreateDirectoryExtended(path, {CreateDirectoryMode::RECURSIVE}, opener); +void CachingFileSystemWrapper::CreateDirectoriesRecursive(Context &context, const string &path) { + CreateDirectoryExtended(context, path, {CreateDirectoryMode::RECURSIVE}); } -void CachingFileSystemWrapper::RemoveDirectory(const string &directory, optional_ptr opener) { - RemoveDirectoryExtended(directory, {RemoveDirectoryMode::RECURSIVE}, opener); +void CachingFileSystemWrapper::RemoveDirectory(Context &context, const string &directory) { + RemoveDirectoryExtended(context, directory, {RemoveDirectoryMode::RECURSIVE}); } -bool CachingFileSystemWrapper::RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener) { +bool CachingFileSystemWrapper::RemoveDirectoryExtended(Context &context, const string &directory, + const RemoveDirectoryOptions &options) { return underlying_file_system.RemoveDirectoryExtended(directory, options); } -bool CachingFileSystemWrapper::ListFiles(const string &directory, - const std::function &callback, - FileOpener *opener) { +bool CachingFileSystemWrapper::ListFiles(Context &context, const string &directory, + const std::function &callback) { return underlying_file_system.ListFiles(directory, callback); } -bool CachingFileSystemWrapper::ListFilesExtended(const string &directory, - const std::function &callback, - optional_ptr opener) { +bool CachingFileSystemWrapper::ListFilesExtended(Context &context, const string &directory, + const std::function &callback) { // Use the public ListFiles API which will internally call `ListFilesExtended` if supported. return underlying_file_system.ListFiles(directory, callback); } @@ -260,23 +256,23 @@ bool CachingFileSystemWrapper::SupportsListFilesExtended() const { return true; } -void CachingFileSystemWrapper::MoveFile(const string &source, const string &target, optional_ptr opener) { +void CachingFileSystemWrapper::MoveFile(Context &context, const string &source, const string &target) { underlying_file_system.MoveFile(source, target); } -bool CachingFileSystemWrapper::FileExists(const string &filename, optional_ptr opener) { +bool CachingFileSystemWrapper::FileExists(Context &context, const string &filename) { return underlying_file_system.FileExists(filename); } -bool CachingFileSystemWrapper::IsPipe(const string &filename, optional_ptr opener) { +bool CachingFileSystemWrapper::IsPipe(Context &context, const string &filename) { return underlying_file_system.IsPipe(filename); } -void CachingFileSystemWrapper::RemoveFile(const string &filename, optional_ptr opener) { +void CachingFileSystemWrapper::RemoveFile(Context &context, const string &filename) { underlying_file_system.RemoveFile(filename); } -bool CachingFileSystemWrapper::TryRemoveFile(const string &filename, optional_ptr opener) { +bool CachingFileSystemWrapper::TryRemoveFile(Context &context, const string &filename) { return underlying_file_system.TryRemoveFile(filename); } @@ -295,7 +291,7 @@ string CachingFileSystemWrapper::PathSeparator(const string &path) { return underlying_file_system.PathSeparator(path); } -vector CachingFileSystemWrapper::Glob(const string &path, FileOpener *opener) { +vector CachingFileSystemWrapper::Glob(Context &context, const string &path) { return underlying_file_system.Glob(path); } @@ -347,7 +343,7 @@ bool CachingFileSystemWrapper::OnDiskFile(FileHandle &handle) { //===----------------------------------------------------------------------===// // Other Operations //===----------------------------------------------------------------------===// -unique_ptr CachingFileSystemWrapper::OpenCompressedFile(QueryContext context, unique_ptr handle, +unique_ptr CachingFileSystemWrapper::OpenCompressedFile(Context &context, unique_ptr handle, bool write) { auto &file_system = handle->file_system; return file_system.OpenCompressedFile(context, std::move(handle), write); diff --git a/src/duckdb/src/storage/local_storage.cpp b/src/duckdb/src/storage/local_storage.cpp index 66525f328..ddd949914 100644 --- a/src/duckdb/src/storage/local_storage.cpp +++ b/src/duckdb/src/storage/local_storage.cpp @@ -98,7 +98,7 @@ LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_dt, LocalTableStorage::~LocalTableStorage() { } -void LocalTableStorage::InitializeScan(const QueryContext &scan_context, CollectionScanState &state, +void LocalTableStorage::InitializeScan(Context &scan_context, CollectionScanState &state, optional_ptr table_filters) { auto &collection = *row_groups->collection; if (collection.GetTotalRows() == 0) { @@ -466,7 +466,7 @@ LocalStorage &LocalStorage::Get(ClientContext &context, Catalog &catalog) { return LocalStorage::Get(context, catalog.GetAttached()); } -void LocalStorage::InitializeScan(const QueryContext &context, DataTable &table, CollectionScanState &state, +void LocalStorage::InitializeScan(Context &context, DataTable &table, CollectionScanState &state, optional_ptr table_filters) { auto storage = table_manager.GetStorage(table); if (storage == nullptr) { diff --git a/src/duckdb/src/storage/magic_bytes.cpp b/src/duckdb/src/storage/magic_bytes.cpp index 141f7de43..a006997b5 100644 --- a/src/duckdb/src/storage/magic_bytes.cpp +++ b/src/duckdb/src/storage/magic_bytes.cpp @@ -26,7 +26,7 @@ static DataFileType ClassifyMagicBytes(const char *buffer) { return DataFileType::UNKNOWN_FILE; } -DataFileType MagicBytes::CheckMagicBytes(QueryContext context, FileSystem &fs, const string &path, +DataFileType MagicBytes::CheckMagicBytes(Context &context, FileSystem &fs, const string &path, optional_ptr out_prefetch) { if (path.empty() || path == IN_MEMORY_PATH) { return DataFileType::DUCKDB_FILE; diff --git a/src/duckdb/src/storage/metadata/metadata_manager.cpp b/src/duckdb/src/storage/metadata/metadata_manager.cpp index ac38cf2bd..44e316c16 100644 --- a/src/duckdb/src/storage/metadata/metadata_manager.cpp +++ b/src/duckdb/src/storage/metadata/metadata_manager.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/database.hpp" #include "duckdb/storage/metadata/metadata_manager.hpp" #include "duckdb/common/serializer/read_stream.hpp" @@ -9,6 +10,10 @@ namespace duckdb { +DatabaseInstance &MetadataManager::GetDatabase() { + return buffer_manager.GetDatabase(); +} + MetadataBlock::MetadataBlock() : block_id(INVALID_BLOCK), pending_reuse(0), dirty(false) { } @@ -98,10 +103,10 @@ MetadataHandle MetadataManager::AllocateHandle() { } MetadataHandle MetadataManager::Pin(const MetadataPointer &pointer) { - return Pin(QueryContext(), pointer); + return Pin(GetDatabase().GetContext(), pointer); } -MetadataHandle MetadataManager::Pin(const QueryContext &context, const MetadataPointer &pointer) { +MetadataHandle MetadataManager::Pin(Context &context, const MetadataPointer &pointer) { D_ASSERT(pointer.index < METADATA_BLOCK_COUNT); while (true) { shared_ptr block_handle; @@ -291,7 +296,7 @@ idx_t MetadataManager::BlockCount() { return blocks.size(); } -void MetadataManager::Flush(QueryContext context) { +void MetadataManager::Flush(Context &context) { // Write the blocks of the metadata manager to disk. const idx_t total_metadata_size = GetMetadataBlockSize() * METADATA_BLOCK_COUNT; diff --git a/src/duckdb/src/storage/metadata/metadata_reader.cpp b/src/duckdb/src/storage/metadata/metadata_reader.cpp index be0b771b3..7b4733bf2 100644 --- a/src/duckdb/src/storage/metadata/metadata_reader.cpp +++ b/src/duckdb/src/storage/metadata/metadata_reader.cpp @@ -1,3 +1,4 @@ +#include "duckdb/main/database.hpp" #include "duckdb/storage/metadata/metadata_reader.hpp" #include "duckdb/common/numeric_utils.hpp" @@ -27,10 +28,10 @@ MetadataReader::~MetadataReader() { } void MetadataReader::ReadData(data_ptr_t buffer, idx_t read_size) { - ReadData(QueryContext(), buffer, read_size); + ReadData(manager.GetDatabase().GetContext(), buffer, read_size); } -void MetadataReader::ReadData(QueryContext context, data_ptr_t buffer, idx_t read_size) { +void MetadataReader::ReadData(Context &context, data_ptr_t buffer, idx_t read_size) { while (offset + read_size > capacity) { // cannot read entire entry from block // first read what we can from this block @@ -57,10 +58,10 @@ MetaBlockPointer MetadataReader::GetMetaBlockPointer() { } void MetadataReader::ReadNextBlock() { - ReadNextBlock(QueryContext()); + ReadNextBlock(manager.GetDatabase().GetContext()); } -void MetadataReader::ReadNextBlock(QueryContext context) { +void MetadataReader::ReadNextBlock(Context &context) { if (!has_next_block) { throw IOException("No more data remaining in MetadataReader"); } diff --git a/src/duckdb/src/storage/partial_block_manager.cpp b/src/duckdb/src/storage/partial_block_manager.cpp index 7125a6891..5c6780fb7 100644 --- a/src/duckdb/src/storage/partial_block_manager.cpp +++ b/src/duckdb/src/storage/partial_block_manager.cpp @@ -32,7 +32,7 @@ struct PartialBlock { //! Borrow the source pin and copy its bytes into the packing buffer. BlockPointer Store(BlockPackable &packable, const BufferHandle &source, uint32_t byte_size); //! Flush the block to disk and zero-initialize any tail free space. - void Flush(QueryContext context, PartialBlockType type); + void Flush(Context &context, PartialBlockType type); //! Merge packables before either block has a persistent block ID. void Merge(PartialBlock &other); //! Remove all packables and the associated backing block. @@ -172,7 +172,7 @@ BlockPointer PartialBlock::FinishStore(BlockPackable &packable, BufferHandle des return block_ptr; } -void PartialBlock::Flush(QueryContext context, PartialBlockType type) { +void PartialBlock::Flush(Context &context, PartialBlockType type) { if (!block_handle) { throw InternalException("Flush called on partial block that was already flushed"); } @@ -300,7 +300,7 @@ void PartialBlockManager::ClearBlocks() { void PartialBlockManager::FlushPartialBlocks(Context &context) { for (auto &e : partially_filled_blocks) { - e.second->Flush(QueryContext(context), partial_block_type); + e.second->Flush(context, partial_block_type); } partially_filled_blocks.clear(); } @@ -358,27 +358,23 @@ unique_ptr PartialBlockManager::PruneFreeList() { return block; } -static QueryContext ToQueryContext(optional_ptr context) { - return context ? QueryContext(*context) : QueryContext(); -} - -void PartialBlockManager::RetainOrFlush(optional_ptr context, unique_ptr partial_block) { +void PartialBlockManager::RetainOrFlush(Context &context, unique_ptr partial_block) { auto min_reusable_space = block_manager.GetBlockSize() - max_partial_block_size; auto available_space = partial_block->AvailableSpace(); if (partial_block->UseCount() >= max_use_count) { - partial_block->Flush(ToQueryContext(context), partial_block_type); + partial_block->Flush(context, partial_block_type); return; } if (available_space < min_reusable_space) { - partial_block->Flush(ToQueryContext(context), partial_block_type); + partial_block->Flush(context, partial_block_type); return; } partially_filled_blocks.insert(make_pair(partial_block->AvailableSpace(), std::move(partial_block))); if (auto pruned_block = PruneFreeList()) { - pruned_block->Flush(ToQueryContext(context), partial_block_type); + pruned_block->Flush(context, partial_block_type); } } @@ -404,12 +400,7 @@ optional PartialBlockManager::Write(Context &context, BlockPackabl return WriteCopy(context, packable, source, byte_size); } -optional PartialBlockManager::Write(BlockPackable &packable, const BufferHandle &source, - uint32_t byte_size) { - return WriteCopy(nullptr, packable, source, byte_size); -} - -optional PartialBlockManager::WriteCopy(optional_ptr context, BlockPackable &packable, +optional PartialBlockManager::WriteCopy(Context &context, BlockPackable &packable, const BufferHandle &source, uint32_t byte_size) { unique_lock lock(partial_block_lock); diff --git a/src/duckdb/src/storage/single_file_block_manager.cpp b/src/duckdb/src/storage/single_file_block_manager.cpp index df2b0a5c2..8b96ae390 100644 --- a/src/duckdb/src/storage/single_file_block_manager.cpp +++ b/src/duckdb/src/storage/single_file_block_manager.cpp @@ -196,7 +196,7 @@ void MainHeader::Write(WriteStream &ser) { SerializeTag(ser, canary_tag, encryption_enabled); } -void MainHeader::CheckMagicBytes(QueryContext context, FileHandle &handle) { +void MainHeader::CheckMagicBytes(Context &context, FileHandle &handle) { data_t magic_bytes[MAGIC_BYTE_SIZE]; if (handle.GetFileSize() < MainHeader::MAGIC_BYTE_SIZE + MainHeader::MAGIC_BYTE_OFFSET) { throw IOException("The file \"%s\" exists, but it is not a valid DuckDB database file!", handle.path); @@ -524,7 +524,7 @@ void SingleFileBlockManager::CheckAndAddEncryptionKey(MainHeader &main_header) { return CheckAndAddEncryptionKey(main_header, *options.encryption_options.user_key); } -void SingleFileBlockManager::CreateNewDatabase(QueryContext context) { +void SingleFileBlockManager::CreateNewDatabase(Context &context) { auto encryption_enabled = options.encryption_options.encryption_enabled; if (encryption_enabled) { // Check if we can read/write the encrypted database @@ -636,7 +636,7 @@ void SingleFileBlockManager::CreateNewDatabase(QueryContext context) { max_block = 0; } -void SingleFileBlockManager::LoadExistingDatabase(QueryContext context) { +void SingleFileBlockManager::LoadExistingDatabase(Context &context) { handle = DatabaseHandle::Open(context, db, path, options, DatabaseOpenMode::OPEN_EXISTING_FILE); handle->CheckMagicBytes(context); @@ -779,7 +779,7 @@ void SingleFileBlockManager::CheckChecksum(FileBuffer &block, uint64_t location, } } -void SingleFileBlockManager::ReadAndChecksum(QueryContext context, FileBuffer &block, uint64_t location, +void SingleFileBlockManager::ReadAndChecksum(Context &context, FileBuffer &block, uint64_t location, bool skip_block_header) const { // read the buffer from disk handle->Read(context, block, location); @@ -795,7 +795,7 @@ void SingleFileBlockManager::ReadAndChecksum(QueryContext context, FileBuffer &b CheckChecksum(block, location, delta, skip_block_header); } -void SingleFileBlockManager::ChecksumAndWrite(QueryContext context, FileBuffer &block, uint64_t location, +void SingleFileBlockManager::ChecksumAndWrite(Context &context, FileBuffer &block, uint64_t location, bool skip_block_header) const { auto delta = GetBlockHeaderSize() - Storage::DEFAULT_BLOCK_HEADER_SIZE; uint64_t checksum; @@ -875,7 +875,7 @@ void SingleFileBlockManager::Initialize(const DatabaseHeader &header, const opti SetBlockAllocSize(header.block_alloc_size); } -void SingleFileBlockManager::RewriteMainHeader(QueryContext &context, StorageVersion version_number) { +void SingleFileBlockManager::RewriteMainHeader(Context &context, StorageVersion version_number) { MainHeader main_header = ConstructMainHeader(version_number); SerializeHeaderStructure(main_header, header_buffer.GetDataMutable()); // now write the header to the file @@ -885,7 +885,7 @@ void SingleFileBlockManager::RewriteMainHeader(QueryContext &context, StorageVer handle->Sync(); } -void SingleFileBlockManager::LoadFreeList(QueryContext context) { +void SingleFileBlockManager::LoadFreeList(Context &context) { MetaBlockPointer free_pointer(free_list_id, 0); if (!free_pointer.IsValid()) { // no free list @@ -1218,7 +1218,7 @@ void SingleFileBlockManager::ReadBlock(data_ptr_t internal_buffer, uint64_t bloc void SingleFileBlockManager::ReadBlock(Block &block, bool skip_block_header) const { // read the buffer from disk auto location = GetBlockLocation(block.id); - handle->Read(QueryContext(), block, location); + handle->Read(db.GetContext(), block, location); //! calculate delta header bytes (if any) uint64_t delta = GetBlockHeaderSize() - Storage::DEFAULT_BLOCK_HEADER_SIZE; @@ -1231,7 +1231,7 @@ void SingleFileBlockManager::ReadBlock(Block &block, bool skip_block_header) con CheckChecksum(block, location, delta, skip_block_header); } -void SingleFileBlockManager::Read(QueryContext context, Block &block) { +void SingleFileBlockManager::Read(Context &context, Block &block) { D_ASSERT(block.id >= 0); D_ASSERT(!BlockIsFreeListed(block.id)); ReadAndChecksum(context, block, GetBlockLocation(block.id)); @@ -1242,7 +1242,7 @@ bool SingleFileBlockManager::BlockIsFreeListed(block_id_t block_id) { return free_list.find(block_id) != free_list.end(); } -void SingleFileBlockManager::ReadBlocks(QueryContext context, FileBuffer &buffer, block_id_t start_block, +void SingleFileBlockManager::ReadBlocks(Context &context, FileBuffer &buffer, block_id_t start_block, idx_t block_count) { D_ASSERT(start_block >= 0); D_ASSERT(block_count >= 1); @@ -1260,10 +1260,10 @@ void SingleFileBlockManager::ReadBlocks(QueryContext context, FileBuffer &buffer } void SingleFileBlockManager::Write(FileBuffer &buffer, block_id_t block_id) { - Write(QueryContext(), buffer, block_id); + Write(db.GetContext(), buffer, block_id); } -void SingleFileBlockManager::Write(QueryContext context, FileBuffer &buffer, block_id_t block_id) { +void SingleFileBlockManager::Write(Context &context, FileBuffer &buffer, block_id_t block_id) { D_ASSERT(block_id >= 0); ChecksumAndWrite(context, buffer, BLOCK_START + NumericCast(block_id) * GetBlockAllocSize()); } @@ -1366,7 +1366,7 @@ bool SingleFileBlockManager::AddFreeBlock(unique_lock &lock, block_id_t b lock.lock(); return false; } -void SingleFileBlockManager::WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound, +void SingleFileBlockManager::WriteHeader(Context &context, DatabaseHeader header, VisibilityBound bound, transaction_t read_stamp, transaction_t lowest_active_start) { auto free_list_blocks = GetFreeListBlocks(); diff --git a/src/duckdb/src/storage/standard_buffer_manager.cpp b/src/duckdb/src/storage/standard_buffer_manager.cpp index d89b0d708..126c64524 100644 --- a/src/duckdb/src/storage/standard_buffer_manager.cpp +++ b/src/duckdb/src/storage/standard_buffer_manager.cpp @@ -133,8 +133,8 @@ idx_t StandardBufferManager::GetOperatorMemoryLimit() const { } template -TempBufferPoolReservation StandardBufferManager::EvictBlocksOrThrow(QueryContext context, MemoryTag tag, - idx_t memory_delta, unique_ptr *buffer, +TempBufferPoolReservation StandardBufferManager::EvictBlocksOrThrow(Context &context, MemoryTag tag, idx_t memory_delta, + unique_ptr *buffer, const ARGS &...args) { auto r = buffer_pool.EvictBlocks(context, tag, memory_delta, buffer_pool.maximum_memory, buffer); if (!r.success) { @@ -162,7 +162,7 @@ shared_ptr StandardBufferManager::RegisterTransientMemory(const idx shared_ptr StandardBufferManager::RegisterSmallMemory(MemoryTag tag, const idx_t size) { D_ASSERT(size < GetBlockSize()); - auto reservation = EvictBlocksOrThrow(QueryContext(), tag, size, nullptr, "could not allocate block of size %s%s", + auto reservation = EvictBlocksOrThrow(db.GetContext(), tag, size, nullptr, "could not allocate block of size %s%s", StringUtil::BytesToHumanReadableString(size)); auto buffer = ConstructManagedBuffer(size, DEFAULT_BLOCK_HEADER_STORAGE_SIZE, nullptr, FileBufferType::TINY_BUFFER); @@ -178,7 +178,7 @@ shared_ptr StandardBufferManager::RegisterSmallMemory(MemoryTag tag } shared_ptr StandardBufferManager::RegisterMemory(MemoryTag tag, idx_t block_size, idx_t block_header_size, - bool can_destroy, QueryContext context) { + bool can_destroy, Context &context) { auto alloc_size = GetAllocSize(block_size + block_header_size); // Evict blocks until there is enough memory to store the buffer. @@ -195,6 +195,11 @@ shared_ptr StandardBufferManager::RegisterMemory(MemoryTag tag, idx destroy_buffer_upon, alloc_size, std::move(res)); } +shared_ptr StandardBufferManager::RegisterMemory(MemoryTag tag, idx_t block_size, idx_t block_header_size, + bool can_destroy) { + return RegisterMemory(tag, block_size, block_header_size, can_destroy, db.GetContext()); +} + shared_ptr StandardBufferManager::AllocateTemporaryMemory(MemoryTag tag, idx_t block_size, bool can_destroy) { return RegisterMemory(tag, block_size, Storage::DEFAULT_BLOCK_HEADER_SIZE, can_destroy); @@ -225,7 +230,7 @@ BufferHandle StandardBufferManager::Allocate(MemoryTag tag, idx_t block_size, bo return Pin(block); } -BufferHandle StandardBufferManager::Allocate(QueryContext context, MemoryTag tag, idx_t block_size, bool can_destroy) { +BufferHandle StandardBufferManager::Allocate(Context &context, MemoryTag tag, idx_t block_size, bool can_destroy) { auto block = RegisterMemory(tag, block_size, Storage::DEFAULT_BLOCK_HEADER_SIZE, can_destroy, context); #ifdef DUCKDB_DEBUG_DESTROY_BLOCKS @@ -235,7 +240,7 @@ BufferHandle StandardBufferManager::Allocate(QueryContext context, MemoryTag tag return Pin(context, block); } -BufferHandle StandardBufferManager::Allocate(QueryContext context, MemoryTag tag, BlockManager *block_manager, +BufferHandle StandardBufferManager::Allocate(Context &context, MemoryTag tag, BlockManager *block_manager, bool can_destroy) { auto block = RegisterMemory(tag, block_manager->GetBlockSize(), block_manager->GetBlockHeaderSize(), can_destroy, context); @@ -247,7 +252,7 @@ BufferHandle StandardBufferManager::Allocate(QueryContext context, MemoryTag tag return Pin(context, block); } -void StandardBufferManager::BatchRead(QueryContext context, PrefetchRun &run) { +void StandardBufferManager::BatchRead(Context &context, PrefetchRun &run) { idx_t block_count = run.handles.size(); // Allocate a buffer to hold the data of all blocks. @@ -336,7 +341,7 @@ StandardBufferManager::RegisterPrefetch(vector> &handles return plan; } -void StandardBufferManager::ExecutePrefetch(QueryContext context, vector &plan) { +void StandardBufferManager::ExecutePrefetch(Context &context, vector &plan) { for (auto &run : plan) { if (run.handles.size() == 1 && Settings::Get(db) != StorageBlockPrefetch::DEBUG_FORCE_ALWAYS) { @@ -347,12 +352,12 @@ void StandardBufferManager::ExecutePrefetch(QueryContext context, vector> &handles) { +void StandardBufferManager::Prefetch(Context &context, vector> &handles) { auto plan = RegisterPrefetch(handles); ExecutePrefetch(context, plan); } -vector> StandardBufferManager::CreatePrefetchTasks(QueryContext context, +vector> StandardBufferManager::CreatePrefetchTasks(Context &context, vector> &handles) { auto plan = RegisterPrefetch(handles); vector> tasks; @@ -361,16 +366,16 @@ vector> StandardBufferManager::CreatePrefetchTasks(QueryCo // the io size is the number of bytes this run will read auto io_size = run.handles.size() * run.handles[0]->GetBlockAllocSize(); tasks.push_back(make_uniq( - [this, context, run = std::move(run)]() mutable { BatchRead(context, run); }, io_size)); + [this, context = &context, run = std::move(run)]() mutable { BatchRead(*context, run); }, io_size)); } return tasks; } BufferHandle StandardBufferManager::Pin(shared_ptr &handle) { - return Pin(QueryContext(), handle); + return Pin(db.GetContext(), handle); } -BufferHandle StandardBufferManager::Pin(const QueryContext &context, shared_ptr &handle) { +BufferHandle StandardBufferManager::Pin(Context &context, shared_ptr &handle) { // we need to be careful not to return the BufferHandle to this block while holding the BlockHandle's lock // as exiting this function's scope may cause the destructor of the BufferHandle to be called while holding the lock // the destructor calls Unpin, which grabs the BlockHandle's lock again, causing a deadlock @@ -496,7 +501,7 @@ void StandardBufferManager::Unpin(shared_ptr &handle) { } void StandardBufferManager::SetMemoryLimit(idx_t limit) { - buffer_pool.SetLimit(limit, InMemoryWarning()); + buffer_pool.SetLimit(db.GetContext(), limit, InMemoryWarning()); } void StandardBufferManager::SetSwapLimit(optional_idx limit) { @@ -548,7 +553,7 @@ bool StandardBufferManager::EncryptTemporaryFiles() { return Settings::Get(db); } -void StandardBufferManager::WriteTemporaryBuffer(QueryContext context, MemoryTag tag, block_id_t block_id, +void StandardBufferManager::WriteTemporaryBuffer(Context &context, MemoryTag tag, block_id_t block_id, FileBuffer &buffer) { // WriteTemporaryBuffer assumes that we never write a buffer below DEFAULT_BLOCK_ALLOC_SIZE. RequireTemporaryDirectory(); @@ -557,7 +562,7 @@ void StandardBufferManager::WriteTemporaryBuffer(QueryContext context, MemoryTag if (buffer.AllocSize() == GetBlockAllocSize()) { idx_t eviction_size = temporary_directory.handle->GetTempFile().WriteTemporaryBuffer(context, block_id, buffer); evicted_data_per_tag[uint8_t(tag)] += eviction_size; - auto profiler = Context::TryGetQueryProfiler(context.GetContext()); + auto profiler = context.TryGetQueryProfiler(); if (profiler) { profiler->TrackBytesSpilled(eviction_size); } @@ -607,14 +612,13 @@ void StandardBufferManager::WriteTemporaryBuffer(QueryContext context, MemoryTag throw; } evicted_data_per_tag[uint8_t(tag)] += buffer.AllocSize(); - auto profiler = Context::TryGetQueryProfiler(context.GetContext()); + auto profiler = context.TryGetQueryProfiler(); if (profiler) { profiler->TrackBytesSpilled(buffer.AllocSize() + header_size); } } -unique_ptr StandardBufferManager::ReadTemporaryBuffer(QueryContext context, MemoryTag tag, - BlockHandle &block, +unique_ptr StandardBufferManager::ReadTemporaryBuffer(Context &context, MemoryTag tag, BlockHandle &block, unique_ptr reusable_buffer) { D_ASSERT(!temporary_directory.path.empty()); auto id = block.BlockId(); @@ -803,7 +807,7 @@ void StandardBufferManager::ReserveMemory(idx_t size) { return; } auto reservation = - EvictBlocksOrThrow(QueryContext(), MemoryTag::EXTENSION, size, nullptr, + EvictBlocksOrThrow(db.GetContext(), MemoryTag::EXTENSION, size, nullptr, "failed to reserve memory data of size %s%s", StringUtil::BytesToHumanReadableString(size)); reservation.size = 0; } @@ -819,7 +823,7 @@ void StandardBufferManager::FreeReservedMemory(idx_t size) { // Buffer Allocator //===--------------------------------------------------------------------===// TempBufferPoolReservation BufferAllocatorData::Reserve(idx_t size) { - return manager.EvictBlocksOrThrow(QueryContext(), MemoryTag::ALLOCATOR, size, nullptr, + return manager.EvictBlocksOrThrow(manager.GetDatabase().GetContext(), MemoryTag::ALLOCATOR, size, nullptr, "failed to allocate data of size %s%s", StringUtil::BytesToHumanReadableString(size)); } diff --git a/src/duckdb/src/storage/storage_manager.cpp b/src/duckdb/src/storage/storage_manager.cpp index 4595930f8..9290198e7 100644 --- a/src/duckdb/src/storage/storage_manager.cpp +++ b/src/duckdb/src/storage/storage_manager.cpp @@ -176,7 +176,7 @@ StorageManager::StorageManager(AttachedDatabase &db, string path_p, AttachOption auto &fs = FileSystem::Get(db); path = fs.ExpandPath(path); - auto &services = db.GetDatabase().GetContext(); + auto &services = db.GetContext(); storage_options.Initialize(services, options.options); } @@ -580,7 +580,7 @@ inline void ClearUserKey(shared_ptr const &encryption_key) { } } -void StorageManager::Initialize(QueryContext context) { +void StorageManager::Initialize(Context &context) { bool in_memory = InMemory(); if (in_memory && read_only) { throw CatalogException("Cannot launch in-memory database in read-only mode!"); @@ -622,7 +622,7 @@ SingleFileStorageManager::SingleFileStorageManager(AttachedDatabase &db, string : StorageManager(db, std::move(path), options) { } -void SingleFileStorageManager::LoadDatabase(QueryContext context) { +void SingleFileStorageManager::LoadDatabase(Context &context) { if (InMemory()) { block_manager = make_uniq(BufferManager::GetBufferManager(db), DEFAULT_BLOCK_ALLOC_SIZE, DEFAULT_BLOCK_HEADER_STORAGE_SIZE); @@ -777,7 +777,7 @@ void SingleFileStorageManager::LoadDatabase(QueryContext context) { unique_ptr timer = nullptr; // Start timing the storage load step. - auto profiler = Context::TryGetQueryProfiler(context.GetContext()); + auto profiler = context.TryGetQueryProfiler(); if (profiler) { timer = make_uniq(profiler->StartTimer()); } @@ -982,7 +982,7 @@ bool SingleFileStorageManager::IsCheckpointClean(MetaBlockPointer checkpoint_id) } unique_ptr -SingleFileStorageManager::CreateCheckpointWriter(QueryContext context, CheckpointOptions options, +SingleFileStorageManager::CreateCheckpointWriter(Context &context, CheckpointOptions options, optional_ptr checkpoint_context) { if (InMemory()) { return make_uniq(context, db, *block_manager, *this, options, checkpoint_context); @@ -1100,7 +1100,7 @@ bool SingleFileStorageManager::BindIndexesForCheckpoint(optional_ptr client_context) { if (read_only || !load_complete) { return; @@ -1131,7 +1131,7 @@ void SingleFileStorageManager::CreateCheckpoint(QueryContext context, Checkpoint // Shared by the index binds before the checkpoint and by the checkpoint transaction. unique_ptr checkpoint_connection; optional_ptr checkpoint_context; - if (should_checkpoint && Context::TryGetClientContext(context.GetContext())) { + if (should_checkpoint && context.IsClient()) { checkpoint_connection = make_uniq(Connection::CreateInternal(db.GetDatabase())); checkpoint_context = checkpoint_connection->context.get(); } @@ -1143,7 +1143,7 @@ void SingleFileStorageManager::CreateCheckpoint(QueryContext context, Checkpoint if (should_checkpoint) { try { // Start timing the checkpoint. - auto profiler = Context::TryGetQueryProfiler(context.GetContext()); + auto profiler = context.TryGetQueryProfiler(); MetricsTimer timer; if (profiler) { timer = profiler->StartTimer(); diff --git a/src/duckdb/src/storage/table/array_column_data.cpp b/src/duckdb/src/storage/table/array_column_data.cpp index 195a221e7..7864ec792 100644 --- a/src/duckdb/src/storage/table/array_column_data.cpp +++ b/src/duckdb/src/storage/table/array_column_data.cpp @@ -248,7 +248,7 @@ void ArrayColumnData::FetchRows(TransactionData transaction, ColumnFetchState &s idx_t result_offset) { // Create state for validity & child column if (state.child_states.empty()) { - state.child_states.push_back(make_uniq()); + state.child_states.push_back(make_uniq(state.context)); } // Fetch validity @@ -262,7 +262,7 @@ void ArrayColumnData::FetchRows(TransactionData transaction, ColumnFetchState &s for (idx_t idx = 0; idx < fetch_count; idx++) { // We need to fetch between [row_id * array_size, (row_id + 1) * array_size) - ColumnScanState child_state(nullptr); + ColumnScanState child_state(nullptr, state.context); child_state.Initialize(state.context, child_type, nullptr); const auto row_id = offsets[sel.get_index(idx)]; @@ -387,7 +387,7 @@ void ArrayColumnData::InitializeColumn(PersistentColumnData &column_data, BaseSt this->count = validity->count.load(); } -void ArrayColumnData::GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector col_path, +void ArrayColumnData::GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector col_path, vector &result, const ColumnSegmentInfoScanOptions &options) { col_path.push_back(0); diff --git a/src/duckdb/src/storage/table/column_data.cpp b/src/duckdb/src/storage/table/column_data.cpp index 263e59c80..22a472e97 100644 --- a/src/duckdb/src/storage/table/column_data.cpp +++ b/src/duckdb/src/storage/table/column_data.cpp @@ -33,6 +33,7 @@ #include "duckdb/storage/table/data_table_info.hpp" #include "duckdb/storage/table/append_state.hpp" #include "duckdb/storage/table/scan_state.hpp" +#include "duckdb/main/database.hpp" namespace duckdb { @@ -404,7 +405,7 @@ idx_t ColumnData::GetVectorCount(idx_t vector_index) const { } void ColumnData::ScanCommittedRange(idx_t row_group_start, idx_t offset_in_row_group, idx_t s_count, Vector &result) { - ColumnScanState child_state(nullptr); + ColumnScanState child_state(nullptr, GetDatabase().GetContext()); InitializeScanWithOffset(child_state, offset_in_row_group); bool has_updates = HasUpdates(); ScanVector(child_state, result, s_count, ScanVectorType::SCAN_FLAT_VECTOR); @@ -494,7 +495,7 @@ FilterPropagateResult ColumnData::CheckZonemap(ColumnScanState &state, const Sca : *state.current; // segment rows are relative to the row group checked_end = checked_segment.GetRowStart() + checked_segment.GetNode().count; - return CheckSegmentStatistics(state.context.GetClientContext(), checked_segment, expr_filter); + return CheckSegmentStatistics(state.context.get().TryGetClientContext(), checked_segment, expr_filter); } FilterPropagateResult ColumnData::CheckZonemapAt(ColumnScanState &state, const ScanFilter &filter, idx_t row, @@ -507,7 +508,7 @@ FilterPropagateResult ColumnData::CheckZonemapAt(ColumnScanState &state, const S auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter.filter, "ColumnData::CheckZonemapAt"); auto segment = data.GetSegment(row); checked_end = segment->GetRowStart() + segment->GetNode().count; - return CheckSegmentStatistics(state.context.GetClientContext(), *segment, expr_filter); + return CheckSegmentStatistics(state.context.get().TryGetClientContext(), *segment, expr_filter); } FilterPropagateResult ColumnData::CheckSegmentStatistics(optional_ptr context, @@ -801,13 +802,12 @@ void ColumnData::FetchScannedRows(ColumnScanState &state, const SelectionVector result_offset); } -void ColumnData::FetchBaseRows(const QueryContext &context, const idx_t *offsets, const SelectionVector &sel, - idx_t fetch_count, Vector &result, idx_t result_offset) { +void ColumnData::FetchBaseRows(Context &context, const idx_t *offsets, const SelectionVector &sel, idx_t fetch_count, + Vector &result, idx_t result_offset) { optional_ptr> current_segment; idx_t segment_start = 0; idx_t segment_end = 0; - ColumnScanState scan_state(nullptr); - scan_state.context = context; + ColumnScanState scan_state(nullptr, context); scan_state.string_scan_type = StringScanType::COPY_STRINGS; SelectionVector window_sel; idx_t idx = 0; @@ -879,7 +879,8 @@ void ColumnData::FetchBaseRows(const row_t *row_ids, idx_t count, Vector &result } offsets[i] = UnsafeNumericCast(row_ids[i]) - row_group_start; } - FetchBaseRows(QueryContext(), offsets.data(), *FlatVector::IncrementalSelectionVector(), count, result, 0); + FetchBaseRows(GetDatabase().GetContext(), offsets.data(), *FlatVector::IncrementalSelectionVector(), count, result, + 0); } void ColumnData::Update(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, @@ -1443,7 +1444,7 @@ struct ListBlockIds : public BlockIdVisitor { vector &block_ids; }; -void ColumnData::GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector col_path, +void ColumnData::GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector col_path, vector &result, const ColumnSegmentInfoScanOptions &options) { D_ASSERT(!col_path.empty()); diff --git a/src/duckdb/src/storage/table/column_data_checkpointer.cpp b/src/duckdb/src/storage/table/column_data_checkpointer.cpp index c62f760ea..93d4b05bb 100644 --- a/src/duckdb/src/storage/table/column_data_checkpointer.cpp +++ b/src/duckdb/src/storage/table/column_data_checkpointer.cpp @@ -98,7 +98,7 @@ void ColumnDataCheckpointer::ScanSegments(const std::function &c // TODO: scan all the nodes from all segments, no need for CheckpointScan to virtualize this I think.. for (auto &segment_node : col_data.data.SegmentNodes()) { auto &segment = segment_node.GetNode(); - ColumnScanState scan_state(nullptr); + ColumnScanState scan_state(nullptr, col_data.GetDatabase().GetContext()); scan_state.current = segment_node; segment.InitializeScan(scan_state); diff --git a/src/duckdb/src/storage/table/geo_column_data.cpp b/src/duckdb/src/storage/table/geo_column_data.cpp index e9554ced2..bd3b990fd 100644 --- a/src/duckdb/src/storage/table/geo_column_data.cpp +++ b/src/duckdb/src/storage/table/geo_column_data.cpp @@ -14,6 +14,7 @@ #include "duckdb/main/settings.hpp" #include "duckdb/storage/data_table.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/main/database.hpp" namespace duckdb { @@ -383,7 +384,7 @@ unique_ptr GeoColumnData::Checkpoint(const RowGroup &row_ // Setup scan from the old column DataChunk scan_chunk; - ColumnScanState scan_state(nullptr); + ColumnScanState scan_state(nullptr, GetDatabase().GetContext()); scan_chunk.Initialize(Allocator::DefaultAllocator(), {base_column->type}, STANDARD_VECTOR_SIZE); InitializeScan(scan_state); @@ -485,7 +486,7 @@ unique_ptr GeoColumnData::Checkpoint(const RowGroup &row_ // Setup scan from the old column DataChunk scan_chunk; - ColumnScanState scan_state(nullptr); + ColumnScanState scan_state(nullptr, GetDatabase().GetContext()); scan_chunk.Initialize(Allocator::DefaultAllocator(), {base_column->type}, STANDARD_VECTOR_SIZE); InitializeScan(scan_state); @@ -603,7 +604,7 @@ idx_t GeoColumnData::GetMaxEntry() { return base_column->GetMaxEntry(); } -void GeoColumnData::GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector col_path, +void GeoColumnData::GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector col_path, vector &result, const ColumnSegmentInfoScanOptions &options) { return base_column->GetColumnSegmentInfo(context, row_group_index, col_path, result, options); diff --git a/src/duckdb/src/storage/table/in_memory_checkpoint.cpp b/src/duckdb/src/storage/table/in_memory_checkpoint.cpp index 90e0e2442..7c2a012d1 100644 --- a/src/duckdb/src/storage/table/in_memory_checkpoint.cpp +++ b/src/duckdb/src/storage/table/in_memory_checkpoint.cpp @@ -19,7 +19,7 @@ namespace duckdb { //===--------------------------------------------------------------------===// // In-Memory Checkpoint Writer //===--------------------------------------------------------------------===// -InMemoryCheckpointer::InMemoryCheckpointer(QueryContext context, AttachedDatabase &db, BlockManager &block_manager, +InMemoryCheckpointer::InMemoryCheckpointer(Context &context, AttachedDatabase &db, BlockManager &block_manager, StorageManager &storage_manager, CheckpointOptions options_p, optional_ptr checkpoint_context) : CheckpointWriter(db, context, checkpoint_context), diff --git a/src/duckdb/src/storage/table/list_column_data.cpp b/src/duckdb/src/storage/table/list_column_data.cpp index aae750a48..b48156440 100644 --- a/src/duckdb/src/storage/table/list_column_data.cpp +++ b/src/duckdb/src/storage/table/list_column_data.cpp @@ -12,6 +12,7 @@ #include "duckdb/storage/table/column_checkpoint_state.hpp" #include "duckdb/storage/table/append_state.hpp" #include "duckdb/storage/table/scan_state.hpp" +#include "duckdb/main/database.hpp" namespace duckdb { @@ -98,7 +99,7 @@ uint64_t ListColumnData::FetchListOffset(idx_t row_idx) { if (row_idx >= count) { throw DataCorruptionException("Corrupted database: list offset row ID is out of range"); } - ColumnScanState offset_state(nullptr); + ColumnScanState offset_state(nullptr, GetDatabase().GetContext()); ColumnData::InitializeScanWithOffset(offset_state, row_idx); Vector result(LogicalType::UBIGINT, 1); ScanVector(offset_state, result, 1, ScanVectorType::SCAN_FLAT_VECTOR); @@ -336,7 +337,7 @@ void ListColumnData::FetchRows(TransactionData transaction, ColumnFetchState &st idx_t result_offset) { // insert the validity child state if (state.child_states.empty()) { - auto child_state = make_uniq(); + auto child_state = make_uniq(state.context); state.child_states.push_back(std::move(child_state)); } @@ -383,7 +384,7 @@ void ListColumnData::FetchRows(TransactionData transaction, ColumnFetchState &st // now we need to read from the child all the elements between [offset...length] auto child_scan_count = list_entry.length; if (child_scan_count > 0) { - ColumnScanState child_state(nullptr); + ColumnScanState child_state(nullptr, state.context); auto &child_type = ListType::GetChildType(result.GetType()); Vector child_scan(child_type, child_scan_count); // seek the scan towards the specified position and read [length] entries @@ -595,7 +596,7 @@ void ListColumnData::InitializeColumn(PersistentColumnData &column_data, BaseSta child_column->InitializeColumn(column_data.child_columns[1], child_stats); } -void ListColumnData::GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector col_path, +void ListColumnData::GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector col_path, vector &result, const ColumnSegmentInfoScanOptions &options) { ColumnData::GetColumnSegmentInfo(context, row_group_index, col_path, result, options); diff --git a/src/duckdb/src/storage/table/row_group.cpp b/src/duckdb/src/storage/table/row_group.cpp index 0f74d7835..d210f4416 100644 --- a/src/duckdb/src/storage/table/row_group.cpp +++ b/src/duckdb/src/storage/table/row_group.cpp @@ -257,9 +257,8 @@ void RowGroup::InitializeEmpty(const vector &types, ColumnDataType } void ColumnScanState::PushDownCast(const LogicalType &original_type, const LogicalType &cast_type) { - D_ASSERT(context.Valid()); D_ASSERT(!expression_state); - auto &client_context = *context.GetClientContext(); + auto &client_context = *context.get().TryGetClientContext(); auto input = make_uniq(original_type, 0ULL); auto cast_expression = BoundCastExpression::AddCastToType(client_context, std::move(input), cast_type); @@ -270,7 +269,7 @@ void ColumnScanState::PushDownCast(const LogicalType &original_type, const Logic expression_state->expression = std::move(cast_expression); } -void ColumnScanState::Initialize(const QueryContext &context_p, const LogicalType &type, const StorageIndex &column_id, +void ColumnScanState::Initialize(Context &context_p, const LogicalType &type, const StorageIndex &column_id, optional_ptr options) { auto &children = column_id.GetChildIndexes(); // Register the options in the state @@ -304,7 +303,7 @@ void ColumnScanState::Initialize(const QueryContext &context_p, const LogicalTyp auto &struct_children = StructType::GetChildTypes(type); child_states.reserve(struct_children.size() + 1); for (idx_t i = 0; i <= struct_children.size(); i++) { - child_states.emplace_back(parent); + child_states.emplace_back(parent, context); } if (children.empty()) { @@ -315,7 +314,6 @@ void ColumnScanState::Initialize(const QueryContext &context_p, const LogicalTyp } } else { if (storage_index.IsPushdownExtract()) { - D_ASSERT(context.Valid()); scan_child_column.resize(1, true); D_ASSERT(children.size() == 1); auto &child = children[0]; @@ -340,37 +338,36 @@ void ColumnScanState::Initialize(const QueryContext &context_p, const LogicalTyp } else if (type.InternalType() == PhysicalType::LIST) { // validity + list child for (idx_t i = 0; i < 2; i++) { - child_states.emplace_back(parent); + child_states.emplace_back(parent, context); } child_states[1].Initialize(context, ListType::GetChildType(type), options); child_states[0].scan_options = options; } else if (type.InternalType() == PhysicalType::ARRAY) { // validity + array child for (idx_t i = 0; i < 2; i++) { - child_states.emplace_back(parent); + child_states.emplace_back(parent, context); } child_states[0].scan_options = options; child_states[1].Initialize(context, ArrayType::GetChildType(type), options); } else { // validity - child_states.emplace_back(parent); + child_states.emplace_back(parent, context); child_states[0].scan_options = options; } } -void ColumnScanState::Initialize(const QueryContext &context_p, const LogicalType &type, - optional_ptr options) { +void ColumnScanState::Initialize(Context &context_p, const LogicalType &type, optional_ptr options) { auto column_id = StorageIndex(0); Initialize(context_p, type, column_id, options); } -void CollectionScanState::Initialize(const QueryContext &context_p, const vector &types) { - context = context_p; +void CollectionScanState::Initialize(Context &context_p, const vector &types) { + context = &context_p; auto &column_ids = GetColumnIds(); D_ASSERT(column_scans.empty()); column_scans.reserve(column_ids.size()); for (idx_t i = 0; i < column_ids.size(); i++) { - column_scans.emplace_back(*this); + column_scans.emplace_back(*this, context_p); } for (idx_t i = 0; i < column_ids.size(); i++) { if (column_ids[i].IsRowIdColumn() || column_ids[i].IsRowNumberColumn()) { @@ -378,7 +375,7 @@ void CollectionScanState::Initialize(const QueryContext &context_p, const vector } auto index = column_ids[i].GetPrimaryIndex(); auto &type = types[index]; - column_scans[i].Initialize(context, type, column_ids[i], &GetOptions()); + column_scans[i].Initialize(*context, type, column_ids[i], &GetOptions()); } } @@ -850,7 +847,7 @@ void RowGroup::PrefetchScanIO(CollectionScanState &state, idx_t row_count) const PrefetchState prefetch_state; const idx_t start_row = state.vector_index * STANDARD_VECTOR_SIZE; CollectScanBlocks(state, start_row, start_row + row_count, prefetch_state); - GetBlockManager().buffer_manager.Prefetch(state.context, prefetch_state.blocks); + GetBlockManager().buffer_manager.Prefetch(*state.context, prefetch_state.blocks); } vector> RowGroup::CollectScanIOTasks(CollectionScanState &state, idx_t row_count) const { @@ -860,7 +857,7 @@ vector> RowGroup::CollectScanIOTasks(CollectionScanState & PrefetchState prefetch_state; const idx_t start_row = state.vector_index * STANDARD_VECTOR_SIZE; CollectScanBlocks(state, start_row, start_row + row_count, prefetch_state); - return GetBlockManager().buffer_manager.CreatePrefetchTasks(state.context, prefetch_state.blocks); + return GetBlockManager().buffer_manager.CreatePrefetchTasks(*state.context, prefetch_state.blocks); } vector> RowGroup::CollectAssignmentIOTasks(CollectionScanState &state) const { @@ -869,7 +866,7 @@ vector> RowGroup::CollectAssignmentIOTasks(CollectionScanS } PrefetchState prefetch_state; CollectAssignmentBlocks(state, prefetch_state); - return GetBlockManager().buffer_manager.CreatePrefetchTasks(state.context, prefetch_state.blocks); + return GetBlockManager().buffer_manager.CreatePrefetchTasks(*state.context, prefetch_state.blocks); } void RowGroup::CollectAssignmentBlocks(CollectionScanState &state, PrefetchState &prefetch_state) const { @@ -2126,8 +2123,8 @@ PartitionStatistics RowGroup::GetPartitionStats(SegmentNode &row_group //===--------------------------------------------------------------------===// // GetColumnSegmentInfo //===--------------------------------------------------------------------===// -void RowGroup::GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, - vector &result, const ColumnSegmentInfoScanOptions &options) { +void RowGroup::GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector &result, + const ColumnSegmentInfoScanOptions &options) { for (idx_t col_idx = 0; col_idx < GetColumnCount(); col_idx++) { if (options.loaded_segments_only && !ColumnIsLoaded(col_idx)) { // column is not loaded - skip it diff --git a/src/duckdb/src/storage/table/row_group_collection.cpp b/src/duckdb/src/storage/table/row_group_collection.cpp index 245144b73..52dd34aba 100644 --- a/src/duckdb/src/storage/table/row_group_collection.cpp +++ b/src/duckdb/src/storage/table/row_group_collection.cpp @@ -32,6 +32,7 @@ #include "duckdb/logging/log_type.hpp" #include "duckdb/logging/logger.hpp" #include "duckdb/storage/buffer_manager.hpp" +#include "duckdb/main/database.hpp" namespace duckdb { @@ -322,7 +323,7 @@ void RowGroupCollection::Verify() { //===--------------------------------------------------------------------===// // Scan //===--------------------------------------------------------------------===// -void RowGroupCollection::InitializeScan(const QueryContext &context, CollectionScanState &state, +void RowGroupCollection::InitializeScan(Context &context, CollectionScanState &state, const vector &column_ids, optional_ptr table_filters) { state.row_groups = GetRowGroups(); @@ -339,7 +340,7 @@ void RowGroupCollection::InitializeCreateIndexScan(CreateIndexScanState &state) state.segment_lock = state.row_groups->Lock(); } -void RowGroupCollection::InitializeScanWithOffset(const QueryContext &context, CollectionScanState &state, +void RowGroupCollection::InitializeScanWithOffset(Context &context, CollectionScanState &state, const vector &column_ids, idx_t start_row, idx_t end_row) { state.row_groups = GetRowGroups(); @@ -545,7 +546,7 @@ RowGroupIterationHelper::RowGroupIterator::RowGroupIterator(optional_ptr(); state->Initialize(column_ids, nullptr); - collection->InitializeScan(QueryContext(), state->local_state, column_ids, nullptr); + collection->InitializeScan(collection->GetDatabase().GetContext(), state->local_state, column_ids, nullptr); // scan the first chunk this->operator++(); } @@ -1129,9 +1130,9 @@ void RowGroupCollection::Update(TransactionData transaction, DuckTableEntry &tab } } -void RowGroupCollection::RemoveFromIndexes(const QueryContext &context, TableIndexList &indexes, - Vector &row_identifiers, idx_t count, IndexRemovalType removal_type, - optional_idx active_checkpoint, VisibilityBound bound) { +void RowGroupCollection::RemoveFromIndexes(Context &context, TableIndexList &indexes, Vector &row_identifiers, + idx_t count, IndexRemovalType removal_type, optional_idx active_checkpoint, + VisibilityBound bound) { // Collect the indexed columns of the indexes we remove from. auto indexed_column_id_set = indexes.GetIndexedColumns(bound); if (indexed_column_id_set.empty()) { @@ -1153,7 +1154,7 @@ void RowGroupCollection::RemoveFromIndexes(const QueryContext &context, TableInd DataChunk fetch_chunk; fetch_chunk.Initialize(GetAllocator(), column_types); - ColumnFetchState state; + ColumnFetchState state(context); state.fetch_type = FetchType::FORCE_FETCH; TransactionData commit_transaction(MAX_TRANSACTION_ID, VisibilityBound::Before(MAX_COMMIT_ID)); Fetch(commit_transaction, fetch_chunk, column_ids, row_identifiers, count, state); @@ -1481,7 +1482,7 @@ class VacuumTask : public BaseCheckpointTask { TableScanState scan_state; scan_state.Initialize(column_ids); - scan_state.table_state.Initialize(QueryContext(), types); + scan_state.table_state.Initialize(checkpoint_state.writer.GetContext(), types); scan_state.table_state.max_row = idx_t(-1); idx_t merged_groups = 0; idx_t total_row_groups = vacuum_state.row_group_counts.size(); @@ -2360,7 +2361,7 @@ vector RowGroupCollection::GetPartitionStats(TransactionDat //===--------------------------------------------------------------------===// // GetColumnSegmentInfo //===--------------------------------------------------------------------===// -vector RowGroupCollection::GetColumnSegmentInfo(const QueryContext &context, +vector RowGroupCollection::GetColumnSegmentInfo(Context &context, const ColumnSegmentInfoScanOptions &options) const { vector result; ColumnSegmentInfoScanState state; @@ -2380,7 +2381,7 @@ void RowGroupCollection::InitializeColumnSegmentInfoScan(ColumnSegmentInfoScanSt state.current_row_group = state.row_groups->GetRootSegment(); } -bool RowGroupCollection::ScanColumnSegmentInfo(const QueryContext &context, ColumnSegmentInfoScanState &state, +bool RowGroupCollection::ScanColumnSegmentInfo(Context &context, ColumnSegmentInfoScanState &state, vector &result) const { if (!state.current_row_group) { return false; @@ -2508,8 +2509,8 @@ shared_ptr RowGroupCollection::AlterType(ClientContext &cont return result; } -void RowGroupCollection::VerifyNewConstraint(const QueryContext &context, DuckTransaction &transaction, - DataTable &parent, const BoundConstraint &constraint) { +void RowGroupCollection::VerifyNewConstraint(Context &context, DuckTransaction &transaction, DataTable &parent, + const BoundConstraint &constraint) { if (total_rows == 0) { return; } diff --git a/src/duckdb/src/storage/table/scan_state.cpp b/src/duckdb/src/storage/table/scan_state.cpp index b5bbc087a..acc899edb 100644 --- a/src/duckdb/src/storage/table/scan_state.cpp +++ b/src/duckdb/src/storage/table/scan_state.cpp @@ -387,7 +387,7 @@ void CollectionScanState::InitializeColumnScans() { bool CollectionScanState::InitializeRowGroupScan(SegmentNode &node, shared_ptr payload, idx_t vector_offset, idx_t end_row) { - if (!payload->CheckZonemap(context.GetClientContext(), GetFilterInfo(), node.GetRowStart())) { + if (!payload->CheckZonemap(Context::TryGetClientContext(context), GetFilterInfo(), node.GetRowStart())) { return false; } D_ASSERT(prepared_vector.prepare_state == VectorPrepareState::NONE); @@ -432,7 +432,7 @@ bool CollectionScanState::SetAssignment(const RowGroupScanAssignment &assignment D_ASSERT(assignment.pinned_row_group); ReleasePins(); if (column_scans.empty()) { - Initialize(assignment.context, assignment.pinned_row_group->GetCollection().GetTypes()); + Initialize(*assignment.context, assignment.pinned_row_group->GetCollection().GetTypes()); } AssignSharedPointer(row_groups, assignment.row_groups); auto node = assignment.row_group; @@ -468,7 +468,7 @@ void CollectionScanState::PrepareAssignmentBlocks(PrefetchState &blocks, vector< InitializeColumnScans(); pinned_row_group->CollectAssignmentBlocks(*this, blocks); if (prefetch) { - tasks = pinned_row_group->GetBlockManager().buffer_manager.CreatePrefetchTasks(context, blocks.blocks); + tasks = pinned_row_group->GetBlockManager().buffer_manager.CreatePrefetchTasks(*context, blocks.blocks); } } @@ -556,7 +556,8 @@ bool CollectionScanState::RecheckPreparedRowGroup() { if (!row_group || prepared_vector.prepare_state == VectorPrepareState::NONE) { return true; } - if (pinned_row_group->CheckZonemap(context.GetClientContext(), GetFilterInfo(), row_group->GetRowStart())) { + if (pinned_row_group->CheckZonemap(Context::TryGetClientContext(context), GetFilterInfo(), + row_group->GetRowStart())) { return true; } // the prepared vector was counted as scanned when it was prepared, it is never decoded diff --git a/src/duckdb/src/storage/table/standard_column_data.cpp b/src/duckdb/src/storage/table/standard_column_data.cpp index 85b9e925a..5e1c212cd 100644 --- a/src/duckdb/src/storage/table/standard_column_data.cpp +++ b/src/duckdb/src/storage/table/standard_column_data.cpp @@ -216,7 +216,7 @@ void StandardColumnData::FetchRows(TransactionData transaction, ColumnFetchState const StorageIndex &storage_index, const idx_t *offsets, const SelectionVector &sel, idx_t fetch_count, Vector &result, idx_t result_offset) { if (state.child_states.empty()) { - state.child_states.emplace_back(make_uniq()); + state.child_states.emplace_back(make_uniq(state.context)); } // Bulk fetch the data and the validity in two passes. FetchRowsAtSegmentLevel(transaction, state, offsets, sel, fetch_count, result, result_offset); @@ -365,7 +365,7 @@ void StandardColumnData::InitializeColumn(PersistentColumnData &column_data, Bas } } -void StandardColumnData::GetColumnSegmentInfo(const QueryContext &context, duckdb::idx_t row_group_index, +void StandardColumnData::GetColumnSegmentInfo(Context &context, duckdb::idx_t row_group_index, vector col_path, vector &result, const ColumnSegmentInfoScanOptions &options) { ColumnData::GetColumnSegmentInfo(context, row_group_index, col_path, result, options); diff --git a/src/duckdb/src/storage/table/struct_column_data.cpp b/src/duckdb/src/storage/table/struct_column_data.cpp index e1f963ba1..f19efb6b4 100644 --- a/src/duckdb/src/storage/table/struct_column_data.cpp +++ b/src/duckdb/src/storage/table/struct_column_data.cpp @@ -151,7 +151,6 @@ static Vector &GetFieldVectorForScan(Vector &result, optional_idx field_index) { static void ScanChild(ColumnScanState &state, Vector &result, const std::function &callback) { if (state.expression_state) { auto &expression_state = *state.expression_state; - D_ASSERT(state.context.Valid()); auto &executor = expression_state.executor; auto &target = expression_state.target; auto &input = expression_state.input; @@ -352,8 +351,7 @@ void StructColumnData::FetchRows(TransactionData transaction, ColumnFetchState & if (!child_storage_index.HasChildren() && child_storage_index.HasType() && child_storage_index.GetType() != child_type) { auto &cast_set = CastFunctionSet::Get(GetDatabase()); - auto context = state.context.GetContext(); - auto cast_input = context ? GetCastFunctionInput(*context) : GetCastFunctionInput::Default(); + GetCastFunctionInput cast_input(state.context); for (idx_t idx = 0; idx < fetch_count; idx++) { const idx_t offset = offsets[sel.get_index(idx)]; Vector intermediate(child_type, 1); @@ -535,7 +533,7 @@ void StructColumnData::InitializeColumn(PersistentColumnData &column_data, BaseS this->count = validity->count.load(); } -void StructColumnData::GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector col_path, +void StructColumnData::GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector col_path, vector &result, const ColumnSegmentInfoScanOptions &options) { col_path.push_back(0); diff --git a/src/duckdb/src/storage/table/variant_column_data.cpp b/src/duckdb/src/storage/table/variant_column_data.cpp index bbed61537..b273c38ce 100644 --- a/src/duckdb/src/storage/table/variant_column_data.cpp +++ b/src/duckdb/src/storage/table/variant_column_data.cpp @@ -23,6 +23,7 @@ #include "duckdb/storage/storage_manager.hpp" #include "duckdb/transaction/duck_transaction.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/main/database.hpp" namespace duckdb { @@ -164,16 +165,16 @@ void VariantColumnData::CreateScanStates(ColumnScanState &state) { //! Re-initialize the scan state, since VARIANT can have a different shape for every RowGroup state.child_states.clear(); - state.child_states.emplace_back(state.parent); + state.child_states.emplace_back(state.parent, state.context); state.child_states[0].scan_options = state.scan_options; auto unshredded_type = VariantShredding::GetUnshreddedType(); - state.child_states.emplace_back(state.parent); + state.child_states.emplace_back(state.parent, state.context); state.child_states[1].Initialize(state.context, unshredded_type, state.scan_options); if (IsShredded()) { auto &shredded_column = sub_columns[1]; - state.child_states.emplace_back(state.parent); + state.child_states.emplace_back(state.parent, state.context); if (state.storage_index.IsPushdownExtract()) { StorageIndex struct_extract; if (PushdownShreddedFieldExtract(state.storage_index.GetChildIndex(0), struct_extract)) { @@ -587,8 +588,7 @@ void VariantColumnData::FetchRows(TransactionData transaction, ColumnFetchState //! Need to perform the cast here as well auto &cast_set = CastFunctionSet::Get(GetDatabase()); - auto context = state.context.GetContext(); - auto cast_input = context ? GetCastFunctionInput(*context) : GetCastFunctionInput::Default(); + GetCastFunctionInput cast_input(state.context); auto fetched_row = extracted_variant.GetValue(0).CastAs(cast_set, cast_input, result.GetType()); result.SetValue(result_idx, fetched_row); } @@ -760,7 +760,7 @@ vector> VariantColumnData::WriteShreddedData(const RowGro ColumnAppendState shredded_append_state; shredded->InitializeAppend(shredded_append_state); - ColumnScanState scan_state(nullptr); + ColumnScanState scan_state(nullptr, GetDatabase().GetContext()); InitializeScan(scan_state); //! Scan + transform + append @@ -795,7 +795,7 @@ LogicalType VariantColumnData::GetShreddedType() { scan_chunk.Initialize(Allocator::DefaultAllocator(), {LogicalType::VARIANT()}, STANDARD_VECTOR_SIZE); auto &scan_vector = scan_chunk.data[0]; - ColumnScanState scan_state(nullptr); + ColumnScanState scan_state(nullptr, GetDatabase().GetContext()); InitializeScan(scan_state); idx_t total_count = count.load(); idx_t vector_index = 0; @@ -955,7 +955,7 @@ void VariantColumnData::InitializeColumn(PersistentColumnData &column_data, Base this->count = validity->count.load(); } -void VariantColumnData::GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector col_path, +void VariantColumnData::GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector col_path, vector &result, const ColumnSegmentInfoScanOptions &options) { col_path.push_back(0); diff --git a/src/duckdb/src/storage/temporary_file_manager.cpp b/src/duckdb/src/storage/temporary_file_manager.cpp index 33211ee99..32f4d1c8b 100644 --- a/src/duckdb/src/storage/temporary_file_manager.cpp +++ b/src/duckdb/src/storage/temporary_file_manager.cpp @@ -238,7 +238,7 @@ FileHandle &TemporaryFileHandle::GetIOHandle(data_ptr_t buffer, const idx_t size return *buffered_handle; } -unique_ptr TemporaryFileHandle::ReadTemporaryBuffer(QueryContext context, +unique_ptr TemporaryFileHandle::ReadTemporaryBuffer(Context &context, const TemporaryFileIndex &index_in_file, unique_ptr buffer) { auto block_index = index_in_file.block_index.GetIndex(); @@ -296,7 +296,7 @@ unique_ptr TemporaryFileHandle::ReadTemporaryBuffer(QueryContext con return buffer; } -void TemporaryFileHandle::WriteTemporaryBuffer(QueryContext context, FileBuffer &buffer, const idx_t block_index, +void TemporaryFileHandle::WriteTemporaryBuffer(Context &context, FileBuffer &buffer, const idx_t block_index, AllocatedData &compressed_buffer) { // We group DEFAULT_BLOCK_ALLOC_SIZE blocks into the same file. D_ASSERT(buffer.AllocSize() == BufferManager::GetBufferManager(db).GetBlockAllocSize()); @@ -535,7 +535,7 @@ TemporaryFileManager::~TemporaryFileManager() { TemporaryFileManager::TemporaryFileManagerLock::TemporaryFileManagerLock(mutex &mutex) : lock(mutex) { } -idx_t TemporaryFileManager::WriteTemporaryBuffer(QueryContext context, block_id_t block_id, FileBuffer &buffer) { +idx_t TemporaryFileManager::WriteTemporaryBuffer(Context &context, block_id_t block_id, FileBuffer &buffer) { // We group DEFAULT_BLOCK_ALLOC_SIZE blocks into the same file. D_ASSERT(buffer.AllocSize() == BufferManager::GetBufferManager(db).GetBlockAllocSize()); @@ -693,7 +693,7 @@ bool TemporaryFileManager::IsEncrypted() const { return Settings::Get(db); } -unique_ptr TemporaryFileManager::ReadTemporaryBuffer(QueryContext context, block_id_t id, +unique_ptr TemporaryFileManager::ReadTemporaryBuffer(Context &context, block_id_t id, unique_ptr reusable_buffer, idx_t *eviction_size) { TemporaryFileIndex index; diff --git a/src/duckdb/src/storage/wal_replay.cpp b/src/duckdb/src/storage/wal_replay.cpp index e165398b8..04f407efc 100644 --- a/src/duckdb/src/storage/wal_replay.cpp +++ b/src/duckdb/src/storage/wal_replay.cpp @@ -354,7 +354,7 @@ class WriteAheadLogDeserializer { //===--------------------------------------------------------------------===// struct WriteAheadLogReplayer { public: - WriteAheadLogReplayer(QueryContext context, StorageManager &storage_manager, const string &wal_path); + WriteAheadLogReplayer(Context &context, StorageManager &storage_manager, const string &wal_path); unique_ptr Replay(); @@ -367,20 +367,20 @@ struct WriteAheadLogReplayer { const string &recovery_path, unique_ptr checkpoint_handle); private: - QueryContext context; + Context &context; StorageManager &storage_manager; AttachedDatabase &database; const string &main_wal_path; FileSystem &fs; }; -unique_ptr WriteAheadLog::Replay(QueryContext context, StorageManager &storage_manager, +unique_ptr WriteAheadLog::Replay(Context &context, StorageManager &storage_manager, const string &main_wal_path) { WriteAheadLogReplayer wal_replay(context, storage_manager, main_wal_path); return wal_replay.Replay(); } -WriteAheadLogReplayer::WriteAheadLogReplayer(QueryContext context, StorageManager &storage_manager, +WriteAheadLogReplayer::WriteAheadLogReplayer(Context &context, StorageManager &storage_manager, const string &main_wal_path) : context(context), storage_manager(storage_manager), database(storage_manager.GetAttached()), main_wal_path(main_wal_path), fs(FileSystem::Get(storage_manager.GetAttached())) { @@ -412,7 +412,7 @@ void WriteAheadLogReplayer::CopyOverWAL(BufferedFileReader &reader, FileHandle & if (read_count == 0) { break; } - reader.ReadData(context, buffer, read_count); + reader.ReadData(buffer, read_count); target.Write(buffer, read_count); } @@ -520,7 +520,7 @@ unique_ptr WriteAheadLogReplayer::ReplayLog(unique_ptrAddToMetricCounter(MetricStorageWALReplayEntryCount::Name, replay_entry_count); } diff --git a/src/duckdb/src/storage/write_ahead_log.cpp b/src/duckdb/src/storage/write_ahead_log.cpp index dace5860f..07ba7a35f 100644 --- a/src/duckdb/src/storage/write_ahead_log.cpp +++ b/src/duckdb/src/storage/write_ahead_log.cpp @@ -56,7 +56,7 @@ BufferedFileWriter &WriteAheadLog::Initialize() { lock_guard lock(wal_lock); if (!writer) { writer = - make_uniq(FileSystem::Get(GetDatabase()), wal_path, + make_uniq(FileSystem::Get(GetDatabase()), GetDatabase().GetContext(), wal_path, FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE | FileFlags::FILE_FLAGS_APPEND | FileFlags::FILE_FLAGS_MULTI_CLIENT_ACCESS); if (init_state == WALInitState::UNINITIALIZED_REQUIRES_TRUNCATE) { diff --git a/src/duckdb/src/transaction/cleanup_state.cpp b/src/duckdb/src/transaction/cleanup_state.cpp index 2502bf345..7623ccf20 100644 --- a/src/duckdb/src/transaction/cleanup_state.cpp +++ b/src/duckdb/src/transaction/cleanup_state.cpp @@ -12,13 +12,16 @@ #include "duckdb/storage/table/update_segment.hpp" #include "duckdb/storage/table/row_version_manager.hpp" #include "duckdb/transaction/commit_state.hpp" +#include "duckdb/transaction/duck_transaction.hpp" +#include "duckdb/transaction/transaction_manager.hpp" +#include "duckdb/main/attached_database.hpp" namespace duckdb { CleanupState::CleanupState(DuckTransaction &transaction, VisibilityBound lowest_visibility_bound, ActiveTransactionState transaction_state) : lowest_visibility_bound(lowest_visibility_bound), transaction_state(transaction_state), - index_data_remover(transaction, QueryContext(), IndexRemovalType::DELETED_ROWS_IN_USE) { + index_data_remover(transaction, transaction.manager.GetDB().GetContext(), IndexRemovalType::DELETED_ROWS_IN_USE) { } void CleanupState::CleanupEntry(UndoFlags type, data_ptr_t data) { diff --git a/src/duckdb/src/transaction/commit_state.cpp b/src/duckdb/src/transaction/commit_state.cpp index cb80295ce..dd74a7341 100644 --- a/src/duckdb/src/transaction/commit_state.cpp +++ b/src/duckdb/src/transaction/commit_state.cpp @@ -25,6 +25,7 @@ #include "duckdb/transaction/duck_transaction_manager.hpp" #include "duckdb/storage/data_table.hpp" #include "duckdb/common/types/data_chunk.hpp" +#include "duckdb/main/attached_database.hpp" namespace duckdb { @@ -85,7 +86,7 @@ bool CommitDropState::Empty() const { //===--------------------------------------------------------------------===// // IndexDataRemover //===--------------------------------------------------------------------===// -IndexDataRemover::IndexDataRemover(DuckTransaction &transaction_p, QueryContext context, IndexRemovalType removal_type) +IndexDataRemover::IndexDataRemover(DuckTransaction &transaction_p, Context &context, IndexRemovalType removal_type) : transaction(transaction_p), context(context), removal_type(removal_type) { } @@ -158,7 +159,8 @@ void IndexDataRemover::Flush(DataTable &table, row_t *row_numbers, idx_t count) CommitState::CommitState(DuckTransaction &transaction_p, transaction_t commit_id, ActiveTransactionState transaction_state, CommitMode commit_mode) : transaction(transaction_p), commit_id(commit_id), - index_data_remover(transaction, QueryContext(), GetIndexRemovalType(transaction_state, commit_mode)) { + index_data_remover(transaction, transaction.manager.GetDB().GetContext(), + GetIndexRemovalType(transaction_state, commit_mode)) { D_ASSERT(commit_mode != CommitMode::COMMIT || IsCommitted(commit_id)); } diff --git a/src/duckdb/src/transaction/transaction_context.cpp b/src/duckdb/src/transaction/transaction_context.cpp index 28ba4674d..af69c0185 100644 --- a/src/duckdb/src/transaction/transaction_context.cpp +++ b/src/duckdb/src/transaction/transaction_context.cpp @@ -61,9 +61,26 @@ void TransactionContext::BeginTransaction() { SetCurrentTransaction(make_shared_ptr(*context.db, context.client_data->temporary_objects, start_timestamp, global_transaction_id)); - // Notify any registered state of transaction begin + // Notify any registered state of transaction begin - all of them, also when one of them fails, so that all see the + // transaction end + ErrorData begin_error; for (auto &state : context.GetContext().GetRegisteredState().States()) { - state->TransactionBegin(*current_transaction, context); + try { + state->TransactionBegin(*current_transaction, context); + } catch (std::exception &ex) { + if (!begin_error.HasError()) { + begin_error = ErrorData(ex); + } + } + } + if (begin_error.HasError()) { + // a state rejected the transaction: it does not stay open + try { + Rollback(&begin_error); + } catch (...) { + // the rejection is the error reported + } + begin_error.Throw(); } } diff --git a/src/duckdb/ub_src_common.cpp b/src/duckdb/ub_src_common.cpp index f53389f48..f3ed364b0 100644 --- a/src/duckdb/ub_src_common.cpp +++ b/src/duckdb/ub_src_common.cpp @@ -82,8 +82,6 @@ #include "src/common/process_util.cpp" -#include "src/common/query_context.cpp" - #include "src/common/radix_partitioning.cpp" #include "src/common/random_engine.cpp" diff --git a/src/duckdb/ub_src_common_multi_file.cpp b/src/duckdb/ub_src_common_multi_file.cpp index 450e84f75..0301db8c0 100644 --- a/src/duckdb/ub_src_common_multi_file.cpp +++ b/src/duckdb/ub_src_common_multi_file.cpp @@ -14,5 +14,7 @@ #include "src/common/multi_file/table_function_multi_file_list.cpp" +#include "src/common/multi_file/table_function_query_filter.cpp" + #include "src/common/multi_file/union_by_name.cpp" diff --git a/src/duckdb/ub_src_main.cpp b/src/duckdb/ub_src_main.cpp index df179ab8d..41214e6d7 100644 --- a/src/duckdb/ub_src_main.cpp +++ b/src/duckdb/ub_src_main.cpp @@ -8,8 +8,6 @@ #include "src/main/client_context_execution.cpp" -#include "src/main/client_context_file_opener.cpp" - #include "src/main/client_data.cpp" #include "src/main/client_verify.cpp" diff --git a/src/duckdb/ub_src_main_capi_v2.cpp b/src/duckdb/ub_src_main_capi_v2.cpp index 3e5427e28..29f218b41 100644 --- a/src/duckdb/ub_src_main_capi_v2.cpp +++ b/src/duckdb/ub_src_main_capi_v2.cpp @@ -12,6 +12,8 @@ #include "src/main/capi/v2/capi_v2_connection.cpp" +#include "src/main/capi/v2/capi_v2_context_state.cpp" + #include "src/main/capi/v2/capi_v2_crypto.cpp" #include "src/main/capi/v2/capi_v2_custom_option.cpp" From 37ebef5dd4ae78a5496dc4bbe0375b72c4193cc1 Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Mon, 30 Nov 2026 10:54:25 +0000 Subject: [PATCH 5/8] Update vendored DuckDB sources to be81c35c08f --- .../extension/parquet/parquet_writer.cpp | 15 ++-- ...nerated_extension_loader_package_build.cpp | 8 +- .../src/catalog/catalog_search_path.cpp | 13 ++- .../src/function/scalar/string/prefix.cpp | 1 + .../src/function/scalar/string/regexp.cpp | 84 ++++++++++--------- .../string/regexp/regexp_extract_all.cpp | 22 +++-- .../scalar/string/regexp/regexp_util.cpp | 43 ++++++---- .../function/scalar/string/string_split.cpp | 18 +++- .../src/function/scalar/string/suffix.cpp | 1 + .../function/table/version/pragma_version.cpp | 6 +- .../duckdb/catalog/catalog_search_path.hpp | 2 + .../duckdb/common/types/double_na_equal.hpp | 10 +-- .../include/duckdb/function/scalar/regexp.hpp | 11 ++- .../storage/table/array_column_data.hpp | 1 + .../duckdb/storage/table/column_data.hpp | 2 + .../duckdb/storage/table/list_column_data.hpp | 1 + .../duckdb/storage/table/row_group.hpp | 4 + .../storage/table/standard_column_data.hpp | 1 + .../storage/table/struct_column_data.hpp | 1 + .../src/main/settings/custom_settings.cpp | 2 +- src/duckdb/src/optimizer/filter_combiner.cpp | 6 ++ .../src/planner/filter/expression_filter.cpp | 11 +++ .../src/storage/table/array_column_data.cpp | 4 + src/duckdb/src/storage/table/column_data.cpp | 4 + .../src/storage/table/list_column_data.cpp | 4 + src/duckdb/src/storage/table/row_group.cpp | 20 +++++ .../src/storage/table/row_group_reorderer.cpp | 61 ++++++++++++-- .../storage/table/standard_column_data.cpp | 4 + .../src/storage/table/struct_column_data.cpp | 12 +++ 29 files changed, 272 insertions(+), 100 deletions(-) diff --git a/src/duckdb/extension/parquet/parquet_writer.cpp b/src/duckdb/extension/parquet/parquet_writer.cpp index 425d2a388..4b281cc3d 100644 --- a/src/duckdb/extension/parquet/parquet_writer.cpp +++ b/src/duckdb/extension/parquet/parquet_writer.cpp @@ -665,7 +665,7 @@ void ParquetWriter::InitializeColumnWriters() { &options.shredding_types, 0, 1, can_have_nulls)); auto &column_writer = *column_writers.back(); column_writer.bloom_filter_fallback = - options.enable_bloom_filters && !options.encryption_config && column_writer.SupportsBloomFilterFallback(); + options.enable_bloom_filters && column_writer.SupportsBloomFilterFallback(); } } @@ -1568,7 +1568,6 @@ void ParquetWriter::FlushBloomFilters() { (a.column_idx == b.column_idx && a.row_group_idx < b.row_group_idx); }); for (auto &bloom_filter_entry : bloom_filters) { - D_ASSERT(!options.encryption_config); // write nonsense bloom filter header duckdb_parquet::BloomFilterHeader filter_header; const auto bloom_filter_size = bloom_filter_entry.bloom_filter->Get()->GetLength(); @@ -1584,13 +1583,16 @@ void ParquetWriter::FlushBloomFilters() { column_chunk.meta_data.__isset.bloom_filter_offset = true; column_chunk.meta_data.bloom_filter_offset = NumericCast(writer->GetTotalWritten()); + // in an encrypted file the header and the bitset are their own encrypted modules auto bloom_filter_header_size = Write(filter_header); // the async writer accounts for the bytes it queues, so the filter no longer needs the budget bloom_filter_entry.bloom_filter->ReleaseReservation(); - WriteData(make_uniq(std::move(bloom_filter_entry.bloom_filter))); + auto bloom_filter_on_disk_size = WriteData( + PrepareWriteData(make_uniq(std::move(bloom_filter_entry.bloom_filter)))); column_chunk.meta_data.__isset.bloom_filter_length = true; - column_chunk.meta_data.bloom_filter_length = NumericCast(bloom_filter_header_size + bloom_filter_size); + column_chunk.meta_data.bloom_filter_length = + NumericCast(bloom_filter_header_size + bloom_filter_on_disk_size); } bloom_filters.clear(); } @@ -1598,7 +1600,7 @@ void ParquetWriter::FlushBloomFilters() { void ParquetWriter::Finalize() { InitializeSchemaElements(); - // dump the remaining bloom filters right before footer, not if stuff is encrypted + // dump the remaining bloom filters right before the footer FlushBloomFilters(); // the page index goes right in front of the footer, after the bloom filters, so that it is part of the tail of the @@ -1684,9 +1686,6 @@ void ParquetWriter::BufferPageIndex(idx_t col_idx, ParquetPageIndexEntry page_in } void ParquetWriter::BufferBloomFilter(idx_t col_idx, unique_ptr bloom_filter) { - if (options.encryption_config) { - return; - } ParquetBloomFilterEntry new_entry; new_entry.bloom_filter = std::move(bloom_filter); new_entry.column_idx = col_idx; diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 86e6a25f1..14965f69f 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-alpha58282"; + descriptor->api_version = "v2.1.0-alpha58324"; 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-alpha58282"; + descriptor->api_version = "v2.1.0-alpha58324"; 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-alpha58282"; + descriptor->api_version = "v2.1.0-alpha58324"; 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-alpha58282"; + descriptor->api_version = "v2.1.0-alpha58324"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/catalog/catalog_search_path.cpp b/src/duckdb/src/catalog/catalog_search_path.cpp index 0e24488c0..9d2f3db35 100644 --- a/src/duckdb/src/catalog/catalog_search_path.cpp +++ b/src/duckdb/src/catalog/catalog_search_path.cpp @@ -40,17 +40,22 @@ string CatalogSearchEntry::GetSchemaName() const { return IsNested() ? QualifiedName::FromPath(GetSchemaPath()).ToString() : schema.GetIdentifierName(); } -string CatalogSearchEntry::ToString() const { +string CatalogSearchEntry::SchemaToString() const { string result; - if (!catalog.empty()) { - result = WriteOptionallyQuoted(catalog) + "."; - } for (auto &parent : parent_schemas) { result += WriteOptionallyQuoted(parent) + "."; } return result + WriteOptionallyQuoted(schema); } +string CatalogSearchEntry::ToString() const { + string result; + if (!catalog.empty()) { + result = WriteOptionallyQuoted(catalog) + "."; + } + return result + SchemaToString(); +} + string CatalogSearchEntry::WriteOptionallyQuoted(const Identifier &input) { auto &name = input.GetIdentifierName(); for (idx_t i = 0; i < name.size(); i++) { diff --git a/src/duckdb/src/function/scalar/string/prefix.cpp b/src/duckdb/src/function/scalar/string/prefix.cpp index 7857f5c8e..5096e95a6 100644 --- a/src/duckdb/src/function/scalar/string/prefix.cpp +++ b/src/duckdb/src/function/scalar/string/prefix.cpp @@ -67,6 +67,7 @@ ScalarFunction PrefixFun::GetFunction() { function.GetSignature() .AddParameter("string", LogicalType::VARCHAR) .AddParameter("search_string", LogicalType::VARCHAR); + function.SetCollationHandling(FunctionCollationHandling::PUSH_COMBINABLE_COLLATIONS); function.SetFilterPruneCallback(PrefixFilterPrune); return function; } diff --git a/src/duckdb/src/function/scalar/string/regexp.cpp b/src/duckdb/src/function/scalar/string/regexp.cpp index 29e929110..65ff14cec 100644 --- a/src/duckdb/src/function/scalar/string/regexp.cpp +++ b/src/duckdb/src/function/scalar/string/regexp.cpp @@ -55,6 +55,19 @@ RegexpBaseBindData::RegexpBaseBindData(duckdb_re2::RE2::Options options, string RegexpBaseBindData::~RegexpBaseBindData() { } +unique_ptr RegexpBaseBindData::CompileConstantPattern() const { + if (!constant_pattern) { + return nullptr; + } + auto validation_options = options; + validation_options.set_log_errors(false); + return make_uniq(constant_string, validation_options); +} + +unique_ptr RegexpBaseBindData::Copy() const { + return make_uniq(options, constant_string, constant_pattern); +} + bool RegexpBaseBindData::Equals(const FunctionData &other_p) const { auto &other = other_p.Cast(); return constant_pattern == other.constant_pattern && constant_string == other.constant_string && @@ -73,18 +86,6 @@ unique_ptr RegexInitLocalState(ExpressionState &state, const //===--------------------------------------------------------------------===// // Regexp Matches //===--------------------------------------------------------------------===// -RegexpMatchesBindData::RegexpMatchesBindData(duckdb_re2::RE2::Options options, string constant_string_p, - bool constant_pattern) - : RegexpBaseBindData(options, std::move(constant_string_p), constant_pattern) { - if (constant_pattern) { - // an invalid pattern is reported when the function state is initialized - auto pattern = make_uniq(constant_string, options); - range_success = pattern->ok() && pattern->PossibleMatchRange(&range_min, &range_max, 1000); - } else { - range_success = false; - } -} - RegexpMatchesBindData::RegexpMatchesBindData(duckdb_re2::RE2::Options options, string constant_string_p, bool constant_pattern, string range_min_p, string range_max_p, bool range_success) @@ -108,9 +109,18 @@ unique_ptr RegexpMatchesBind(BindScalarFunctionInput &input) { } string constant_string; - bool constant_pattern; - constant_pattern = TryParseConstantPattern(input.TryGetConstant(1), constant_string); - return make_uniq(options, std::move(constant_string), constant_pattern); + const bool constant_pattern = TryParseConstantPattern(input.TryGetConstant(1), constant_string); + string range_min; + string range_max; + bool range_success = false; + RegexpBaseBindData data(options, std::move(constant_string), constant_pattern); + auto pattern = data.CompileConstantPattern(); + if (pattern && pattern->ok()) { + range_success = pattern->PossibleMatchRange(&range_min, &range_max, 1000); + input.GetBoundFunction().SetErrorMode(FunctionErrors::CANNOT_ERROR); + } + return make_uniq(options, std::move(data.constant_string), constant_pattern, + std::move(range_min), std::move(range_max), range_success); } struct RegexPartialMatch { @@ -182,12 +192,10 @@ static unique_ptr RegexReplaceBind(BindScalarFunctionInput &input) data->options.set_log_errors(false); auto replacement = input.TryGetConstant(2); - if (data->constant_pattern && replacement && !replacement->IsNull() && - data->constant_string.find("\\C") == string::npos) { - RE2 validation_re(data->constant_string, data->options); + auto pattern = data->CompileConstantPattern(); + if (regexp_util::CanExtractUTF8(pattern.get()) && replacement && !replacement->IsNull()) { std::string rewrite_error; - if (validation_re.ok() && - validation_re.CheckRewriteString(CreateStringPiece(StringValue::Get(*replacement)), &rewrite_error)) { + if (pattern->CheckRewriteString(CreateStringPiece(StringValue::Get(*replacement)), &rewrite_error)) { // A valid pattern without byte escapes and a valid replacement cannot throw. input.GetBoundFunction().SetErrorMode(FunctionErrors::CANNOT_ERROR); } @@ -397,9 +405,17 @@ static unique_ptr RegexExtractBind(BindScalarFunctionInput &input) ParseRegexOptions(input.GetConstant(3), options, nullptr, &no_match_returns_input); } - int8_t group_index = 0; + Value group_or_options; + if (arguments.size() >= 3) { + group_or_options = input.GetConstant(2); + if (group_or_options.type() == LogicalType::VARCHAR) { + ParseRegexOptions(group_or_options, options, nullptr, &no_match_returns_input); + } + } + auto data = make_uniq(options, std::move(constant_string), constant_pattern, 0, + no_match_returns_input); + auto pattern = data->CompileConstantPattern(); if (arguments.size() >= 3) { - Value group_or_options = input.GetConstant(2); if (group_or_options.type().id() == LogicalTypeId::LIST) { if (!constant_pattern) { throw BinderException("%s with LIST of group names requires a constant pattern", @@ -407,34 +423,26 @@ static unique_ptr RegexExtractBind(BindScalarFunctionInput &input) } vector dummy_names; // not reused after bind child_list_t struct_children; - regexp_util::ParseGroupNameList(bound_function.GetName().GetIdentifierName(), group_or_options, - constant_string, options, constant_pattern, dummy_names, struct_children); + regexp_util::ParseGroupNameList(bound_function.GetName().GetIdentifierName(), group_or_options, *pattern, + dummy_names, struct_children); bound_function.SetReturnType(LogicalType::STRUCT(struct_children)); - } else if (group_or_options.type() == LogicalType::VARCHAR) { - ParseRegexOptions(group_or_options, options, nullptr, &no_match_returns_input); } else if (group_or_options.IsNull()) { // NULL group → never returns a capture; runtime treats out-of-range index as no match. - group_index = -1; - } else { + data->group_index = -1; + } else if (group_or_options.type() != LogicalType::VARCHAR) { int32_t group_idx = group_or_options.GetValue(); if (group_idx < 0 || group_idx > 9) { throw InvalidInputException("Group index must be between 0 and 9!"); } - group_index = static_cast(group_idx); + data->group_index = static_cast(group_idx); } } - if (constant_pattern && constant_string.find("\\C") == string::npos) { - auto validation_options = options; - validation_options.set_log_errors(false); - if (RE2(constant_string, validation_options).ok()) { - // A valid UTF-8 pattern without byte escapes cannot return a partial character. - bound_function.SetErrorMode(FunctionErrors::CANNOT_ERROR); - } + if (regexp_util::CanExtractUTF8(pattern.get())) { + bound_function.SetErrorMode(FunctionErrors::CANNOT_ERROR); } - return make_uniq(options, std::move(constant_string), constant_pattern, group_index, - no_match_returns_input); + return std::move(data); } // Constructs a regex-family ScalarFunction and names its (up to 4) parameters via the builder pattern, since these diff --git a/src/duckdb/src/function/scalar/string/regexp/regexp_extract_all.cpp b/src/duckdb/src/function/scalar/string/regexp/regexp_extract_all.cpp index 338074112..2e6b153c4 100644 --- a/src/duckdb/src/function/scalar/string/regexp/regexp_extract_all.cpp +++ b/src/duckdb/src/function/scalar/string/regexp/regexp_extract_all.cpp @@ -304,10 +304,15 @@ unique_ptr RegexpExtractAllStruct::Bind(BindScalarFunctionInput &i options.set_log_errors(false); vector group_names; child_list_t struct_children; - regexp_util::ParseGroupNameList(function.GetName().GetIdentifierName(), input.GetConstant(2), constant_string, - options, true, group_names, struct_children); + RegexpBaseBindData data(options, std::move(constant_string), constant_pattern); + auto pattern = data.CompileConstantPattern(); + regexp_util::ParseGroupNameList(function.GetName().GetIdentifierName(), input.GetConstant(2), *pattern, group_names, + struct_children); function.SetReturnType(LogicalType::LIST(LogicalType::STRUCT(struct_children))); - return make_uniq(options, std::move(constant_string), constant_pattern, + if (regexp_util::CanExtractUTF8(pattern.get())) { + function.SetErrorMode(FunctionErrors::CANNOT_ERROR); + } + return make_uniq(options, std::move(data.constant_string), constant_pattern, std::move(group_names)); } @@ -324,8 +329,15 @@ unique_ptr RegexpExtractAll::Bind(BindScalarFunctionInput &input) if (arguments.size() >= 4) { ParseRegexOptions(input.GetConstant(3), options); } - return make_uniq(options, std::move(constant_string), constant_pattern, - static_cast(0)); + auto data = make_uniq(options, std::move(constant_string), constant_pattern); + auto pattern = data->CompileConstantPattern(); + if (regexp_util::CanExtractUTF8(pattern.get())) { + auto group = arguments.size() >= 3 ? input.TryGetConstant(2) : optional(Value::INTEGER(0)); + if (group && (group->IsNull() || group->GetValue() <= pattern->NumberOfCapturingGroups())) { + input.GetBoundFunction().SetErrorMode(FunctionErrors::CANNOT_ERROR); + } + } + return std::move(data); } } // namespace duckdb diff --git a/src/duckdb/src/function/scalar/string/regexp/regexp_util.cpp b/src/duckdb/src/function/scalar/string/regexp/regexp_util.cpp index 04db81e3e..85c92a377 100644 --- a/src/duckdb/src/function/scalar/string/regexp/regexp_util.cpp +++ b/src/duckdb/src/function/scalar/string/regexp/regexp_util.cpp @@ -1,6 +1,7 @@ #include "duckdb/function/scalar/regexp.hpp" #include "duckdb/execution/expression_executor.hpp" #include "re2/re2.h" +#include "re2/regexp.h" #include "re2/stringpiece.h" #include "utf8proc_wrapper.hpp" @@ -80,9 +81,27 @@ void ParseRegexOptions(const Value &options_str, RE2::Options &target, bool *glo ParseRegexOptions(StringValue::Get(options_str), target, global_replace, no_match_returns_input); } -void ParseGroupNameList(const string &function_name, const Value &list_val, const string &pattern_string, - RE2::Options &options, bool require_constant_pattern, vector &out_names, - child_list_t &out_struct_children) { +bool CanExtractUTF8(optional_ptr pattern) { + if (!pattern || !pattern->ok()) { + return false; + } + vector> pending; + pending.emplace_back(*pattern->Regexp()); + while (!pending.empty()) { + auto &node = pending.back().get(); + pending.pop_back(); + if (node.op() == duckdb_re2::kRegexpAnyByte) { + return false; + } + for (idx_t i = 0; i < NumericCast(node.nsub()); i++) { + pending.emplace_back(*node.sub()[i]); + } + } + return true; +} + +void ParseGroupNameList(const string &function_name, const Value &list_val, const RE2 &pattern, + vector &out_names, child_list_t &out_struct_children) { if (list_val.IsNull() || list_val.type().id() != LogicalTypeId::LIST) { throw BinderException("Group specification must be a non-NULL LIST"); } @@ -106,17 +125,13 @@ void ParseGroupNameList(const string &function_name, const Value &list_val, cons out_names.push_back(name); out_struct_children.emplace_back(make_pair(name, LogicalType::VARCHAR)); } - if (require_constant_pattern) { - duckdb_re2::StringPiece const_piece(pattern_string.c_str(), pattern_string.size()); - RE2 constant_re(const_piece, options); - auto group_cnt = constant_re.NumberOfCapturingGroups(); - if (group_cnt == -1) { - throw BinderException("Pattern failed to parse: %s", constant_re.error()); - } - if ((idx_t)group_cnt < out_names.size()) { - throw BinderException("Not enough capturing groups (%d) for provided names (%llu)", group_cnt, - NumericCast(out_names.size())); - } + auto group_cnt = pattern.NumberOfCapturingGroups(); + if (group_cnt == -1) { + throw BinderException("Pattern failed to parse: %s", pattern.error()); + } + if ((idx_t)group_cnt < out_names.size()) { + throw BinderException("Not enough capturing groups (%d) for provided names (%llu)", group_cnt, + NumericCast(out_names.size())); } } diff --git a/src/duckdb/src/function/scalar/string/string_split.cpp b/src/duckdb/src/function/scalar/string/string_split.cpp index 71ca93f0f..86fc16dcf 100644 --- a/src/duckdb/src/function/scalar/string/string_split.cpp +++ b/src/duckdb/src/function/scalar/string/string_split.cpp @@ -131,9 +131,23 @@ void StringSplitFunction(DataChunk &args, ExpressionState &state, Vector &result StringSplitExecutor(args, state, result, [](const string_t &) -> void * { return nullptr; }); } +unique_ptr StringSplitRegexBind(BindScalarFunctionInput &input) { + auto data = make_uniq(); + data->constant_pattern = regexp_util::TryParseConstantPattern(input.TryGetConstant(1), data->constant_string); + data->options.set_log_errors(false); + if (input.GetArguments().size() == 3) { + regexp_util::ParseRegexOptions(input.GetConstant(2), data->options); + } + auto pattern = data->CompileConstantPattern(); + if (regexp_util::CanExtractUTF8(pattern.get())) { + input.GetBoundFunction().SetErrorMode(FunctionErrors::CANNOT_ERROR); + } + return std::move(data); +} + void StringSplitRegexFunction(DataChunk &args, ExpressionState &state, Vector &result) { auto &func_expr = state.expr.Cast(); - auto &info = func_expr.BindInfo()->Cast(); + auto &info = func_expr.BindInfo()->Cast(); if (info.constant_pattern) { // fast path: pre-compiled regex auto &lstate = ExecuteFunctionState::GetFunctionState(state)->Cast(); @@ -168,7 +182,7 @@ ScalarFunction StringSplitFun::GetFunction() { ScalarFunctionSet StringSplitRegexFun::GetFunctions() { auto varchar_list_type = LogicalType::LIST(LogicalType::VARCHAR); ScalarFunctionSet regexp_split; - ScalarFunction regex_fun({}, varchar_list_type, StringSplitRegexFunction, RegexpMatchesBind, nullptr, + ScalarFunction regex_fun({}, varchar_list_type, StringSplitRegexFunction, StringSplitRegexBind, nullptr, RegexInitLocalState, LogicalType::INVALID, FunctionStability::CONSISTENT, FunctionNullHandling::SPECIAL_HANDLING); regex_fun.GetSignature().AddParameter("string", LogicalType::VARCHAR).AddParameter("regex", LogicalType::VARCHAR); diff --git a/src/duckdb/src/function/scalar/string/suffix.cpp b/src/duckdb/src/function/scalar/string/suffix.cpp index 08a51d6f7..40f58b279 100644 --- a/src/duckdb/src/function/scalar/string/suffix.cpp +++ b/src/duckdb/src/function/scalar/string/suffix.cpp @@ -74,6 +74,7 @@ ScalarFunction SuffixFun::GetFunction() { function.GetSignature() .AddParameter("string", LogicalType::VARCHAR) .AddParameter("search_string", LogicalType::VARCHAR); + function.SetCollationHandling(FunctionCollationHandling::PUSH_COMBINABLE_COLLATIONS); function.SetFilterPruneCallback(SuffixFilterPrune); return function; } diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index d37ffb6c5..69aa17184 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-alpha58282" +#define DUCKDB_PATCH_VERSION "0-alpha58324" #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-alpha58282" +#define DUCKDB_VERSION "v2.1.0-alpha58324" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "9345a4d95c" +#define DUCKDB_SOURCE_ID "be81c35c08" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_search_path.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_search_path.hpp index 79a9891be..ab1a4a9d6 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_search_path.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_search_path.hpp @@ -51,6 +51,8 @@ struct CatalogSearchEntry { DUCKDB_API vector GetSchemaPath() const; //! The schema name, including its parent path for nested schemas string GetSchemaName() const; + //! The schema path rendered with quotes where required, so that it can be parsed back + string SchemaToString() const; string ToString() const; static string ListToString(const vector &input); diff --git a/src/duckdb/src/include/duckdb/common/types/double_na_equal.hpp b/src/duckdb/src/include/duckdb/common/types/double_na_equal.hpp index 1c40e02f1..7b1945834 100644 --- a/src/duckdb/src/include/duckdb/common/types/double_na_equal.hpp +++ b/src/duckdb/src/include/duckdb/common/types/double_na_equal.hpp @@ -25,10 +25,7 @@ struct double_na_equal { } bool operator==(const double &right) const { - if (std::isnan(val) && std::isnan(right)) { - return true; - } - return val == right && std::signbit(val) == std::signbit(right); + return std::signbit(val) == std::signbit(right) && (val == right || (std::isnan(val) && std::isnan(right))); } bool operator!=(const double &right) const { @@ -49,10 +46,7 @@ struct float_na_equal { } bool operator==(const float &right) const { - if (std::isnan(val) && std::isnan(right)) { - return true; - } - return val == right && std::signbit(val) == std::signbit(right); + return std::signbit(val) == std::signbit(right) && (val == right || (std::isnan(val) && std::isnan(right))); } bool operator!=(const float &right) const { diff --git a/src/duckdb/src/include/duckdb/function/scalar/regexp.hpp b/src/duckdb/src/include/duckdb/function/scalar/regexp.hpp index 27b3d82b0..2311dbe70 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/regexp.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/regexp.hpp @@ -22,9 +22,10 @@ void ParseRegexOptions(const string &options, duckdb_re2::RE2::Options &result, bool *no_match_returns_input = nullptr); void ParseRegexOptions(const Value &options_str, RE2::Options &target, bool *global_replace = nullptr, bool *no_match_returns_input = nullptr); -void ParseGroupNameList(const string &function_name, const Value &list_val, const string &pattern_string, - RE2::Options &options, bool require_constant_pattern, vector &out_names, - child_list_t &out_struct_children); +//! Whether the constant pattern is valid and preserves UTF-8 match boundaries. +bool CanExtractUTF8(optional_ptr pattern); +void ParseGroupNameList(const string &function_name, const Value &list_val, const RE2 &pattern, + vector &out_names, child_list_t &out_struct_children); idx_t AdvanceOneUTF8Basic(const duckdb_re2::StringPiece &input, idx_t base); //! Throws if a regex result is not valid UTF-8 @@ -52,6 +53,9 @@ struct RegexpBaseBindData : public FunctionData { string constant_string; bool constant_pattern; + //! Returns nullptr for a nonconstant pattern; invalid patterns are returned without throwing. + unique_ptr CompileConstantPattern() const; + unique_ptr Copy() const override; bool Equals(const FunctionData &other_p) const override; }; @@ -82,7 +86,6 @@ struct RegexpExtractAllStruct { }; struct RegexpMatchesBindData : public RegexpBaseBindData { - RegexpMatchesBindData(duckdb_re2::RE2::Options options, string constant_string, bool constant_pattern); RegexpMatchesBindData(duckdb_re2::RE2::Options options, string constant_string, bool constant_pattern, string range_min, string range_max, bool range_success); diff --git a/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp index dcc997025..76a838a16 100644 --- a/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp @@ -60,6 +60,7 @@ class ArrayColumnData : public ColumnData { bool IsPersistent() override; bool HasAnyChanges() const override; + bool HasAnyUpdates() const override; PersistentColumnData Serialize() override; void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/column_data.hpp index ed0a8544f..79151c3db 100644 --- a/src/duckdb/src/include/duckdb/storage/table/column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/column_data.hpp @@ -144,6 +144,8 @@ class ColumnData : public enable_shared_from_this { //! Whether or not the column has ANY changes, including in child columns virtual bool HasAnyChanges() const; + //! Whether or not the column has ANY updates, including in child columns + virtual bool HasAnyUpdates() const; //! Whether or not we can scan an entire vector virtual ScanVectorType GetVectorScanType(ColumnScanState &state, idx_t scan_count, Vector &result); diff --git a/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp index a1bc28293..1fc04c09e 100644 --- a/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp @@ -76,6 +76,7 @@ class ListColumnData : public ColumnData { bool IsPersistent() override; bool HasAnyChanges() const override; + bool HasAnyUpdates() const override; PersistentColumnData Serialize() override; void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/row_group.hpp b/src/duckdb/src/include/duckdb/storage/table/row_group.hpp index 47cfbb885..986596aa0 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_group.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_group.hpp @@ -279,6 +279,10 @@ class RowGroup : public SegmentBase { void GetColumnSegmentInfo(Context &context, idx_t row_group_index, vector &result, const ColumnSegmentInfoScanOptions &options = ColumnSegmentInfoScanOptions {}); static PartitionStatistics GetPartitionStats(SegmentNode &row_group, TransactionData transaction); + //! Whether the statistics of the given column describe exactly the rows visible to the transaction. + //! Deleted, updated, or invisible rows leave the statistics as a superset of the visible values, so a + //! statistics bound is then not necessarily attained by any row visible to the transaction. + bool ColumnStatsReflectVisibleRows(const StorageIndex &column_idx, TransactionData transaction); idx_t GetAllocationSize() const { return allocation_size; diff --git a/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp index c32c44a01..b82a963e8 100644 --- a/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp @@ -66,6 +66,7 @@ class StandardColumnData : public ColumnData { bool IsPersistent() override; bool HasAnyChanges() const override; + bool HasAnyUpdates() const override; PersistentColumnData Serialize() override; void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp index 610d70bb3..2d35a3e73 100644 --- a/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp @@ -77,6 +77,7 @@ class StructColumnData : public ColumnData { bool IsPersistent() override; bool HasAnyChanges() const override; + bool HasAnyUpdates() const override; PersistentColumnData Serialize() override; void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats) override; diff --git a/src/duckdb/src/main/settings/custom_settings.cpp b/src/duckdb/src/main/settings/custom_settings.cpp index 233815cf2..a6b65ce37 100644 --- a/src/duckdb/src/main/settings/custom_settings.cpp +++ b/src/duckdb/src/main/settings/custom_settings.cpp @@ -1553,7 +1553,7 @@ void SchemaSetting::ResetLocal(ClientContext &context) { Value SchemaSetting::GetSetting(const ClientContext &context) { auto &client_data = ClientData::Get(context); - return Value(client_data.catalog_search_path->GetDefault().GetSchemaName()); + return Value(client_data.catalog_search_path->GetDefault().SchemaToString()); } //===----------------------------------------------------------------------===// diff --git a/src/duckdb/src/optimizer/filter_combiner.cpp b/src/duckdb/src/optimizer/filter_combiner.cpp index 4b652c6ba..c8ea8943c 100644 --- a/src/duckdb/src/optimizer/filter_combiner.cpp +++ b/src/duckdb/src/optimizer/filter_combiner.cpp @@ -1086,6 +1086,12 @@ FilterPushdownResult FilterCombiner::TryPushdownOrClause(TableFilterSet &table_f CreateComparisonExpression(*column_ref, comparison_type, const_val->GetValue())); } } + if (conj_filter->GetChildren().empty()) { + // every child compares with a NULL constant - the OR can never be true: fold it to false + auto false_expr = make_uniq(Value::BOOLEAN(false)); + table_filters.PushFilter(proj_id, CreateOptionalExpressionFilter(std::move(false_expr), col_type)); + return FilterPushdownResult::PUSHED_DOWN_PARTIALLY; + } if (only_equalities && equality_column) { if (TryPushdownDenseInFilter(table_filters, *equality_column, equality_values)) { return FilterPushdownResult::PUSHED_DOWN_FULLY; diff --git a/src/duckdb/src/planner/filter/expression_filter.cpp b/src/duckdb/src/planner/filter/expression_filter.cpp index df1aa24df..0dd25d71e 100644 --- a/src/duckdb/src/planner/filter/expression_filter.cpp +++ b/src/duckdb/src/planner/filter/expression_filter.cpp @@ -974,6 +974,17 @@ FilterPropagateResult ExpressionFilter::CheckExpressionStatistics(optional_ptr(), input_stats); case ExpressionClass::BOUND_REF: return CheckBoolRefStatistics(expr, input_stats, false); + case ExpressionClass::BOUND_CONSTANT: { + auto &value = expr.Cast().GetValue(); + if (value.type().id() != LogicalTypeId::BOOLEAN) { + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } + if (value.IsNull()) { + return FilterPropagateResult::FILTER_FALSE_OR_NULL; + } + return BooleanValue::Get(value) ? FilterPropagateResult::FILTER_ALWAYS_TRUE + : FilterPropagateResult::FILTER_ALWAYS_FALSE; + } default: return FilterPropagateResult::NO_PRUNING_POSSIBLE; } diff --git a/src/duckdb/src/storage/table/array_column_data.cpp b/src/duckdb/src/storage/table/array_column_data.cpp index 7864ec792..aba06719a 100644 --- a/src/duckdb/src/storage/table/array_column_data.cpp +++ b/src/duckdb/src/storage/table/array_column_data.cpp @@ -372,6 +372,10 @@ bool ArrayColumnData::HasAnyChanges() const { return child_column->HasAnyChanges() || validity->HasAnyChanges(); } +bool ArrayColumnData::HasAnyUpdates() const { + return child_column->HasAnyUpdates() || validity->HasAnyUpdates(); +} + PersistentColumnData ArrayColumnData::Serialize() { PersistentColumnData persistent_data(type); persistent_data.child_columns.push_back(validity->Serialize()); diff --git a/src/duckdb/src/storage/table/column_data.cpp b/src/duckdb/src/storage/table/column_data.cpp index 22a472e97..2aec40df0 100644 --- a/src/duckdb/src/storage/table/column_data.cpp +++ b/src/duckdb/src/storage/table/column_data.cpp @@ -130,6 +130,10 @@ bool ColumnData::HasAnyChanges() const { return HasChanges(); } +bool ColumnData::HasAnyUpdates() const { + return HasUpdates(); +} + idx_t ColumnData::GetMaxEntry() { return count; } diff --git a/src/duckdb/src/storage/table/list_column_data.cpp b/src/duckdb/src/storage/table/list_column_data.cpp index b48156440..093917cb3 100644 --- a/src/duckdb/src/storage/table/list_column_data.cpp +++ b/src/duckdb/src/storage/table/list_column_data.cpp @@ -508,6 +508,10 @@ bool ListColumnData::HasAnyChanges() const { return ColumnData::HasAnyChanges() || validity->HasAnyChanges() || child_column->HasAnyChanges(); } +bool ListColumnData::HasAnyUpdates() const { + return ColumnData::HasAnyUpdates() || validity->HasAnyUpdates() || child_column->HasAnyUpdates(); +} + //! Resolves the statistics of a column from the statistics of its root column //! A nested column can hold its own statistics (e.g. when it was created by a checkpoint), but those are not updated: //! the statistics of nested columns are tracked in the statistics of the root column diff --git a/src/duckdb/src/storage/table/row_group.cpp b/src/duckdb/src/storage/table/row_group.cpp index d210f4416..6ca2c7c5c 100644 --- a/src/duckdb/src/storage/table/row_group.cpp +++ b/src/duckdb/src/storage/table/row_group.cpp @@ -2120,6 +2120,26 @@ PartitionStatistics RowGroup::GetPartitionStats(SegmentNode &row_group return result; } +bool RowGroup::ColumnStatsReflectVisibleRows(const StorageIndex &column_idx, TransactionData transaction) { + if (HasUnloadedDeletes()) { + return false; + } + auto vinfo = GetVersionInfoIfLoaded(); + if (vinfo) { + if (vinfo->HasDeletes()) { + return false; + } + if (GetVisibleRowCount(transaction) != count) { + return false; + } + } + auto primary_idx = column_idx.GetPrimaryIndex(); + if (ColumnIsLoaded(primary_idx) && GetColumn(primary_idx).HasAnyUpdates()) { + return false; + } + return true; +} + //===--------------------------------------------------------------------===// // GetColumnSegmentInfo //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/storage/table/row_group_reorderer.cpp b/src/duckdb/src/storage/table/row_group_reorderer.cpp index 86b98fab5..8849513e7 100644 --- a/src/duckdb/src/storage/table/row_group_reorderer.cpp +++ b/src/duckdb/src/storage/table/row_group_reorderer.cpp @@ -7,6 +7,8 @@ namespace { struct RowGroupSegmentNodeEntry { reference> row_group; unique_ptr stats; + //! Whether the statistics describe exactly the rows visible to the transaction (no deletes/updates/invisible rows) + bool stats_reflect_visible_rows; }; struct RowGroupOffsetEntry { @@ -22,13 +24,35 @@ bool CompareValues(const Value &v1, const Value &v2, const OrderByStatistics ord return (order == OrderByStatistics::MAX && v1 < v2) || (order == OrderByStatistics::MIN && v1 > v2); } -idx_t GetMinimumQualifyingTupleCount(RowGroup &row_group, BaseStatistics &stats, const OrderByColumnType type, +idx_t GetMinimumQualifyingTupleCount(const RowGroupSegmentNodeEntry &entry, const OrderByColumnType type, TransactionData transaction) { + auto &stats = *entry.stats; if (!stats.CanHaveNull()) { - return row_group.GetVisibleRowCount(transaction); + // every visible row is non-NULL and within the statistics bounds, so every visible row qualifies + return entry.row_group.get().GetNode().GetVisibleRowCount(transaction); + } + + if (!entry.stats_reflect_visible_rows) { + // the bounds may stem from deleted, updated, or invisible rows, so they cannot prove that any + // visible non-NULL row exists + return 0; } if (type == OrderByColumnType::NUMERIC) { + if (stats.GetStatsType() == StatisticsType::BIGNUM_STATS) { + // the bignum_t tier of decimals + if (!BignumStats::HasMinMax(stats)) { + return 0; + } + // a cut bound is not attained by a value, so it only guarantees one qualifying tuple + if (!BignumStats::MinIsExact(stats) || !BignumStats::MaxIsExact(stats)) { + return 1; + } + if (BignumStats::Min(stats) == BignumStats::Max(stats)) { + return 1; + } + return 2; + } if (!NumericStats::HasMinMax(stats)) { return 0; } @@ -42,6 +66,19 @@ idx_t GetMinimumQualifyingTupleCount(RowGroup &row_group, BaseStatistics &stats, return 0; } +//! Whether the ordering bound of the row group is attained by a row visible to the transaction +bool KeyBoundAttained(const RowGroupSegmentNodeEntry &entry, const OrderByStatistics stat_type) { + if (!entry.stats_reflect_visible_rows) { + return false; + } + if (entry.stats->GetStatsType() == StatisticsType::BIGNUM_STATS) { + // a cut bound is not attained by any row + return stat_type == OrderByStatistics::MIN ? BignumStats::MinIsExact(*entry.stats) + : BignumStats::MaxIsExact(*entry.stats); + } + return true; +} + template bool AddRowGroups(multimap &row_group_map, It it, const End &end, vector>> &ordered_row_groups, const idx_t row_limit, @@ -57,20 +94,22 @@ bool AddRowGroups(multimap &row_group_map, It i idx_t qualifying_tuples = 0; idx_t qualify_later = 0; - idx_t last_unresolved_row_group_sum = - GetMinimumQualifyingTupleCount(it->second.row_group.get().GetNode(), *last_stats, column_type, transaction); + idx_t last_unresolved_row_group_sum = GetMinimumQualifyingTupleCount(it->second, column_type, transaction); for (; it != end; ++it) { auto ¤t_key = it->first; auto &row_group = it->second.row_group; while (last_unresolved_entry != it) { if (!CompareValues(current_key, last_unresolved_boundary, stat_type)) { + // The guaranteed tuple is the one attaining the previous row group's ordering bound if (current_key != std::prev(it)->first) { // Row groups overlap: we can only guarantee one additional qualifying tuple qualifying_tuples += qualify_later; qualify_later = 0; - qualifying_tuples++; - } else { + if (KeyBoundAttained(std::prev(it)->second, stat_type)) { + qualifying_tuples++; + } + } else if (KeyBoundAttained(std::prev(it)->second, stat_type)) { // Row groups have the same order value, we can only guarantee a qualifying tuple later qualify_later++; } @@ -82,11 +121,10 @@ bool AddRowGroups(multimap &row_group_map, It i // 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; last_unresolved_row_group_sum += - GetMinimumQualifyingTupleCount(upcoming_row_group, upcoming_stats, column_type, transaction); + GetMinimumQualifyingTupleCount(last_unresolved_entry->second, column_type, transaction); last_unresolved_boundary = RowGroupReorderer::RetrieveStat(upcoming_stats, opposite_stat_type, column_type); } if (qualifying_tuples >= row_limit) { @@ -380,6 +418,8 @@ optional_ptr> RowGroupReorderer::GetRootSegment(RowGroupSe vector>> null_only_groups; vector>> ambiguous_groups; multimap row_group_map; + // the proof that statistics bounds are attained by visible rows is only needed for limit pruning + const bool needs_qualifying_proof = options.row_limit.IsValid(); for (auto &row_group : row_groups.SegmentNodes()) { auto stats = row_group.GetNode().GetStatistics(options.column_idx); if (!stats) { @@ -397,7 +437,10 @@ optional_ptr> RowGroupReorderer::GetRootSegment(RowGroupSe ambiguous_groups.push_back(row_group); continue; } - auto entry = RowGroupSegmentNodeEntry {row_group, std::move(stats)}; + const bool stats_reflect_visible_rows = + needs_qualifying_proof && + row_group.GetNode().ColumnStatsReflectVisibleRows(options.column_idx, transaction); + auto entry = RowGroupSegmentNodeEntry {row_group, std::move(stats), stats_reflect_visible_rows}; row_group_map.emplace(comparison_value, std::move(entry)); } diff --git a/src/duckdb/src/storage/table/standard_column_data.cpp b/src/duckdb/src/storage/table/standard_column_data.cpp index 5e1c212cd..7589e8f43 100644 --- a/src/duckdb/src/storage/table/standard_column_data.cpp +++ b/src/duckdb/src/storage/table/standard_column_data.cpp @@ -339,6 +339,10 @@ bool StandardColumnData::HasAnyChanges() const { return ColumnData::HasAnyChanges() || validity->HasAnyChanges(); } +bool StandardColumnData::HasAnyUpdates() const { + return ColumnData::HasAnyUpdates() || validity->HasAnyUpdates(); +} + PersistentColumnData StandardColumnData::Serialize() { auto persistent_data = ColumnData::Serialize(); persistent_data.child_columns.push_back(validity->Serialize()); diff --git a/src/duckdb/src/storage/table/struct_column_data.cpp b/src/duckdb/src/storage/table/struct_column_data.cpp index f19efb6b4..a987c65a5 100644 --- a/src/duckdb/src/storage/table/struct_column_data.cpp +++ b/src/duckdb/src/storage/table/struct_column_data.cpp @@ -515,6 +515,18 @@ bool StructColumnData::HasAnyChanges() const { return false; } +bool StructColumnData::HasAnyUpdates() const { + if (validity->HasAnyUpdates()) { + return true; + } + for (auto &child_col : sub_columns) { + if (child_col->HasAnyUpdates()) { + return true; + } + } + return false; +} + PersistentColumnData StructColumnData::Serialize() { PersistentColumnData persistent_data(type); persistent_data.child_columns.push_back(validity->Serialize()); From b6ef3d326a3fb964e140d33b2e283f088c01ba46 Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Mon, 30 Nov 2026 13:56:02 +0000 Subject: [PATCH 6/8] Update vendored DuckDB sources to a044966347b --- .../core_functions/aggregate/holistic/mad.cpp | 9 +- .../aggregate/holistic/quantile.cpp | 49 +- .../aggregate/quantile_state.hpp | 44 +- ...nerated_extension_loader_package_build.cpp | 8 +- src/duckdb/src/common/enum_util.cpp | 25 +- src/duckdb/src/common/hive_partitioning.cpp | 2 - src/duckdb/src/common/radix_partitioning.cpp | 4 +- src/duckdb/src/common/sort/topn_heap.cpp | 7 +- .../types/column/column_data_collection.cpp | 462 ++++++++++++++---- .../types/column/partitioned_column_data.cpp | 64 +-- .../common/types/variant/variant_writer.cpp | 224 +++++---- src/duckdb/src/execution/join_hashtable.cpp | 4 - .../aggregate/physical_streaming_window.cpp | 6 +- .../operator/persistent/physical_update.cpp | 18 - .../src/function/aggregate_function.cpp | 6 +- .../scalar/system/aggregate_export.cpp | 3 + .../scalar/variant/variant_bind_utils.cpp | 46 ++ .../scalar/variant/variant_path_function.cpp | 37 +- .../function/table/version/pragma_version.cpp | 6 +- .../window/window_custom_aggregator.cpp | 26 +- .../window/window_distinct_aggregator.cpp | 2 +- .../window/window_naive_aggregator.cpp | 3 + .../function/window/window_segment_tree.cpp | 4 +- .../src/include/duckdb/common/enum_util.hpp | 8 + .../duckdb/common/radix_partitioning.hpp | 20 - .../types/column/column_data_collection.hpp | 26 + .../types/column/partitioned_column_data.hpp | 18 +- .../common/types/variant/variant_builder.hpp | 23 +- .../duckdb/common/types/variant_writer.hpp | 173 ++++--- .../duckdb/common/types/vector_buffer.hpp | 8 + .../duckdb/function/aggregate_function.hpp | 19 + .../function/scalar/variant_path_function.hpp | 16 +- .../duckdb/function/scalar/variant_utils.hpp | 45 +- .../optimizer/aggregate_reuse_internal.hpp | 17 +- .../duckdb/optimizer/column_origin.hpp | 30 ++ .../relation_statistics.hpp | 19 +- .../src/include/duckdb/parallel/pipeline.hpp | 2 + src/duckdb/src/optimizer/aggregate_reuse.cpp | 121 +---- .../optimizer/aggregate_rewrite_helper.cpp | 17 +- src/duckdb/src/optimizer/column_origin.cpp | 171 +++++++ .../src/optimizer/cte_join_filter_pusher.cpp | 2 +- .../duplicate_eliminated_domain_optimizer.cpp | 3 +- .../src/optimizer/grouping_sets_optimizer.cpp | 4 + .../join_order/cardinality_estimator.cpp | 40 +- .../materialized_aggregate_reuse.cpp | 50 +- .../optimizer/partial_aggregate_pushdown.cpp | 4 +- .../pushdown/pushdown_inner_join.cpp | 24 +- .../relation_statistics_helper.cpp | 3 +- .../relation_statistics_operator.cpp | 56 ++- .../relation_statistics_scan.cpp | 21 +- src/duckdb/src/parallel/pipeline.cpp | 1 + src/duckdb/src/parallel/pipeline_executor.cpp | 14 + src/duckdb/src/parallel/scan_read_ahead.cpp | 4 +- src/duckdb/src/storage/data_table.cpp | 14 +- .../src/storage/table/update_segment.cpp | 4 +- src/duckdb/ub_src_optimizer.cpp | 2 + 56 files changed, 1375 insertions(+), 663 deletions(-) create mode 100644 src/duckdb/src/include/duckdb/optimizer/column_origin.hpp create mode 100644 src/duckdb/src/optimizer/column_origin.cpp diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/mad.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/mad.cpp index ff14efccd..1e9359190 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/mad.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/mad.cpp @@ -175,8 +175,8 @@ struct MedianAbsoluteDeviationOperation : QuantileOperation { Vector &result, idx_t row_idx) { using MAD = MadAccessor; - auto &state = *reinterpret_cast(l_state); - auto gstate = reinterpret_cast(g_state); + auto &state = STATE::Get(l_state); + auto gstate = STATE::Get(g_state); auto &data = state.GetOrCreateWindowCursor(partition); const auto &fmask = partition.filter_mask; @@ -283,8 +283,9 @@ AggregateFunction GetTypedMedianAbsoluteDeviationAggregateFunction(const Logical fun.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); fun.SetIsHolistic(true); #if !DUCKDB_SMALLER_BINARY(mad_window) - fun.SetWindowBatchCallback(OP::template Window); - fun.SetWindowInitCallback(OP::template WindowInit); + fun.SetInitWindowStateCallback(QuantileWindowState::Init); + fun.SetWindowBatchCallback(OP::template Window, INPUT_TYPE, TARGET_TYPE>); + fun.SetWindowInitCallback(OP::template WindowInit, INPUT_TYPE>); #endif return fun; } diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp index f53fe9761..caf2bddcb 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp @@ -191,8 +191,8 @@ struct QuantileScalarOperation : public QuantileOperation { static void Window(AggregateInputData &aggr_input_data, const WindowPartitionInput &partition, const_data_ptr_t g_state, data_ptr_t l_state, const SubFrames *subframes_per_row, idx_t count, Vector &result, idx_t row_idx) { - auto &state = *reinterpret_cast(l_state); - auto gstate = reinterpret_cast(g_state); + auto &state = STATE::Get(l_state); + auto gstate = STATE::Get(g_state); auto &data = state.GetOrCreateWindowCursor(partition); const auto &fmask = partition.filter_mask; @@ -321,8 +321,8 @@ struct QuantileListOperation : QuantileOperation { static void Window(AggregateInputData &aggr_input_data, const WindowPartitionInput &partition, const_data_ptr_t g_state, data_ptr_t l_state, const SubFrames *subframes_per_row, idx_t count, Vector &list, idx_t row_idx) { - auto &state = *reinterpret_cast(l_state); - auto gstate = reinterpret_cast(g_state); + auto &state = STATE::Get(l_state); + auto gstate = STATE::Get(g_state); auto &data = state.GetOrCreateWindowCursor(partition); const auto &fmask = partition.filter_mask; @@ -449,8 +449,9 @@ struct ScalarDiscreteQuantile { auto fun = QuantileBufferingAggregate(type, type); fun.SetStructStateExport(QuantileStateLayout); #if !DUCKDB_SMALLER_BINARY(quantile_window) - fun.SetWindowBatchCallback(OP::Window); - fun.SetWindowInitCallback(OP::WindowInit); + fun.SetInitWindowStateCallback(QuantileWindowState::Init); + fun.SetWindowBatchCallback(OP::Window, INPUT_TYPE, INPUT_TYPE>); + fun.SetWindowInitCallback(OP::WindowInit, INPUT_TYPE>); #endif return fun; } @@ -460,10 +461,9 @@ struct ScalarDiscreteQuantile { using OP = QuantileScalarFallback; AggregateFunction fun({type}, type, AggregateFunction::StateSize, - AggregateFunction::StateInitialize, - QuantileSortKeyUpdate, ListCombineFunction, - AggregateFunction::StateVoidFinalize, nullptr, nullptr, - AggregateFunction::StateDestroy); + AggregateFunction::StateInitialize, QuantileSortKeyUpdate, + ListCombineFunction, AggregateFunction::StateVoidFinalize, nullptr, + nullptr); fun.SetInitLocalStateFinalizeCallback(FlattenedQuantileValues::Init); fun.SetStructStateExport(QuantileStateLayout>>>); return fun; @@ -480,8 +480,9 @@ struct ListDiscreteQuantile { fun.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); fun.SetIsHolistic(true); #if !DUCKDB_SMALLER_BINARY(quantile_window) - fun.SetWindowBatchCallback(OP::template Window); - fun.SetWindowInitCallback(OP::template WindowInit); + fun.SetInitWindowStateCallback(QuantileWindowState::Init); + fun.SetWindowBatchCallback(OP::template Window, INPUT_TYPE, list_entry_t>); + fun.SetWindowInitCallback(OP::template WindowInit, INPUT_TYPE>); #endif return fun; } @@ -491,10 +492,9 @@ struct ListDiscreteQuantile { using OP = QuantileListFallback; AggregateFunction fun({type}, LogicalType::LIST(type), AggregateFunction::StateSize, - AggregateFunction::StateInitialize, - QuantileSortKeyUpdate, ListCombineFunction, - AggregateFunction::StateFinalize, nullptr, nullptr, - AggregateFunction::StateDestroy); + AggregateFunction::StateInitialize, QuantileSortKeyUpdate, + ListCombineFunction, AggregateFunction::StateFinalize, + nullptr, nullptr); fun.SetInitLocalStateFinalizeCallback(FlattenedQuantileValues::Init); fun.SetStructStateExport(QuantileStateLayout>>>); return fun; @@ -590,8 +590,9 @@ struct ScalarContinuousQuantile { fun.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); fun.SetIsHolistic(true); #if !DUCKDB_SMALLER_BINARY(quantile_window) - fun.SetWindowBatchCallback(OP::template Window); - fun.SetWindowInitCallback(OP::template WindowInit); + fun.SetInitWindowStateCallback(QuantileWindowState::Init); + fun.SetWindowBatchCallback(OP::template Window, INPUT_TYPE, TARGET_TYPE>); + fun.SetWindowInitCallback(OP::template WindowInit, INPUT_TYPE>); #endif return fun; } @@ -607,8 +608,9 @@ struct ListContinuousQuantile { fun.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); fun.SetIsHolistic(true); #if !DUCKDB_SMALLER_BINARY(quantile_window) - fun.SetWindowBatchCallback(OP::template Window); - fun.SetWindowInitCallback(OP::template WindowInit); + fun.SetInitWindowStateCallback(QuantileWindowState::Init); + fun.SetWindowBatchCallback(OP::template Window, INPUT_TYPE, list_entry_t>); + fun.SetWindowInitCallback(OP::template WindowInit, INPUT_TYPE>); #endif return fun; } @@ -731,8 +733,13 @@ static LogicalType InterpolationType(const LogicalType &type) { struct MedianFunction { static AggregateFunction GetAggregate(const LogicalType &type) { - auto fun = CanInterpolate(type) ? GetContinuousQuantile(type) : GetDiscreteQuantile(type); + const auto can_interpolate = CanInterpolate(type); + auto fun = can_interpolate ? GetContinuousQuantile(type) : GetDiscreteQuantile(type); fun.SetName("median"); + fun.SetIsHolistic(true); + // Only medians without window callbacks reach the trees. Discrete ones such as the sort-key fallback keep them + // because naive is quadratic on running frames, and continuous ones stay naive like quantile_cont + fun.SetAllowsWindowTrees(!can_interpolate); fun.SetSerializeCallback(QuantileBindData::Serialize); fun.SetDeserializeCallback(Deserialize); return fun; diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp index efc396ed4..e6aba7211 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp @@ -75,11 +75,6 @@ struct QuantileOperation { return aggr_input_data.function.GetArguments()[0]; } - template - static void Destroy(STATE &state, AggregateInputData &) { - state.~STATE(); - } - template static void WindowInit(AggregateInputData &aggr_input_data, const WindowPartitionInput &partition, data_ptr_t g_state) { @@ -99,7 +94,7 @@ struct QuantileOperation { } // Build the tree - auto &state = *reinterpret_cast(g_state); + auto &state = STATE::Get(g_state); auto &window_state = state.GetOrCreateWindowState(); window_state.qst = make_uniq(aggr_input_data, partition); } @@ -132,12 +127,10 @@ struct QuantileOperation { //! update callback is handed it along with the input and simply does not read it template AggregateFunction QuantileBufferingAggregate(const LogicalType &input_type, const LogicalType &result_type) { - AggregateFunction fun({}, result_type, AggregateFunction::StateSize, - AggregateFunction::StateInitialize, - ListUpdateFunction, ListCombineFunction, - AggregateFunction::StateFinalize, - FunctionNullHandling::DEFAULT_NULL_HANDLING, AggregateFunction::NoClusterUpdate(), - AggregateFunction::NoBind(), AggregateFunction::StateDestroy); + AggregateFunction fun( + {}, result_type, AggregateFunction::StateSize, AggregateFunction::StateInitialize, + ListUpdateFunction, ListCombineFunction, AggregateFunction::StateFinalize, + FunctionNullHandling::DEFAULT_NULL_HANDLING, AggregateFunction::NoClusterUpdate(), AggregateFunction::NoBind()); fun.GetSignature().AddParameter("x", input_type); fun.SetInitLocalStateFinalizeCallback(FlattenedQuantileValues::Init); return fun; @@ -319,12 +312,29 @@ struct WindowQuantileState { template struct QuantileState : ListAggState { using InputType = INPUT_TYPE; +}; + +//! The state of the custom window callbacks +template +struct QuantileWindowState : FunctionLocalState { using CursorType = QuantileCursor; - // Window Quantile State (only used for window execution) unique_ptr> window_state; unique_ptr window_cursor; + static unique_ptr Init(AggregateStateInput &) { + return make_uniq(); + } + static QuantileWindowState &Get(data_ptr_t state) { + return reinterpret_cast(state)->Cast(); + } + static const QuantileWindowState *Get(const_data_ptr_t state) { + if (!state) { + return nullptr; + } + return &reinterpret_cast(state)->Cast(); + } + bool HasTree() const { return window_state && window_state->HasTree(); } @@ -417,13 +427,7 @@ template >> AggregateStateLayout QuantileStateLayout(AggregateLayoutInput &input) { auto &function = input.function; AggregateStateLayout layout; - if (function.ReturnsExportedState()) { - // the function has been modified for state export (see ExportAggregateFunction::SetStateExport) - - // its return type IS the state type already - layout.type = function.GetReturnType(); - } else { - layout.type = LogicalType::LIST(function.GetArguments()[0]); - } + layout.type = LogicalType::LIST(function.GetArguments()[0]); layout.total_state_size = AlignValue(sizeof(STATE)); layout.field = BuildStateField(); // NULL inputs are never buffered, so the finalize assumes all values are valid diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 14965f69f..b2f66228b 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-alpha58324"; + descriptor->api_version = "v2.1.0-alpha58348"; 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-alpha58324"; + descriptor->api_version = "v2.1.0-alpha58348"; 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-alpha58324"; + descriptor->api_version = "v2.1.0-alpha58348"; 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-alpha58324"; + descriptor->api_version = "v2.1.0-alpha58348"; 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 4df1fdfaa..9dd3ae415 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -947,6 +947,24 @@ AsyncResultsExecutionMode EnumUtil::FromString(const return static_cast(StringUtil::StringToEnum(GetAsyncResultsExecutionModeValues(), 2, "AsyncResultsExecutionMode", value)); } +const StringUtil::EnumStringLiteral *GetAuxiliaryDataTypeValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(AuxiliaryDataType::GENERIC), "GENERIC" }, + { static_cast(AuxiliaryDataType::VARIANT_WRITER_STATE), "VARIANT_WRITER_STATE" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(AuxiliaryDataType value) { + return StringUtil::EnumToString(GetAuxiliaryDataTypeValues(), 2, "AuxiliaryDataType", static_cast(value)); +} + +template<> +AuxiliaryDataType EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetAuxiliaryDataTypeValues(), 2, "AuxiliaryDataType", value)); +} + const StringUtil::EnumStringLiteral *GetBaseColumnPrunerModeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(BaseColumnPrunerMode::DEFAULT), "DEFAULT" }, @@ -2160,19 +2178,20 @@ const StringUtil::EnumStringLiteral *GetDistinctCountSourceValues() { { static_cast(DistinctCountSource::CARDINALITY), "CARDINALITY" }, { static_cast(DistinctCountSource::MIN_MAX), "MIN_MAX" }, { static_cast(DistinctCountSource::HLL), "HLL" }, - { static_cast(DistinctCountSource::EXACT), "EXACT" } + { static_cast(DistinctCountSource::EXACT), "EXACT" }, + { static_cast(DistinctCountSource::COMBINED), "COMBINED" } }; return values; } template<> const char* EnumUtil::ToChars(DistinctCountSource value) { - return StringUtil::EnumToString(GetDistinctCountSourceValues(), 4, "DistinctCountSource", static_cast(value)); + return StringUtil::EnumToString(GetDistinctCountSourceValues(), 5, "DistinctCountSource", static_cast(value)); } template<> DistinctCountSource EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetDistinctCountSourceValues(), 4, "DistinctCountSource", value)); + return static_cast(StringUtil::StringToEnum(GetDistinctCountSourceValues(), 5, "DistinctCountSource", value)); } const StringUtil::EnumStringLiteral *GetDistinctTypeValues() { diff --git a/src/duckdb/src/common/hive_partitioning.cpp b/src/duckdb/src/common/hive_partitioning.cpp index 44b53db5f..963b86051 100644 --- a/src/duckdb/src/common/hive_partitioning.cpp +++ b/src/duckdb/src/common/hive_partitioning.cpp @@ -565,11 +565,9 @@ void HivePartitionedColumnData::AddNewPartition(HivePartitionKey key, idx_t part if (state.partition_append_states.size() <= partition_id) { state.partition_append_states.resize(partition_id + 1); - state.partition_buffers.resize(partition_id + 1); partitions.resize(partition_id + 1); } state.partition_append_states[partition_id] = make_uniq(); - state.partition_buffers[partition_id] = CreatePartitionBuffer(); partitions[partition_id] = CreatePartitionCollection(0); partitions[partition_id]->InitializeAppend(*state.partition_append_states[partition_id]); } diff --git a/src/duckdb/src/common/radix_partitioning.cpp b/src/duckdb/src/common/radix_partitioning.cpp index 3d61d5d6f..166e40115 100644 --- a/src/duckdb/src/common/radix_partitioning.cpp +++ b/src/duckdb/src/common/radix_partitioning.cpp @@ -127,11 +127,9 @@ RadixPartitionedColumnData::~RadixPartitionedColumnData() { void RadixPartitionedColumnData::InitializeAppendStateInternal(PartitionedColumnDataAppendState &state) const { const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits); state.partition_append_states.reserve(num_partitions); - state.partition_buffers.reserve(num_partitions); for (idx_t i = 0; i < num_partitions; i++) { state.partition_append_states.emplace_back(make_uniq()); partitions[i]->InitializeAppend(*state.partition_append_states[i]); - state.partition_buffers.emplace_back(CreatePartitionBuffer()); } // Initialize fixed-size map @@ -140,7 +138,7 @@ void RadixPartitionedColumnData::InitializeAppendStateInternal(PartitionedColumn void RadixPartitionedColumnData::ComputePartitionIndices(PartitionedColumnDataAppendState &state, DataChunk &input) { D_ASSERT(partitions.size() == RadixPartitioning::NumberOfPartitions(radix_bits)); - D_ASSERT(state.partition_buffers.size() == RadixPartitioning::NumberOfPartitions(radix_bits)); + D_ASSERT(state.partition_append_states.size() == RadixPartitioning::NumberOfPartitions(radix_bits)); RadixBitsSwitch(radix_bits, input.data[hash_col_idx], state.partition_indices, input.size(), *FlatVector::IncrementalSelectionVector(), input.size()); diff --git a/src/duckdb/src/common/sort/topn_heap.cpp b/src/duckdb/src/common/sort/topn_heap.cpp index 305035c56..f1a823336 100644 --- a/src/duckdb/src/common/sort/topn_heap.cpp +++ b/src/duckdb/src/common/sort/topn_heap.cpp @@ -572,13 +572,12 @@ void TopNHeap::Reduce() { entry.index = i; } - // copy over the data from the current payload chunk to the new payload chunk - new_heap_data.Slice(heap_data, new_payload_sel, heap.size()); - new_heap_data.Flatten(); + // Copy the survivors so the old payload's string heaps can be released. + heap_data.Copy(new_heap_data, new_payload_sel, heap.size()); sort_key_heap.Destroy(); sort_key_heap.Move(new_sort_heap); - heap_data.Reference(new_heap_data); + heap_data.Move(new_heap_data); } void TopNHeap::InitializeScan(TopNScanState &state, bool exclude_offset) { 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 fcc9c5dd4..2e630fc33 100644 --- a/src/duckdb/src/common/types/column/column_data_collection.cpp +++ b/src/duckdb/src/common/types/column/column_data_collection.cpp @@ -39,7 +39,7 @@ struct ColumnDataMetaData { ColumnDataMetaData(ColumnDataCopyFunction ©_function, ColumnDataMetaData &parent, VectorDataIndex vector_data_index) : copy_function(copy_function), segment(parent.segment), state(parent.state), chunk_data(parent.chunk_data), - vector_data_index(vector_data_index) { + vector_data_index(vector_data_index), child_selections(parent.child_selections), depth(parent.depth + 1) { } ColumnDataCopyFunction ©_function; @@ -47,6 +47,10 @@ struct ColumnDataMetaData { ColumnDataAppendState &state; ChunkMetaData &chunk_data; VectorDataIndex vector_data_index; + //! Where the copies of nested columns build their children's selections + optional_ptr child_selections; + //! The nesting depth of the column, 0 for a top-level column + idx_t depth = 0; idx_t child_list_size = DConstants::INVALID_INDEX; VectorMetaData &GetVectorMetaData() { @@ -54,6 +58,43 @@ struct ColumnDataMetaData { } }; +//! Selections and validity masks over the children of nested columns, one per nesting depth, reused by the appends +//! of one call +struct ColumnDataChildSelections { + vector> by_depth; + vector> masks_by_depth; +}; + +//! A selection of at least `count` entries over the children of the column that `meta_data` copies. There is one +//! per nesting depth, so a child's copy does not overwrite the selection its parent reads through. +static SelectionVector &ChildSelection(ColumnDataMetaData &meta_data, idx_t count) { + D_ASSERT(meta_data.child_selections); + auto &selections = meta_data.child_selections->by_depth; + while (selections.size() <= meta_data.depth) { + selections.push_back(make_uniq()); + } + auto &sel = *selections[meta_data.depth]; + if (sel.Capacity() < count) { + sel.Initialize(NextPowerOfTwo(count)); + } + return sel; +} + +//! An all-valid mask of at least `capacity` rows for the children of the column that `meta_data` copies, one per +//! nesting depth. The caller sets valid again every row it sets invalid. +static ValidityMask &ChildValidity(ColumnDataMetaData &meta_data, idx_t capacity) { + D_ASSERT(meta_data.child_selections); + auto &masks = meta_data.child_selections->masks_by_depth; + while (masks.size() <= meta_data.depth) { + masks.push_back(make_uniq()); + } + auto &mask = *masks[meta_data.depth]; + if (!mask.IsMaskSet() || mask.Capacity() < capacity) { + mask.Initialize(capacity); + } + return mask; +} + //! Explicitly initialized without types ColumnDataCollection::ColumnDataCollection(Allocator &allocator_p) { types.clear(); @@ -848,31 +889,33 @@ 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) { +//! Whether 'length' list elements of 'child_type' appended into the list's child chain are stored as a single +//! LARGE_FLAT entry, so scans read them without copying: a chain that is still empty, of a buffer-managed collection, +//! longer than a vector, of a constant-size type +static bool StoresLargeListChild(ColumnDataMetaData &meta_data, const LogicalType &child_type, idx_t length) { + if (meta_data.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; - } + return ColumnDataCollectionSegment::GetDataSize(type_size, length) + ValidityMask::ValidityMaskSize(length) <= + MAXIMUM_LARGE_LIST_CHILD_SIZE; +} +//! Stores the elements at positions [source_offset, source_offset + length) of 'sel' over 'child_vector' as the list's +//! LARGE_FLAT child entry (StoresLargeListChild) +static void AppendLargeListChild(ColumnDataMetaData &meta_data, Vector &child_vector, const SelectionVector &sel, + idx_t source_offset, idx_t length) { + auto &segment = meta_data.segment; + auto &child_type = child_vector.GetType(); + const auto type_size = GetTypeIdSize(child_type.InternalType()); 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); @@ -880,15 +923,7 @@ static bool TryAppendLargeListChild(ColumnDataMetaData &meta_data, Vector &sourc 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); - } + VectorOperations::Copy(child_vector, target, sel, source_offset + length, source_offset, 0, length); auto validity_data = ColumnDataCollectionSegment::GetValidityPointerForWriting(base_ptr, type_size, length); auto &target_validity = FlatVector::Validity(target); if (target_validity.CanHaveNull()) { @@ -896,9 +931,61 @@ static bool TryAppendLargeListChild(ColumnDataMetaData &meta_data, Vector &sourc } else { ValidityMask(validity_data, length).SetAllValid(length); } +} + +//! Stores the consecutive list children of rows [offset, offset + copy_count) as a LARGE_FLAT entry where +//! StoresLargeListChild allows it. Returns false if they 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) { + const auto length = info.child_list_info.length; + if (!StoresLargeListChild(meta_data, child_vector.GetType(), length)) { + return false; + } + if (info.needs_slicing) { + SelectionVector sel(length); + ListVector::GetConsecutiveChildSelVector(source, sel, offset, copy_count); + AppendLargeListChild(meta_data, child_vector, sel, 0, length); + } else { + AppendLargeListChild(meta_data, child_vector, *FlatVector::IncrementalSelectionVector(), + info.child_list_info.offset, length); + } return true; } +//! The first entry of the chain a list column's elements are appended to, allocated when there is none yet +static VectorDataIndex ListChildChain(ColumnDataMetaData &meta_data, const LogicalType &child_type) { + auto &segment = meta_data.segment; + 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 = segment.AddChildIndex(child_index); + } + return segment.GetChildIndex(meta_data.GetVectorMetaData().child_index); +} + +//! Copies the list entries of rows [offset, offset + copy_count), their elements following the 'list_size' the child +//! chain held before: one shared entry when 'is_constant' +static void CopyListEntries(ColumnDataMetaData &meta_data, const UnifiedVectorFormat &source_data, Vector &source, + idx_t offset, idx_t copy_count, idx_t list_size, bool is_constant) { + meta_data.child_list_size = list_size; + if (is_constant) { + TemplatedColumnDataCopy(meta_data, source_data, source, offset, copy_count); + } else { + TemplatedColumnDataCopy(meta_data, source_data, source, offset, copy_count); + } +} + +//! Calls 'f' with the list entry of each valid row at positions [offset, offset + count) of 'source_data' +template +static void ForEachSelectedList(const UnifiedVectorFormat &source_data, const list_entry_t *entries, idx_t offset, + idx_t count, F &&f) { + for (idx_t i = 0; i < count; i++) { + auto idx = source_data.sel->get_index(offset + i); + if (source_data.validity.RowIsValid(idx)) { + f(entries[idx]); + } + } +} + template <> void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVectorFormat &source_data, Vector &source, idx_t offset, idx_t copy_count) { @@ -906,7 +993,6 @@ void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVe auto &child_vector = ListVector::GetChildMutable(source); auto &child_type = child_vector.GetType(); - 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; @@ -919,13 +1005,59 @@ void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVe } } - 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); + if (source_data.sel->IsSet()) { + auto entries = UnifiedVectorFormat::GetData(source_data); + idx_t element_count = 0; + // whether every selected list is the same entry, as in a flattened constant: its elements are stored once + optional_ptr first; + bool all_same = true; + ForEachSelectedList(source_data, entries, offset, copy_count, [&](const list_entry_t &entry) { + element_count += entry.length; + if (!first) { + first = &entry; + } else if (entry.offset != first->offset || entry.length != first->length) { + all_same = false; + } + }); + const bool is_constant = first && all_same; + const idx_t length = is_constant ? first->length : element_count; + const bool large = StoresLargeListChild(meta_data, child_type, length); + // a LARGE_FLAT copy reads the child vector's rows, the copy functions the rows of its data + UnifiedVectorFormat child_vector_data; + if (large) { + child_vector_data.sel = FlatVector::IncrementalSelectionVector(); + } else { + child_vector.ToUnifiedFormat(child_vector_data); + } + const idx_t child_offset = is_constant ? first->offset : 0; + if (!is_constant && length > 0) { + // the elements of the selected lists, in order + auto &element_sel = ChildSelection(meta_data, length); + idx_t element = 0; + ForEachSelectedList(source_data, entries, offset, copy_count, [&](const list_entry_t &entry) { + for (idx_t j = 0; j < entry.length; j++) { + element_sel.set_index(element++, child_vector_data.sel->get_index(entry.offset + j)); + } + }); + child_vector_data.sel = &element_sel; } + if (large) { + AppendLargeListChild(meta_data, child_vector, *child_vector_data.sel, child_offset, length); + } else { + // the chain is allocated even for no elements, as a scan of the list reads its child chain + auto &child_function = meta_data.copy_function.child_functions[0]; + ColumnDataMetaData child_meta_data(child_function, meta_data, ListChildChain(meta_data, child_type)); + if (length > 0) { + child_function.function(child_meta_data, child_vector_data, child_vector, child_offset, length); + } + } + CopyListEntries(meta_data, source_data, source, offset, copy_count, current_list_size, is_constant); + return; + } + auto info = ListVector::GetConsecutiveChildListInfo(source, offset, copy_count); + if (!TryAppendLargeListChild(meta_data, source, child_vector, info, offset, copy_count)) { auto &child_function = meta_data.copy_function.child_functions[0]; - auto child_index = segment.GetChildIndex(meta_data.GetVectorMetaData().child_index); + auto child_index = ListChildChain(meta_data, child_type); // set the child vector UnifiedVectorFormat child_vector_data; @@ -950,12 +1082,7 @@ void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVe } // now copy the list entries - meta_data.child_list_size = current_list_size; - if (info.is_constant) { - TemplatedColumnDataCopy(meta_data, source_data, source, offset, copy_count); - } else { - TemplatedColumnDataCopy(meta_data, source_data, source, offset, copy_count); - } + CopyListEntries(meta_data, source_data, source, offset, copy_count, current_list_size, info.is_constant); } void ColumnDataCopyStruct(ColumnDataMetaData &meta_data, const UnifiedVectorFormat &source_data, Vector &source, @@ -976,9 +1103,89 @@ void ColumnDataCopyStruct(ColumnDataMetaData &meta_data, const UnifiedVectorForm UnifiedVectorFormat child_data; child_vectors[child_idx].ToUnifiedFormat(child_data); + idx_t child_offset = offset; + if (source_data.sel->IsSet() && !child_data.sel->IsSet()) { + // a field's row is the struct's row at the same index + child_data.sel = source_data.sel; + } else if (source_data.sel->IsSet()) { + // the copied rows' positions in the field; the fields are copied one after another + auto &field_sel = ChildSelection(meta_data, copy_count); + for (idx_t i = 0; i < copy_count; i++) { + field_sel.set_index(i, child_data.sel->get_index(source_data.sel->get_index(offset + i))); + } + child_data.sel = &field_sel; + child_offset = 0; + } + child_function.function(child_meta_data, child_data, child_vectors[child_idx], child_offset, copy_count); + } +} + +// Whether a NULL array row's elements must be NULL in their own vectors, not only in the array's child validity: a +// struct's fields must be NULL under a NULL struct, and a list copy writes the elements of every list it sees. +static bool ElementsNeedOwnNulls(const LogicalType &type) { + switch (type.InternalType()) { + case PhysicalType::STRUCT: + case PhysicalType::LIST: + return true; + case PhysicalType::ARRAY: + return ElementsNeedOwnNulls(ArrayType::GetChildType(type)); + default: + return false; + } +} - child_function.function(child_meta_data, child_data, child_vectors[child_idx], offset, copy_count); +// Copies the elements of rows [offset, offset + copy_count) of an array, some of them NULL, as NULL under the NULL +// rows. The input is not changed. +static void CopyArrayElementsUnderNullRows(ColumnDataMetaData &meta_data, ColumnDataMetaData &child_meta_data, + ColumnDataCopyFunction &child_function, + const UnifiedVectorFormat &source_data, Vector &child_vector, + idx_t array_size, idx_t offset, idx_t copy_count) { + const idx_t child_count = copy_count * array_size; + if (!ElementsNeedOwnNulls(child_vector.GetType())) { + // the elements' validity, NULL under the NULL rows, in a mask of their own + UnifiedVectorFormat child_data; + child_vector.ToUnifiedFormat(child_data); + auto &element_sel = ChildSelection(meta_data, child_count); + auto &validity = ChildValidity(meta_data, child_data.validity.Capacity()); + for (idx_t i = 0; i < copy_count; i++) { + auto source_idx = source_data.sel->get_index(offset + i); + const bool row_valid = source_data.validity.RowIsValid(source_idx); + for (idx_t j = 0; j < array_size; j++) { + auto idx = child_data.sel->get_index(source_idx * array_size + j); + element_sel.set_index(i * array_size + j, idx); + if (!row_valid || !child_data.validity.RowIsValid(idx)) { + validity.SetInvalid(idx); + } + } + } + child_data.sel = &element_sel; + child_data.validity = validity; + child_function.function(child_meta_data, child_data, child_vector, 0, child_count); + for (idx_t i = 0; i < child_count; i++) { + validity.SetValid(element_sel.get_index(i)); + } + return; + } + SelectionVector element_sel(child_count); + for (idx_t i = 0; i < copy_count; i++) { + auto source_idx = source_data.sel->get_index(offset + i); + for (idx_t j = 0; j < array_size; j++) { + element_sel.set_index(i * array_size + j, source_idx * array_size + j); + } + } + // FlatVector::SetNull makes a nested element NULL in its own vectors too, in a copy of the elements + Vector elements(child_vector.GetType(), child_count); + VectorOperations::Copy(child_vector, elements, element_sel, child_count, 0, 0); + for (idx_t i = 0; i < copy_count; i++) { + if (!source_data.validity.RowIsValid(source_data.sel->get_index(offset + i))) { + for (idx_t j = 0; j < array_size; j++) { + FlatVector::SetNull(elements, i * array_size + j, true); + } + } } + UnifiedVectorFormat elements_data; + elements.ToUnifiedFormat(elements_data); + child_function.function(child_meta_data, elements_data, elements, 0, child_count); } void ColumnDataCopyArray(ColumnDataMetaData &meta_data, const UnifiedVectorFormat &source_data, Vector &source, @@ -999,41 +1206,45 @@ void ColumnDataCopyArray(ColumnDataMetaData &meta_data, const UnifiedVectorForma auto &child_function = meta_data.copy_function.child_functions[0]; auto child_index = segment.GetChildIndex(meta_data.GetVectorMetaData().child_index); + ColumnDataMetaData child_meta_data(child_function, meta_data, child_index); - auto current_child_index = child_index; - while (current_child_index.IsValid()) { - auto &child_vdata = segment.GetVectorData(current_child_index); - current_child_index = child_vdata.next_data; + bool any_null = false; + if (source_data.validity.CanHaveNull()) { + for (idx_t i = 0; i < copy_count && !any_null; i++) { + any_null = !source_data.validity.RowIsValid(source_data.sel->get_index(offset + i)); + } + } + if (any_null) { + CopyArrayElementsUnderNullRows(meta_data, child_meta_data, child_function, source_data, child_vector, + array_size, offset, copy_count); + return; } - UnifiedVectorFormat child_vector_data; - ColumnDataMetaData child_meta_data(child_function, meta_data, child_index); child_vector.ToUnifiedFormat(child_vector_data); - - // Broadcast and sync the validity of the array vector to the child vector - // This requires creating a copy of the validity mask: we cannot modify the input validity - child_vector_data.validity = ValidityMask(child_vector_data.validity, child_vector_data.validity.Capacity()); - if (source_data.validity.IsMaskSet()) { + if (source.GetVectorType() == VectorType::CONSTANT_VECTOR) { + // a constant array: copy its child once per row for (idx_t i = 0; i < copy_count; i++) { - auto source_idx = source_data.sel->get_index(offset + i); - if (!source_data.validity.RowIsValid(source_idx)) { - for (idx_t j = 0; j < array_size; j++) { - child_vector_data.validity.SetInvalid(source_idx * array_size + j); - } - } + child_function.function(child_meta_data, child_vector_data, child_vector, 0, array_size); } + return; } - - auto is_constant = source.GetVectorType() == VectorType::CONSTANT_VECTOR; - // If the array is constant, we need to copy the child vector n times - if (is_constant) { + if (source_data.sel->IsSet()) { + // the elements of the selected rows, through the child's own selection + const idx_t child_count = copy_count * array_size; + auto &element_sel = ChildSelection(meta_data, child_count); for (idx_t i = 0; i < copy_count; i++) { - child_function.function(child_meta_data, child_vector_data, child_vector, 0, array_size); + auto source_idx = source_data.sel->get_index(offset + i); + for (idx_t j = 0; j < array_size; j++) { + element_sel.set_index(i * array_size + j, + child_vector_data.sel->get_index(source_idx * array_size + j)); + } } - } else { - child_function.function(child_meta_data, child_vector_data, child_vector, offset * array_size, - copy_count * array_size); + child_vector_data.sel = &element_sel; + child_function.function(child_meta_data, child_vector_data, child_vector, 0, child_count); + return; } + child_function.function(child_meta_data, child_vector_data, child_vector, offset * array_size, + copy_count * array_size); } ColumnDataCopyFunction ColumnDataCollection::GetCopyFunction(const LogicalType &type) { @@ -1426,6 +1637,16 @@ static void MaterializeDictionaryEntry(ColumnDataMetaData &meta_data, const Logi vdata.dictionary_slot = DConstants::INVALID_INDEX; } +//! Writes a constant or dictionary entry out as flat rows, so that rows can be copied after it +static void MaterializeCompactEntry(ColumnDataMetaData &meta_data, const LogicalType &type) { + auto representation = meta_data.GetVectorMetaData().representation; + if (representation == ColumnDataRepresentation::CONSTANT) { + MaterializeConstantEntry(meta_data, type); + } else if (representation == ColumnDataRepresentation::DICTIONARY) { + MaterializeDictionaryEntry(meta_data, type); + } +} + static bool TryAppendCompactVector(ColumnDataMetaData &meta_data, const UnifiedVectorFormat &source_data, Vector &source, idx_t offset, idx_t copy_count) { if (meta_data.segment.allocator->IsManagedResultSet()) { @@ -1435,17 +1656,9 @@ static bool TryAppendCompactVector(ColumnDataMetaData &meta_data, const UnifiedV auto &vdata = meta_data.GetVectorMetaData(); switch (vdata.representation) { case ColumnDataRepresentation::CONSTANT: - if (TryExtendConstantEntry(meta_data, source_data, source, offset, copy_count)) { - return true; - } - MaterializeConstantEntry(meta_data, source.GetType()); - return false; + return TryExtendConstantEntry(meta_data, source_data, source, offset, copy_count); case ColumnDataRepresentation::DICTIONARY: - if (TryExtendDictionaryEntry(meta_data, source_data, source, offset, copy_count)) { - return true; - } - MaterializeDictionaryEntry(meta_data, source.GetType()); - return false; + return TryExtendDictionaryEntry(meta_data, source_data, source, offset, copy_count); default: break; } @@ -1473,35 +1686,32 @@ static bool IsComplexType(const LogicalType &type) { }; } -void ColumnDataCollection::Append(ColumnDataAppendState &state, DataChunk &input) { +void ColumnDataCollection::AppendRows(ColumnDataAppendState &state, const vector &formats, + DataChunk &input, idx_t input_offset, idx_t append_count, bool keep_compact, + ColumnDataChildSelections &child_selections) { D_ASSERT(!finished_append); - { - auto input_types = input.GetTypes(); - D_ASSERT(types == input_types); - } - - auto &segment = *segments.back(); +#ifdef D_ASSERT_IS_ENABLED for (idx_t vector_idx = 0; vector_idx < types.size(); vector_idx++) { - if (IsComplexType(input.data[vector_idx].GetType())) { - input.data[vector_idx].Flatten(); - } - input.data[vector_idx].ToUnifiedFormat(state.vector_data[vector_idx]); + D_ASSERT(input.data[vector_idx].GetType() == types[vector_idx]); } - - idx_t remaining = input.size(); +#endif + auto &segment = *segments.back(); + idx_t remaining = append_count; while (remaining > 0) { auto &chunk_data = segment.chunk_data.back(); idx_t append_amount = MinValue(remaining, STANDARD_VECTOR_SIZE - chunk_data.count); if (append_amount > 0) { - idx_t offset = input.size() - remaining; + const idx_t offset = input_offset + append_count - remaining; for (idx_t vector_idx = 0; vector_idx < types.size(); vector_idx++) { ColumnDataMetaData meta_data(copy_functions[vector_idx], segment, state, chunk_data, chunk_data.vector_data[vector_idx]); + meta_data.child_selections = &child_selections; const auto allocated_before = segment.total_allocated; - if (!TryAppendCompactVector(meta_data, state.vector_data[vector_idx], input.data[vector_idx], offset, - append_amount)) { - copy_functions[vector_idx].function(meta_data, state.vector_data[vector_idx], - input.data[vector_idx], offset, append_amount); + if (!keep_compact || !TryAppendCompactVector(meta_data, formats[vector_idx], input.data[vector_idx], + offset, append_amount)) { + MaterializeCompactEntry(meta_data, types[vector_idx]); + copy_functions[vector_idx].function(meta_data, formats[vector_idx], input.data[vector_idx], offset, + append_amount); } chunk_data.allocation_sizes[vector_idx] += segment.total_allocated - allocated_before; } @@ -1509,14 +1719,80 @@ void ColumnDataCollection::Append(ColumnDataAppendState &state, DataChunk &input } remaining -= append_amount; if (remaining > 0) { - // more to do - // allocate a new chunk segment.AllocateNewChunk(); segment.InitializeChunkState(segment.chunk_data.size() - 1, state.current_chunk_state); } } - segment.count += input.size(); - count += input.size(); + segment.count += append_count; + count += append_count; +} + +void ColumnDataCollection::Append(ColumnDataAppendState &state, DataChunk &input) { +#ifdef D_ASSERT_IS_ENABLED + D_ASSERT(types == input.GetTypes()); +#endif + for (idx_t vector_idx = 0; vector_idx < types.size(); vector_idx++) { + if (IsComplexType(input.data[vector_idx].GetType())) { + input.data[vector_idx].Flatten(); + } + input.data[vector_idx].ToUnifiedFormat(state.vector_data[vector_idx]); + } + ColumnDataChildSelections child_selections; + AppendRows(state, state.vector_data, input, 0, input.size(), true, child_selections); +} + +void ColumnDataCollection::PrepareSelectedFormats(DataChunk &input, idx_t column_count, const SelectionVector &sel, + idx_t sel_count, vector &formats) { + D_ASSERT(input.ColumnCount() >= column_count); + D_ASSERT(sel_count <= STANDARD_VECTOR_SIZE); + D_ASSERT(formats.size() >= column_count); + // each column's format reads its rows through `sel` + for (idx_t vector_idx = 0; vector_idx < column_count; vector_idx++) { + auto &vector = input.data[vector_idx]; + if (IsComplexType(vector.GetType())) { + vector.Flatten(); + } + auto &format = formats[vector_idx]; + vector.ToUnifiedFormat(format); + if (vector.GetVectorType() == VectorType::CONSTANT_VECTOR) { + continue; + } + if (!format.sel->IsSet()) { + format.sel = &sel; + continue; + } + format.owned_sel.Initialize(format.sel->Slice(sel, sel_count)); + format.sel = &format.owned_sel; + } +} + +void ColumnDataCollection::Append(ColumnDataAppendState &state, DataChunk &input, const SelectionVector &sel, + idx_t append_count) { + PrepareSelectedFormats(input, types.size(), sel, append_count, state.vector_data); + ColumnDataChildSelections child_selections; + AppendRows(state, state.vector_data, input, 0, append_count, false, child_selections); +} + +void ColumnDataCollection::AppendBatch(DataChunk &input, const SelectionVector &sel, idx_t sel_count, + const vector &targets) { + if (targets.empty()) { + return; + } + const idx_t column_count = targets[0].collection.ColumnCount(); + // the formats are built once for all targets, which read different positions of `sel` + vector formats(column_count); + PrepareSelectedFormats(input, column_count, sel, sel_count, formats); + // the targets are appended one after another, so they share the selections over nested columns' children + ColumnDataChildSelections child_selections; + for (auto &target : targets) { + D_ASSERT(target.collection.ColumnCount() == column_count); + D_ASSERT(target.begin <= target.end && target.end <= sel_count); + if (target.begin == target.end) { + continue; + } + target.collection.AppendRows(target.state, formats, input, target.begin, target.end - target.begin, false, + child_selections); + } } void ColumnDataCollection::Append(DataChunk &input) { diff --git a/src/duckdb/src/common/types/column/partitioned_column_data.cpp b/src/duckdb/src/common/types/column/partitioned_column_data.cpp index a2ad87e64..3ff3266cb 100644 --- a/src/duckdb/src/common/types/column/partitioned_column_data.cpp +++ b/src/duckdb/src/common/types/column/partitioned_column_data.cpp @@ -30,7 +30,6 @@ PartitionedColumnData::~PartitionedColumnData() { void PartitionedColumnData::InitializeAppendState(PartitionedColumnDataAppendState &state) const { state.partition_sel.Initialize(); - state.slice_chunk.Initialize(BufferAllocator::Get(context), types); InitializeAppendStateInternal(state); } @@ -38,12 +37,6 @@ bool PartitionedColumnData::UseFixedSizeMap() const { return MaxPartitionIndex() < PartitionedTupleDataAppendState::MAP_THRESHOLD; } -unique_ptr PartitionedColumnData::CreatePartitionBuffer() const { - auto result = make_uniq(); - result->Initialize(BufferAllocator::Get(context), types, BufferSize()); - return result; -} - void PartitionedColumnData::Append(PartitionedColumnDataAppendState &state, DataChunk &input) { // Compute partition indices and store them in state.partition_indices ComputePartitionIndices(state, input); @@ -145,56 +138,17 @@ void PartitionedColumnData::AppendInternal(PartitionedColumnDataAppendState &sta using GETTER = TemplatedMapGetter; const auto &partition_entries = state.GetMap(); - // Loop through the partitions to append the new data to the partition buffers, and flush the buffers if necessary - SelectionVector partition_sel; + // Each partition receives its stretch of the partition selection, all in one append. BuildPartitionSel left each + // entry's offset at the end of its stretch. + auto &targets = state.partition_targets; + targets.clear(); for (auto it = partition_entries.begin(); it != partition_entries.end(); ++it) { - const auto &partition_index = GETTER::GetKey(it); - - // Partition, buffer, and append state for this partition index - auto &partition = *partitions[partition_index]; - auto &partition_buffer = *state.partition_buffers[partition_index]; - auto &partition_append_state = *state.partition_append_states[partition_index]; - - // Length and offset into the selection vector for this chunk, for this partition - const auto &partition_entry = GETTER::GetValue(it); - const auto &partition_length = partition_entry.length; - const auto partition_offset = partition_entry.offset - partition_length; - - // Create a selection vector for this partition using the offset into the single selection vector - partition_sel.Initialize(state.partition_sel.data() + partition_offset, - state.partition_sel.Capacity() - partition_offset); - - if (partition_length >= HalfBufferSize()) { - // Slice the input chunk using the selection vector - state.slice_chunk.Reset(); - state.slice_chunk.Slice(input, partition_sel, partition_length); - - // Append it to the partition directly - partition.Append(partition_append_state, state.slice_chunk); - } else { - // Append the input chunk to the partition buffer using the selection vector - partition_buffer.Append(input, partition_sel, partition_length); - - if (partition_buffer.size() >= HalfBufferSize()) { - // Next batch won't fit in the buffer, flush it to the partition - partition.Append(partition_append_state, partition_buffer); - partition_buffer.Reset(); - } - } - } -} - -void PartitionedColumnData::FlushAppendState(PartitionedColumnDataAppendState &state) { - for (idx_t i = 0; i < state.partition_buffers.size(); i++) { - if (!state.partition_buffers[i]) { - continue; - } - auto &partition_buffer = *state.partition_buffers[i]; - if (partition_buffer.size() > 0) { - partitions[i]->Append(partition_buffer); - partition_buffer.Reset(); - } + const auto partition_index = GETTER::GetKey(it); + const auto &entry = GETTER::GetValue(it); + targets.push_back({*partitions[partition_index], *state.partition_append_states[partition_index], + entry.offset - entry.length, entry.offset}); } + ColumnDataCollection::AppendBatch(input, state.partition_sel, input.size(), targets); } void PartitionedColumnData::Combine(PartitionedColumnData &other) { diff --git a/src/duckdb/src/common/types/variant/variant_writer.cpp b/src/duckdb/src/common/types/variant/variant_writer.cpp index f2922fba7..255bbf576 100644 --- a/src/duckdb/src/common/types/variant/variant_writer.cpp +++ b/src/duckdb/src/common/types/variant/variant_writer.cpp @@ -2,137 +2,175 @@ namespace duckdb { -namespace { - -//! Copies the list entries of the rows to 'target', moved to start at 'offset' -void CopyListEntries(list_entry_t *target, const vector &entries, idx_t offset) { - const auto count = entries.size(); - const auto source = entries.data(); - if (offset == 0) { - memcpy(target, source, count * sizeof(list_entry_t)); - return; - } - for (idx_t i = 0; i < count; i++) { - target[i] = list_entry_t(source[i].offset + offset, source[i].length); - } +VariantWriterState::VariantWriterState(ArenaAllocator &keys_arena) + : AuxiliaryDataHolder(AuxiliaryDataType::VARIANT_WRITER_STATE), builder(dictionary, keys_arena) { + builder.dictionary_keys = &dictionary_keys; } -} // namespace +idx_t VariantWriterState::GetAllocationSize() const { + const auto ids = + builder.child_key_ids.capacity() + builder.child_value_ids.capacity() + builder.key_slots.capacity(); + return builder.type_ids.capacity() * sizeof(uint8_t) + (builder.byte_offsets.capacity() + ids) * sizeof(uint32_t) + + builder.blob.capacity() + dictionary_keys.capacity() * sizeof(string_t); +} VectorWriter::VectorWriter(Vector &vector, idx_t count, idx_t offset) - : variant(vector), start_idx(offset), count(offset + count), current_idx(offset) { + : variant(vector), count(offset + count), current_idx(offset) { } VectorWriter::VectorWriter(VectorWriter &&other) noexcept - : variant(other.variant), state(std::move(other.state)), start_idx(other.start_idx), count(other.count), - current_idx(other.current_idx) { + : variant(other.variant), state(other.state), count(other.count), current_idx(other.current_idx), + keys_data(other.keys_data), children_data(other.children_data), values_data(other.values_data), + blob_data(other.blob_data), blob_heap(other.blob_heap), type_ids_data(other.type_ids_data), + byte_offset_data(other.byte_offset_data), values_size(other.values_size), values_capacity(other.values_capacity), + keys_index_data(other.keys_index_data), values_index_data(other.values_index_data), + keys_index_validity(other.keys_index_validity), children_size(other.children_size), + children_capacity(other.children_capacity), keys_entry_data(other.keys_entry_data), keys_size(other.keys_size), + keys_capacity(other.keys_capacity) { + other.state = nullptr; other.count = other.current_idx; } -VectorWriter::~VectorWriter() { // NOLINT(bugprone-exception-escape): only the allocations can throw +VectorWriter::~VectorWriter() { // NOLINT(bugprone-exception-escape): the lists were reserved already D_ASSERT(Exception::UncaughtException() || current_idx == count); - if (state && !Exception::UncaughtException()) { - Finalize(); + if (!state) { + return; } + ListVector::SetListSize(VariantVector::GetKeys(variant), keys_size); + ListVector::SetListSize(VariantVector::GetChildren(variant), children_size); + ListVector::SetListSize(VariantVector::GetValues(variant), values_size); } -void VectorWriter::InitializeState() { - state = make_uniq(); - const auto row_count = count - current_idx; - state->keys.reserve(row_count); - state->children.reserve(row_count); - state->values.reserve(row_count); - state->blobs.reserve(row_count); -} +void VectorWriter::Initialize() { + auto &keys = VariantVector::GetKeys(variant); + auto &keys_entry = ListVector::GetChildMutable(keys); + //! BuildVariant leaves the keys as a dictionary, the new keys are written flat after the existing ones + if (keys_entry.GetVectorType() != VectorType::FLAT_VECTOR) { + keys_entry.Flatten(); + } + //! the state lives as long as the heap its dictionary keys are allocated in + auto &keys_buffer = StringVector::GetStringBuffer(keys_entry); + auto &keys_arena = keys_buffer.GetStringAllocator(); + auto &auxiliary_data = keys_buffer.GetAuxiliaryData(); + if (auxiliary_data) { + for (auto &entry : auxiliary_data->data) { + if (entry->type == AuxiliaryDataType::VARIANT_WRITER_STATE) { + state = &static_cast(*entry); + break; + } + } + } + if (!state) { + auto new_state = make_uniq(keys_arena); + state = new_state.get(); + keys_buffer.AddAuxiliaryData(std::move(new_state)); + } -StringHeap &VectorWriter::InitializeBlobHeap() { - state->blob_heap = StringVector::GetStringHeap(VariantVector::GetData(variant)); - return *state->blob_heap; + keys_size = ListVector::GetListSize(keys); + children_size = ListVector::GetListSize(VariantVector::GetChildren(variant)); + values_size = ListVector::GetListSize(VariantVector::GetValues(variant)); + RefreshRows(); + RefreshChildren(); + //! every row has at least one value + ListVector::Reserve(VariantVector::GetValues(variant), values_size + count - current_idx); + RefreshValues(); } -void VectorWriter::ThrowRowTooLarge() { - throw InvalidInputException( - "Cannot convert value to VARIANT: encoded row size exceeds the maximum supported %u bytes", - NumericLimits::Maximum()); +void VectorWriter::RefreshRows() { + if (!state) { + return; + } + keys_data = FlatVector::GetDataMutable(VariantVector::GetKeys(variant)); + children_data = FlatVector::GetDataMutable(VariantVector::GetChildren(variant)); + values_data = FlatVector::GetDataMutable(VariantVector::GetValues(variant)); + blob_data = FlatVector::GetDataMutable(VariantVector::GetData(variant)); } -void VectorWriter::EmitContainer(const VariantNode &node, VariantBuilder &builder) { - EmitIterator(node, builder); +void VectorWriter::RefreshValues() { + values_capacity = ListVector::GetListCapacity(VariantVector::GetValues(variant)); + type_ids_data = FlatVector::GetDataMutable(VariantVector::GetValuesTypeId(variant)); + byte_offset_data = FlatVector::GetDataMutable(VariantVector::GetValuesByteOffset(variant)); } -void VectorWriter::Finalize() { - auto &writer_state = *state; - auto &builder = writer_state.builder; - const auto row_count = writer_state.blobs.size(); - D_ASSERT(row_count == current_idx - start_idx); - if (row_count == 0) { - return; - } +void VectorWriter::RefreshChildren() { + children_capacity = ListVector::GetListCapacity(VariantVector::GetChildren(variant)); + auto &keys_index = VariantVector::GetChildrenKeysIndex(variant); + keys_index_data = FlatVector::GetDataMutable(keys_index); + keys_index_validity = &FlatVector::ValidityMutable(keys_index); + values_index_data = FlatVector::GetDataMutable(VariantVector::GetChildrenValuesIndex(variant)); auto &keys = VariantVector::GetKeys(variant); - auto &keys_entry = ListVector::GetChildMutable(keys); - auto &children = VariantVector::GetChildren(variant); - auto &values = VariantVector::GetValues(variant); + keys_capacity = ListVector::GetListCapacity(keys); + keys_entry_data = FlatVector::GetDataMutable(ListVector::GetChildMutable(keys)); +} - const auto keys_offset = ListVector::GetListSize(keys); - const auto children_offset = ListVector::GetListSize(children); - const auto values_offset = ListVector::GetListSize(values); - const auto total_keys = builder.key_slots.size(); - const auto total_children = builder.child_value_ids.size(); - const auto total_values = builder.type_ids.size(); +void VectorWriter::ReserveValues(idx_t required) { + ListVector::Reserve(VariantVector::GetValues(variant), required); + RefreshValues(); +} - //! BuildVariant leaves the keys as a dictionary, the new keys are written flat after the existing ones - if (keys_entry.GetVectorType() != VectorType::FLAT_VECTOR) { - keys_entry.Flatten(); +//! Grows the keys first, the lists with the largest entries are copied while the other lists are still small +void VectorWriter::ReserveChildren(idx_t child_count, idx_t key_count) { + if (keys_size + key_count > keys_capacity) { + ListVector::Reserve(VariantVector::GetKeys(variant), keys_size + key_count); } - ListVector::Reserve(keys, keys_offset + total_keys); - ListVector::SetListSize(keys, keys_offset + total_keys); - ListVector::Reserve(children, children_offset + total_children); - ListVector::SetListSize(children, children_offset + total_children); - ListVector::Reserve(values, values_offset + total_values); - ListVector::SetListSize(values, values_offset + total_values); - - //! rows - VariantVectorData variant_data(variant); - CopyListEntries(variant_data.keys_data + start_idx, writer_state.keys, keys_offset); - CopyListEntries(variant_data.children_data + start_idx, writer_state.children, children_offset); - CopyListEntries(variant_data.values_data + start_idx, writer_state.values, values_offset); - memcpy(variant_data.blob_data + start_idx, writer_state.blobs.data(), row_count * sizeof(string_t)); - for (auto row : writer_state.null_rows) { - FlatVector::SetNull(variant, start_idx + row, true); + if (children_size + child_count > children_capacity) { + ListVector::Reserve(VariantVector::GetChildren(variant), children_size + child_count); } + RefreshChildren(); +} - //! values - if (total_values) { - memcpy(variant_data.type_ids_data + values_offset, builder.type_ids.data(), total_values * sizeof(uint8_t)); - memcpy(variant_data.byte_offset_data + values_offset, builder.byte_offsets.data(), - total_values * sizeof(uint32_t)); - } +void VectorWriter::WriteChildren() { + auto &builder = state->builder; + const auto child_count = builder.child_value_ids.size(); + const auto key_count = builder.key_slots.size(); + children_data[current_idx] = list_entry_t(children_size, child_count); + keys_data[current_idx] = list_entry_t(keys_size, key_count); - //! children const auto child_value_ids = builder.child_value_ids.data(); const auto child_key_ids = builder.child_key_ids.data(); - for (idx_t i = 0; i < total_children; i++) { - const auto child_idx = children_offset + i; - variant_data.values_index_data[child_idx] = child_value_ids[i]; + for (idx_t i = 0; i < child_count; i++) { + const auto child_idx = children_size + i; + values_index_data[child_idx] = child_value_ids[i]; if (child_key_ids[i] == VARIANT_INVALID_KEY) { - variant_data.keys_index_validity.SetInvalid(child_idx); + keys_index_validity->SetInvalid(child_idx); } else { - variant_data.keys_index_data[child_idx] = child_key_ids[i]; + keys_index_data[child_idx] = child_key_ids[i]; } } + children_size += child_count; - //! keys: copy each distinct key into the keys vector once, then point every key slot at its copy - vector dictionary_keys(writer_state.dictionary.size()); - const auto dictionary_data = dictionary_keys.data(); - for (auto &entry : writer_state.dictionary) { - dictionary_data[entry.second] = StringVector::AddStringOrBlob(keys_entry, entry.first); - } + //! every distinct key is copied into the heap of the keys vector once, when it is added to the dictionary const auto key_slots = builder.key_slots.data(); - auto keys_entry_data = FlatVector::GetDataMutable(keys_entry); - for (idx_t i = 0; i < total_keys; i++) { - keys_entry_data[keys_offset + i] = dictionary_data[key_slots[i]]; + const auto dictionary_keys = state->dictionary_keys.data(); + for (idx_t i = 0; i < key_count; i++) { + keys_entry_data[keys_size + i] = dictionary_keys[key_slots[i]]; } + keys_size += key_count; +} + +void VectorWriter::WriteNullRow() { + keys_data[current_idx] = list_entry_t(keys_size, 0); + children_data[current_idx] = list_entry_t(children_size, 0); + values_data[current_idx] = list_entry_t(values_size, 0); + blob_data[current_idx] = string_t(0U); + FlatVector::SetNull(variant, current_idx, true); + current_idx++; +} + +StringHeap &VectorWriter::InitializeBlobHeap() { + blob_heap = StringVector::GetStringHeap(VariantVector::GetData(variant)); + return *blob_heap; +} + +void VectorWriter::ThrowRowTooLarge() { + throw InvalidInputException( + "Cannot convert value to VARIANT: encoded row size exceeds the maximum supported %u bytes", + NumericLimits::Maximum()); +} + +void VectorWriter::EmitContainer(const VariantNode &node, VariantBuilder &builder) { + EmitIterator(node, builder); } } // namespace duckdb diff --git a/src/duckdb/src/execution/join_hashtable.cpp b/src/duckdb/src/execution/join_hashtable.cpp index f4b8e5c54..04951a029 100644 --- a/src/duckdb/src/execution/join_hashtable.cpp +++ b/src/duckdb/src/execution/join_hashtable.cpp @@ -3282,10 +3282,6 @@ void ProbeSpill::Append(DataChunk &chunk, ProbeSpillLocalAppendState &local_stat } void ProbeSpill::Finalize() { - D_ASSERT(local_partitions.size() == local_partition_append_states.size()); - for (idx_t i = 0; i < local_partition_append_states.size(); i++) { - local_partitions[i]->FlushAppendState(*local_partition_append_states[i]); - } for (auto &local_partition : local_partitions) { global_partitions->Combine(*local_partition); } diff --git a/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp b/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp index eb1e3a682..abdc50a3b 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp @@ -196,8 +196,10 @@ bool PhysicalStreamingWindow::IsStreamingFunction(ClientContext &client, BoundWi return false; } if (wexpr.GetExpressionType() == ExpressionType::WINDOW_AGGREGATE) { - // Aggregates with destructors (e.g., quantile) are too slow to repeatedly update/finalize - if (wexpr.AggregateFunction()->HasStateDestructorCallback() || !wexpr.AggregateFunction()->CanStream()) { + // Aggregates with destructors, and holistic ones (which copy all their input), are too slow to finalize per row + // Some aggregates cannot stream at all (e.g., top-N with a per-row n) + if (wexpr.AggregateFunction()->HasStateDestructorCallback() || wexpr.AggregateFunction()->IsHolistic() || + !wexpr.AggregateFunction()->CanStream()) { return false; } // We can stream aggregates if they are "running totals" diff --git a/src/duckdb/src/execution/operator/persistent/physical_update.cpp b/src/duckdb/src/execution/operator/persistent/physical_update.cpp index 56218dec1..bca524334 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_update.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_update.cpp @@ -350,19 +350,6 @@ static bool RowIdsAreSorted(Vector &row_ids, idx_t count) { return true; } -//! Keeps one entry per row id of a chunk sorted by row id. Updating a row id more than once in a single chunk would -//! let every column pick its value from a different entry; across chunks, every entry still overwrites the whole row. -static idx_t SelectLastPerRowId(Vector &row_ids, idx_t count, SelectionVector &sel) { - auto ids = row_ids.Values(); - idx_t kept = 0; - for (idx_t i = 0; i < count; i++) { - if (i + 1 == count || ids[i + 1].GetValueUnsafe() != ids[i].GetValueUnsafe()) { - sel.set_index(kept++, i); - } - } - return kept; -} - void PhysicalUpdate::StageUpdates(ExecutionContext &context, GlobalSinkState &gstate, LocalSinkState &lstate, DataChunk &updates, Vector &row_ids, InterruptState &interrupt_state) const { auto &g_state = gstate.Cast(); @@ -423,7 +410,6 @@ void PhysicalUpdate::FlushStagedUpdates(ExecutionContext &context, GlobalSinkSta sorted_updates.InitializeEmpty(update_types); } auto &update_state = l_state.GetUpdateState(table, tableref, context.client); - SelectionVector unique_sel(STANDARD_VECTOR_SIZE); while (true) { context.client.InterruptCheck(); sorted_chunk.Reset(); @@ -432,10 +418,6 @@ void PhysicalUpdate::FlushStagedUpdates(ExecutionContext &context, GlobalSinkSta throw InternalException("Sorting the staged updates of an UPDATE unexpectedly blocked"); } if (sorted_chunk.size() > 0) { - auto unique_count = SelectLastPerRowId(sorted_chunk.data.back(), sorted_chunk.size(), unique_sel); - if (unique_count < sorted_chunk.size()) { - sorted_chunk.Slice(unique_sel, unique_count); - } for (idx_t c = 0; c < sorted_updates.ColumnCount(); c++) { sorted_updates.data[c].Reference(sorted_chunk.data[c]); } diff --git a/src/duckdb/src/function/aggregate_function.cpp b/src/duckdb/src/function/aggregate_function.cpp index d1ccdca11..b48b183da 100644 --- a/src/duckdb/src/function/aggregate_function.cpp +++ b/src/duckdb/src/function/aggregate_function.cpp @@ -88,8 +88,8 @@ void AggregateFinalizeInputData::InitializeLocalState() { bool AggregateFunctionProperties::operator==(const AggregateFunctionProperties &rhs) const { return FunctionProperties::operator==(rhs) && order_dependent == rhs.order_dependent && distinct_dependent == rhs.distinct_dependent && single_value_identity == rhs.single_value_identity && - is_holistic == rhs.is_holistic && combine_source_retention == rhs.combine_source_retention && - can_stream == rhs.can_stream; + is_holistic == rhs.is_holistic && allow_window_trees == rhs.allow_window_trees && + combine_source_retention == rhs.combine_source_retention && can_stream == rhs.can_stream; } bool AggregateFunctionProperties::operator!=(const AggregateFunctionProperties &rhs) const { return !(*this == rhs); @@ -105,7 +105,7 @@ bool AggregateFunctionCallbacks::operator==(const AggregateFunctionCallbacks &rh rewrite == rhs.rewrite && rewrite_policy == rhs.rewrite_policy && rewrite_optimizer_type == rhs.rewrite_optimizer_type && rewrite_cost == rhs.rewrite_cost && get_state_type == rhs.get_state_type && export_aggregate_state == rhs.export_aggregate_state && - import_aggregate_state == rhs.import_aggregate_state; + import_aggregate_state == rhs.import_aggregate_state && init_window_state == rhs.init_window_state; } bool AggregateFunctionCallbacks::operator!=(const AggregateFunctionCallbacks &rhs) const { diff --git a/src/duckdb/src/function/scalar/system/aggregate_export.cpp b/src/duckdb/src/function/scalar/system/aggregate_export.cpp index 438d04474..f18bf6e72 100644 --- a/src/duckdb/src/function/scalar/system/aggregate_export.cpp +++ b/src/duckdb/src/function/scalar/system/aggregate_export.cpp @@ -511,6 +511,9 @@ unique_ptr CombineAggrBind(BindAggregateFunctionInput &input) { if (bind_data->aggr.HasStateDestructorCallback()) { function.SetStateDestructorCallback(CombineAggrStateDestroy); } + // a holistic state stays holistic, but combine_aggr has no custom window and keeps the window trees + function.SetIsHolistic(bind_data->aggr.IsHolistic()); + function.SetAllowsWindowTrees(true); function.SetReturnType(arguments[0]->GetReturnType()); diff --git a/src/duckdb/src/function/scalar/variant/variant_bind_utils.cpp b/src/duckdb/src/function/scalar/variant/variant_bind_utils.cpp index 8e1394d83..c22b8e88d 100644 --- a/src/duckdb/src/function/scalar/variant/variant_bind_utils.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_bind_utils.cpp @@ -1,9 +1,33 @@ #include "duckdb/function/scalar/variant_utils.hpp" #include "duckdb/execution/expression_executor.hpp" +#include "duckdb/common/string_map_set.hpp" namespace duckdb { +VariantPathKeyIndex::VariantPathKeyIndex(const vector> &keys) { + string_map_t> positions_by_key; + for (idx_t path_idx = 0; path_idx < keys.size(); path_idx++) { + const auto &key = keys[path_idx]; + if (key) { + positions_by_key[*key].push_back(path_idx); + } + } + //! at most half of the slots are used, so a lookup ends at an unused slot + const auto slot_count = NextPowerOfTwo(positions_by_key.size() * 2); + mask = slot_count - 1; + slots.resize(slot_count, Slot {string_t(), list_entry_t(0, 0)}); + for (auto &entry : positions_by_key) { + auto slot_idx = Hash(entry.first) & mask; + while (slots[slot_idx].positions.length != 0) { + slot_idx = (slot_idx + 1) & mask; + } + slots[slot_idx] = Slot {entry.first, list_entry_t(positions.size(), entry.second.size())}; + positions.insert(positions.end(), entry.second.begin(), entry.second.end()); + } +} + VariantPathBindData::VariantPathBindData() : FunctionData() { + IndexPaths(); } VariantPathBindData::VariantPathBindData(const string &input_path) : FunctionData() { if (input_path.empty()) { @@ -11,6 +35,7 @@ VariantPathBindData::VariantPathBindData(const string &input_path) : FunctionDat } else { paths.push_back({VariantPathComponent(input_path)}); } + IndexPaths(); } VariantPathBindData::VariantPathBindData(const vector &input_paths) : FunctionData() { for (const auto &path : input_paths) { @@ -20,9 +45,30 @@ VariantPathBindData::VariantPathBindData(const vector &input_paths) : Fu paths.push_back({VariantPathComponent(path)}); } } + IndexPaths(); } VariantPathBindData::VariantPathBindData(int64_t index) : FunctionData() { paths.push_back({VariantPathComponent(index)}); + IndexPaths(); +} +VariantPathBindData::VariantPathBindData(const VariantPathBindData &other) : FunctionData(other), paths(other.paths) { + //! the keys point into the paths, so they are taken from the copied paths + IndexPaths(); +} + +void VariantPathBindData::IndexPaths() { + single_keys.resize(paths.size()); + idx_t single_key_count = 0; + for (idx_t path_idx = 0; path_idx < paths.size(); path_idx++) { + const auto &path = paths[path_idx]; + if (path.size() == 1 && path[0].lookup_mode == VariantChildLookupMode::BY_KEY) { + single_keys[path_idx] = string_t(path[0].key.c_str(), NumericCast(path[0].key.size())); + single_key_count++; + } + } + if (single_key_count >= KEY_INDEX_THRESHOLD) { + key_index = make_uniq(single_keys); + } } unique_ptr VariantPathBindData::Copy() const { 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 b513fdb3a..b39d788cd 100644 --- a/src/duckdb/src/function/scalar/variant/variant_path_function.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_path_function.cpp @@ -1,5 +1,4 @@ #include "duckdb/function/scalar/variant_path_function.hpp" -#include "duckdb/common/numeric_utils.hpp" namespace duckdb { @@ -23,23 +22,12 @@ optional VariantPathFunction::ResolveIndex(const VariantNode &node, return elements[length - 1 - from_end]; } -vector> VariantPathFunction::GetSingleKeys(const vector> &paths) { - vector> keys(paths.size()); - for (idx_t path_idx = 0; path_idx < paths.size(); path_idx++) { - const auto &path = paths[path_idx]; - if (path.size() == 1 && path[0].lookup_mode == VariantChildLookupMode::BY_KEY) { - keys[path_idx] = string_t(path[0].key.c_str(), NumericCast(path[0].key.size())); - } - } - return keys; -} - -void VariantPathFunction::ResolvePaths(const VariantNode &root, const vector> &paths, - const vector> &keys, +void VariantPathFunction::ResolvePaths(const VariantNode &root, const VariantPathBindData &info, vector> &selected) { //! Copied into locals so the matching loop keeps them in registers + const auto &paths = info.paths; const auto path_count = paths.size(); - const auto key_data = keys.data(); + const auto key_data = info.single_keys.data(); const auto selected_data = selected.data(); idx_t pending = 0; @@ -54,6 +42,25 @@ void VariantPathFunction::ResolvePaths(const VariantNode &root, const vector(window_state.get()) : state.data(); + } + public: //! The aggregate function const AggregateObject aggr; //! Data pointer that contains a single state, shared by all the custom evaluators vector state; + //! The state of the custom window callbacks, if the aggregate creates its own + unique_ptr window_state; //! Reused result state container for the window functions Vector statef; //! The frame boundaries, used for the window functions @@ -81,14 +87,19 @@ WindowCustomAggregatorLocalState::WindowCustomAggregatorLocalState(ExecutionCont statef(Value::POINTER(CastPointerToValue(state.data())), count_t(1)), frames(3, {0, 0}) { // if we have a frame-by-frame method, share the single state AggregateStateInput state_input(aggr.function, aggr.GetFunctionData()); - data_ptr_t state_ptr = state.data(); - aggr.function.GetStateInitCallback()(state_input, &state_ptr, 1); + if (aggr.function.HasInitWindowStateCallback()) { + window_state = aggr.function.GetInitWindowStateCallback()(state_input); + D_ASSERT(window_state); + } else { + data_ptr_t state_ptr = state.data(); + aggr.function.GetStateInitCallback()(state_input, &state_ptr, 1); + } InitSubFrames(frames, exclude_mode); } WindowCustomAggregatorLocalState::~WindowCustomAggregatorLocalState() { - if (aggr.function.HasStateDestructorCallback()) { + if (!window_state && aggr.function.HasStateDestructorCallback()) { AggregateInputData aggr_input_data(aggr, allocator); aggr.function.GetStateDestructorCallback()(statef, aggr_input_data, 1); } @@ -128,7 +139,7 @@ void WindowCustomAggregator::Finalize(ExecutionContext &context, CollectionPtr c sink.interrupt_state); AggregateInputData aggr_input_data(aggr, gcstate.allocator); - aggr.function.GetWindowInitCallback()(aggr_input_data, partition, gcstate.state.data()); + aggr.function.GetWindowInitCallback()(aggr_input_data, partition, gcstate.GetState()); } ++gcsink.finalized; @@ -147,7 +158,7 @@ void WindowCustomAggregator::Evaluate(ExecutionContext &context, const DataChunk auto &gcsink = sink.global_state.Cast(); if (gcsink.glstate) { auto &gcstate = gcsink.glstate->Cast(); - gstate_p = gcstate.state.data(); + gstate_p = gcstate.GetState(); } auto collection = gcsink.collection; @@ -168,7 +179,7 @@ void WindowCustomAggregator::Evaluate(ExecutionContext &context, const DataChunk all_frames.reserve(count); EvaluateSubFrames(bounds, exclude_mode, count, row_idx, frames, [&](idx_t i) { all_frames.push_back(frames); }); AggregateInputData aggr_input_data(aggr, lcstate.allocator); - aggr.function.GetWindowBatchCallback()(aggr_input_data, partition, gstate_p, lcstate.state.data(), + aggr.function.GetWindowBatchCallback()(aggr_input_data, partition, gstate_p, lcstate.GetState(), all_frames.data(), count, result, row_idx); return; } @@ -176,8 +187,7 @@ void WindowCustomAggregator::Evaluate(ExecutionContext &context, const DataChunk EvaluateSubFrames(bounds, exclude_mode, count, row_idx, frames, [&](idx_t i) { // Extract the range AggregateInputData aggr_input_data(aggr, lcstate.allocator); - aggr.function.GetWindowCallback()(aggr_input_data, partition, gstate_p, lcstate.state.data(), frames, result, - i); + aggr.function.GetWindowCallback()(aggr_input_data, partition, gstate_p, lcstate.GetState(), frames, result, i); }); } diff --git a/src/duckdb/src/function/window/window_distinct_aggregator.cpp b/src/duckdb/src/function/window/window_distinct_aggregator.cpp index c33f39197..bc8999176 100644 --- a/src/duckdb/src/function/window/window_distinct_aggregator.cpp +++ b/src/duckdb/src/function/window/window_distinct_aggregator.cpp @@ -24,7 +24,7 @@ bool WindowDistinctAggregator::CanAggregate(const BoundWindowExpression &wexpr) } auto &aggr = *wexpr.AggregateFunction(); - if (!aggr.CanAggregate() || aggr.CanWindow() || aggr.IsHolistic()) { + if (!aggr.CanAggregate() || aggr.CanWindow() || (aggr.IsHolistic() && !aggr.AllowsWindowTrees())) { return false; } diff --git a/src/duckdb/src/function/window/window_naive_aggregator.cpp b/src/duckdb/src/function/window/window_naive_aggregator.cpp index c2749ca1f..bc1096883 100644 --- a/src/duckdb/src/function/window/window_naive_aggregator.cpp +++ b/src/duckdb/src/function/window/window_naive_aggregator.cpp @@ -406,6 +406,9 @@ void WindowNaiveLocalState::Evaluate(ExecutionContext &context, const WindowAggr if (aggr.function.HasStateDestructorCallback()) { aggr.function.GetStateDestructorCallback()(statef, aggr_input_data, count); allocator.FreeAll(); + } else if (aggr.function.IsHolistic()) { + // holistic finalizers copy their results out of the arena + allocator.FreeAll(); } live_count = 0; } diff --git a/src/duckdb/src/function/window/window_segment_tree.cpp b/src/duckdb/src/function/window/window_segment_tree.cpp index 869dc2b92..c147cde9e 100644 --- a/src/duckdb/src/function/window/window_segment_tree.cpp +++ b/src/duckdb/src/function/window/window_segment_tree.cpp @@ -21,8 +21,8 @@ bool WindowSegmentTree::CanAggregate(const BoundWindowExpression &wexpr) { return false; } - // Don't use segment trees for custom windowing or holistic aggregates - if (aggr.CanWindow() || aggr.IsHolistic()) { + // Don't use segment trees for custom windowing or holistic aggregates (every level would copy the input) + if (aggr.CanWindow() || (aggr.IsHolistic() && !aggr.AllowsWindowTrees())) { return false; } diff --git a/src/duckdb/src/include/duckdb/common/enum_util.hpp b/src/duckdb/src/include/duckdb/common/enum_util.hpp index 6baa6c64f..d4ee3922f 100644 --- a/src/duckdb/src/include/duckdb/common/enum_util.hpp +++ b/src/duckdb/src/include/duckdb/common/enum_util.hpp @@ -102,6 +102,8 @@ enum class AsyncResultType : uint8_t; enum class AsyncResultsExecutionMode : uint8_t; +enum class AuxiliaryDataType : uint8_t; + enum class BaseColumnPrunerMode : uint8_t; enum class BinderType : uint8_t; @@ -836,6 +838,9 @@ const char* EnumUtil::ToChars(AsyncResultType value); template<> const char* EnumUtil::ToChars(AsyncResultsExecutionMode value); +template<> +const char* EnumUtil::ToChars(AuxiliaryDataType value); + template<> const char* EnumUtil::ToChars(BaseColumnPrunerMode value); @@ -1884,6 +1889,9 @@ AsyncResultType EnumUtil::FromString(const char *value); template<> AsyncResultsExecutionMode EnumUtil::FromString(const char *value); +template<> +AuxiliaryDataType EnumUtil::FromString(const char *value); + template<> BaseColumnPrunerMode EnumUtil::FromString(const char *value); diff --git a/src/duckdb/src/include/duckdb/common/radix_partitioning.hpp b/src/duckdb/src/include/duckdb/common/radix_partitioning.hpp index d8fcdc0a7..4d88d3d5e 100644 --- a/src/duckdb/src/include/duckdb/common/radix_partitioning.hpp +++ b/src/duckdb/src/include/duckdb/common/radix_partitioning.hpp @@ -79,32 +79,12 @@ class RadixPartitionedColumnData : public PartitionedColumnData { //===--------------------------------------------------------------------===// // Radix Partitioning interface implementation //===--------------------------------------------------------------------===// - idx_t BufferSize() const override { - switch (radix_bits) { - case 1: - case 2: - case 3: - case 4: - return GetBufferSize(1 << 1); - case 5: - return GetBufferSize(1 << 2); - case 6: - return GetBufferSize(1 << 3); - default: - return GetBufferSize(1 << 4); - } - } - void InitializeAppendStateInternal(PartitionedColumnDataAppendState &state) const override; void ComputePartitionIndices(PartitionedColumnDataAppendState &state, DataChunk &input) override; idx_t MaxPartitionIndex() const override { return RadixPartitioning::NumberOfPartitions(radix_bits) - 1; } - static constexpr idx_t GetBufferSize(idx_t div) { - return STANDARD_VECTOR_SIZE / div == 0 ? 1 : STANDARD_VECTOR_SIZE / div; - } - private: //! The number of radix bits const idx_t radix_bits; diff --git a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp index d60f21040..17c223cfa 100644 --- a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp +++ b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp @@ -21,6 +21,8 @@ class ColumnDataAllocator; class ColumnDataCollection; class ColumnDataCollectionSegment; class ColumnDataRowCollection; +struct ColumnDataSelectionTarget; +struct ColumnDataChildSelections; //! The ColumnDataCollection represents a set of (buffer-managed) data stored in columnar format //! It is efficient to read and scan @@ -94,6 +96,14 @@ class ColumnDataCollection { DUCKDB_API void InitializeAppend(ColumnDataAppendState &state); //! Append a DataChunk to this ColumnDataCollection using the specified append state DUCKDB_API void Append(ColumnDataAppendState &state, DataChunk &new_chunk); + //! Append the `count` rows of `input` that `sel` lists, in that order. Reads the collection's leading columns of + //! `input`, which may have more. + DUCKDB_API void Append(ColumnDataAppendState &state, DataChunk &input, const SelectionVector &sel, idx_t count); + //! Append the rows of `input` that `sel` lists to several collections of the same types, each target the rows at + //! its positions of `sel`. Prepares `input` once for all targets. Reads the collections' leading columns of + //! `input`, which may have more. + DUCKDB_API static void AppendBatch(DataChunk &input, const SelectionVector &sel, idx_t sel_count, + const vector &targets); //! Initializes a chunk with the correct types that can be used to call Scan DUCKDB_API void InitializeScanChunk(DataChunk &chunk) const; @@ -208,6 +218,13 @@ class ColumnDataCollection { void CreateSegment(); static ColumnDataCopyFunction GetCopyFunction(const LogicalType &type); + //! Builds the formats of the first `column_count` columns of `input`, reading their rows through `sel` + static void PrepareSelectedFormats(DataChunk &input, idx_t column_count, const SelectionVector &sel, + idx_t sel_count, vector &formats); + //! Appends `count` rows of `input` through `formats`, from position `offset`. With `keep_compact`, a constant or + //! dictionary input may stay compact, as Append(state, chunk) keeps it. + void AppendRows(ColumnDataAppendState &state, const vector &formats, DataChunk &input, + idx_t offset, idx_t count, bool keep_compact, ColumnDataChildSelections &child_selections); private: //! The Column Data Allocator @@ -226,6 +243,15 @@ class ColumnDataCollection { optional_idx partition_index; }; +//! One collection's share of ColumnDataCollection::AppendBatch +struct ColumnDataSelectionTarget { + ColumnDataCollection &collection; + ColumnDataAppendState &state; + //! The positions [begin, end) of the selection that this collection receives + idx_t begin; + idx_t end; +}; + //! Walks the chunks of a ColumnDataCollection in storage order: exposes the position, the row count and the //! allocation size of every chunk, e.g. to plan scans over the collection class ColumnDataChunkCursor { diff --git a/src/duckdb/src/include/duckdb/common/types/column/partitioned_column_data.hpp b/src/duckdb/src/include/duckdb/common/types/column/partitioned_column_data.hpp index a16ee6370..8a4bd37df 100644 --- a/src/duckdb/src/include/duckdb/common/types/column/partitioned_column_data.hpp +++ b/src/duckdb/src/include/duckdb/common/types/column/partitioned_column_data.hpp @@ -30,10 +30,9 @@ struct PartitionedColumnDataAppendState { perfect_map_t partition_entries; fixed_size_map_t fixed_partition_entries; - DataChunk slice_chunk; - - vector> partition_buffers; vector> partition_append_states; + //! The partitions an append writes to, reused by the next append + vector partition_targets; public: template @@ -92,8 +91,6 @@ class PartitionedColumnData { void InitializeAppendState(PartitionedColumnDataAppendState &state) const; //! Appends a DataChunk to this PartitionedColumnData void Append(PartitionedColumnDataAppendState &state, DataChunk &input); - //! Flushes any remaining data in the append state into this PartitionedColumnData - void FlushAppendState(PartitionedColumnDataAppendState &state); //! Combine another PartitionedColumnData into this PartitionedColumnData void Combine(PartitionedColumnData &other); //! Get the partitions in this PartitionedColumnData @@ -103,10 +100,6 @@ class PartitionedColumnData { //===--------------------------------------------------------------------===// // Partitioning type implementation interface //===--------------------------------------------------------------------===// - //! Size of the buffers in the append states for this type of partitioning (default 128) - virtual idx_t BufferSize() const { - return MinValue(128, STANDARD_VECTOR_SIZE); - } //! Initialize a PartitionedColumnDataAppendState for this type of partitioning (optional) virtual void InitializeAppendStateInternal(PartitionedColumnDataAppendState &state) const { } @@ -128,11 +121,6 @@ class PartitionedColumnData { PartitionedColumnData(PartitionedColumnDataType type, ClientContext &context, vector types); PartitionedColumnData(const PartitionedColumnData &other); - //! If the buffer is half full, we append to the partition - inline idx_t HalfBufferSize() const { - D_ASSERT(IsPowerOfTwo(BufferSize())); - return BufferSize() / 2; - } //! Create a new shared allocator void CreateAllocator(); //! Whether to use fixed size map or regular map @@ -149,8 +137,6 @@ class PartitionedColumnData { unique_ptr CreatePartitionCollection(idx_t partition_index) const { return make_uniq(allocators->allocators[partition_index], types); } - //! Create a DataChunk used for buffering appends to the partition - unique_ptr CreatePartitionBuffer() const; protected: PartitionedColumnDataType type; 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 7b17d9800..f43d4e326 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 @@ -73,13 +73,6 @@ inline void VariantBuilderAppendBytes(string &blob, const_data_ptr_t data, idx_t blob.append(const_char_ptr_cast(data), size); } -inline uint32_t VariantBuilderGetOrCreateIndex(OrderedOwningStringMap &dictionary, ArenaAllocator &keys_arena, - const string_t &key) { - auto unsorted_idx = dictionary.size(); - //! This will later be remapped to the sorted idx (see FinalizeVariantKeys in 'to_variant.cpp') - return dictionary.emplace(std::make_pair(key, unsorted_idx), keys_arena).first->second; -} - //! The physical storage type of a DECIMAL of the given width (matches VariantDecimalData::GetPhysicalType) inline PhysicalType VariantDecimalPhysicalType(uint32_t width) { if (width > DecimalWidth::max) { @@ -115,6 +108,8 @@ struct VariantBuilder { OrderedOwningStringMap &dictionary; //! the result's keys arena, the dictionary's keys are allocated in ArenaAllocator &keys_arena; + //! if set, receives the key of every new dictionary entry, at the index of the entry + optional_ptr> dictionary_keys; static constexpr idx_t INIT_NESTING_DEPTH = 8; @@ -123,6 +118,16 @@ struct VariantBuilder { idx_t row_children = 0; idx_t row_keys = 0; + //! Returns the (unsorted) dictionary index of 'key', adding it to the dictionary if it is new + uint32_t GetOrCreateKeyIndex(const string_t &key) { + //! This will later be remapped to the sorted idx (see FinalizeVariantKeys in 'to_variant.cpp') + auto entry = dictionary.emplace(std::make_pair(key, static_cast(dictionary.size())), keys_arena); + if (entry.second && dictionary_keys) { + dictionary_keys->push_back(entry.first->first); + } + return entry.first->second; + } + void BeginRow() { row_values = type_ids.size(); row_children = child_value_ids.size(); @@ -168,7 +173,7 @@ struct VariantBuilder { for (idx_t i = 0; i < n; i++) { child_value_ids[block + i] = LocalValue(); child_key_ids[block + i] = LocalKey(); - key_slots.push_back(VariantBuilderGetOrCreateIndex(dictionary, keys_arena, key_fn(i))); + key_slots.push_back(GetOrCreateKeyIndex(key_fn(i))); emit_fn(i); } } @@ -522,7 +527,7 @@ struct VariantBuilder { void AssignObjectChild(idx_t block, idx_t i, string_t key) { child_value_ids[block + i] = LocalValue(); child_key_ids[block + i] = LocalKey(); - key_slots.push_back(VariantBuilderGetOrCreateIndex(dictionary, keys_arena, key)); + key_slots.push_back(GetOrCreateKeyIndex(key)); } void AssignArrayChild(idx_t block, idx_t i) { diff --git a/src/duckdb/src/include/duckdb/common/types/variant_writer.hpp b/src/duckdb/src/include/duckdb/common/types/variant_writer.hpp index 2fad0fb66..71d6d85fb 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_writer.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_writer.hpp @@ -10,33 +10,28 @@ #include "duckdb/common/vector/vector_writer.hpp" #include "duckdb/common/types/variant/variant_builder.hpp" -#include "duckdb/common/unique_ptr.hpp" +#include "duckdb/common/vector/list_vector.hpp" namespace duckdb { -//! The rows collected by a VectorWriter -struct VariantWriterState { - VariantWriterState() : keys_arena(Allocator::DefaultAllocator()), builder(dictionary, keys_arena) { - } +//! The state shared by the VARIANT writers of a vector. It is kept with the string heap of the keys vector, so every +//! writer of the vector (e.g. one per list for LIST(STRUCT(VARIANT))) reuses its allocations and its dictionary. +struct VariantWriterState final : public AuxiliaryDataHolder { + explicit VariantWriterState(ArenaAllocator &keys_arena); + + idx_t GetAllocationSize() const override; - //! owns the keys of the dictionary, they are copied into the keys vector when the rows are written - ArenaAllocator keys_arena; + //! the keys written so far, allocated in the string heap of the keys vector OrderedOwningStringMap dictionary; + //! the key of every dictionary entry, at the index of the entry + vector dictionary_keys; + //! emits one row at a time, its arrays keep their capacity between rows VariantBuilder builder; - //! per row: its keys, children and values in the builder, and its encoded value (owned by the data vector) - vector keys; - vector children; - vector values; - vector blobs; - //! the rows written as SQL NULL, relative to the first row of the writer - vector null_rows; - //! the heap of the data vector, looked up when the first blob that is not inlined is written - optional_ptr blob_heap; }; //! Specialization of VectorWriter for VectorVariantType. -//! The rows are collected in a single VariantBuilder and written to the vector when the writer is destroyed. The -//! keys, children and values of the rows are appended to the ones already in the vector. +//! Every row is emitted into a VariantBuilder and then written to the vector. The keys, children and values of the +//! rows are appended to the ones already in the vector. template <> struct VectorWriter { DUCKDB_API VectorWriter(Vector &vector, idx_t count, idx_t offset); @@ -46,23 +41,16 @@ struct VectorWriter { //! Write a SQL NULL void WriteNull() { D_ASSERT(current_idx < count); - auto &writer_state = GetState(); - auto &builder = writer_state.builder; - writer_state.null_rows.push_back(current_idx - start_idx); - writer_state.keys.emplace_back(builder.key_slots.size(), 0); - writer_state.children.emplace_back(builder.child_value_ids.size(), 0); - writer_state.values.emplace_back(builder.type_ids.size(), 0); - writer_state.blobs.emplace_back(0U); - current_idx++; + if (!state) { + Initialize(); + } + WriteNullRow(); } //! Write a copy of the value 'node' points at. A NULL or missing node is written as a VARIANT null value. void WriteValue(const VariantNode &node) { if (node.IsNull() || node.IsMissing()) { - D_ASSERT(current_idx < count); - auto &builder = GetState().builder; - builder.BeginRow(); - builder.EmitNull(); + BeginRow().EmitNull(); FinishRow(); return; } @@ -89,17 +77,8 @@ struct VectorWriter { count += n; } - VariantWriterState &GetState() { - if (!state) { - InitializeState(); - } - return *state; - } - void WriteNode(const VariantNode &node, VariantLogicalType type_id) { - D_ASSERT(current_idx < count); - auto &builder = GetState().builder; - builder.BeginRow(); + auto &builder = BeginRow(); if (type_id == VariantLogicalType::OBJECT || type_id == VariantLogicalType::ARRAY) { EmitContainer(node, builder); } else { @@ -108,38 +87,105 @@ struct VectorWriter { FinishRow(); } - //! Records the row the builder just emitted + VariantBuilder &BeginRow() { + D_ASSERT(current_idx < count); + if (!state) { + Initialize(); + } + auto &builder = state->builder; + //! a row that threw while it was emitted leaves its entries behind + builder.type_ids.clear(); + builder.byte_offsets.clear(); + builder.child_key_ids.clear(); + builder.child_value_ids.clear(); + builder.key_slots.clear(); + builder.BeginRow(); + return builder; + } + + //! Writes the row the builder just emitted to the vector void FinishRow() { - auto &writer_state = *state; - auto &builder = writer_state.builder; + auto &builder = state->builder; const auto blob_size = builder.blob.size(); if (blob_size > NumericLimits::Maximum()) { ThrowRowTooLarge(); } - writer_state.keys.emplace_back(builder.row_keys, builder.key_slots.size() - builder.row_keys); - writer_state.children.emplace_back(builder.row_children, builder.child_value_ids.size() - builder.row_children); - writer_state.values.emplace_back(builder.row_values, builder.type_ids.size() - builder.row_values); + const auto value_count = builder.type_ids.size(); + const auto child_count = builder.child_value_ids.size(); + //! only objects have keys, so a row without children has no keys either + if (child_count && + (children_size + child_count > children_capacity || keys_size + builder.key_slots.size() > keys_capacity)) { + ReserveChildren(child_count, builder.key_slots.size()); + } + if (values_size + value_count > values_capacity) { + ReserveValues(values_size + value_count); + } string_t blob(builder.blob.data(), static_cast(blob_size)); if (!blob.IsInlined()) { - auto &heap = writer_state.blob_heap ? *writer_state.blob_heap : InitializeBlobHeap(); - blob = heap.AddBlob(blob); + blob = (blob_heap ? *blob_heap : InitializeBlobHeap()).AddBlob(blob); + } + + blob_data[current_idx] = blob; + values_data[current_idx] = list_entry_t(values_size, value_count); + if (value_count == 1) { + type_ids_data[values_size] = builder.type_ids.data()[0]; + byte_offset_data[values_size] = builder.byte_offsets.data()[0]; + } else { + memcpy(type_ids_data + values_size, builder.type_ids.data(), value_count * sizeof(uint8_t)); + memcpy(byte_offset_data + values_size, builder.byte_offsets.data(), value_count * sizeof(uint32_t)); + } + values_size += value_count; + if (child_count) { + WriteChildren(); + } else { + children_data[current_idx] = list_entry_t(children_size, 0); + keys_data[current_idx] = list_entry_t(keys_size, 0); } - writer_state.blobs.push_back(blob); current_idx++; } - DUCKDB_API void InitializeState(); + DUCKDB_API void Initialize(); + //! Reads the row arrays of the vector again, after a parent list moved them + DUCKDB_API void RefreshRows(); + void RefreshValues(); + void RefreshChildren(); + DUCKDB_API void ReserveValues(idx_t required); + //! Makes room for 'child_count' more children and 'key_count' more keys + DUCKDB_API void ReserveChildren(idx_t child_count, idx_t key_count); + DUCKDB_API void WriteChildren(); + DUCKDB_API void WriteNullRow(); DUCKDB_API StringHeap &InitializeBlobHeap(); DUCKDB_API static void ThrowRowTooLarge(); DUCKDB_API static void EmitContainer(const VariantNode &node, VariantBuilder &builder); - void Finalize(); private: Vector &variant; - unique_ptr state; - idx_t start_idx; + //! set by the first write, owned by the keys vector + optional_ptr state; idx_t count; idx_t current_idx; + + //! rows + list_entry_t *keys_data = nullptr; + list_entry_t *children_data = nullptr; + list_entry_t *values_data = nullptr; + string_t *blob_data = nullptr; + optional_ptr blob_heap; + //! values + uint8_t *type_ids_data = nullptr; + uint32_t *byte_offset_data = nullptr; + idx_t values_size = 0; + idx_t values_capacity = 0; + //! children + uint32_t *keys_index_data = nullptr; + uint32_t *values_index_data = nullptr; + optional_ptr keys_index_validity; + idx_t children_size = 0; + idx_t children_capacity = 0; + //! keys + string_t *keys_entry_data = nullptr; + idx_t keys_size = 0; + idx_t keys_capacity = 0; }; //! Specialization of VectorWriter for VectorListType. @@ -187,12 +233,13 @@ struct VectorWriter> { public: VectorWriter(Vector &vector, idx_t count, idx_t offset) : list_data(FlatVector::GetDataMutable(vector)), validity(FlatVector::ValidityMutable(vector)), - list_vec(vector), count(offset + count), current_idx(offset), child_offset(VectorWriterGetListSize(vector)), - child_writer(VectorWriterGetListChild(vector), 0, child_offset) { + list_vec(vector), count(offset + count), current_idx(offset), child_offset(ListVector::GetListSize(vector)), + child_capacity(ListVector::GetListCapacity(vector)), + child_writer(ListVector::GetChildMutable(vector), 0, child_offset) { } VectorWriter(VectorWriter &&other) noexcept : list_data(other.list_data), validity(other.validity), list_vec(other.list_vec), count(other.count), - current_idx(other.current_idx), child_offset(other.child_offset), + current_idx(other.current_idx), child_offset(other.child_offset), child_capacity(other.child_capacity), child_writer(std::move(other.child_writer)) { other.count = other.current_idx; } @@ -216,7 +263,7 @@ struct VectorWriter> { D_ASSERT(current_idx < count); // the elements of the previous list must all have been written D_ASSERT(child_writer.current_idx == child_offset); - VectorWriterReserveList(list_vec, child_offset + n); + ReserveElements(child_offset + n); VectorWriterSetListSize(list_vec, child_offset + n); list_data[current_idx] = {child_offset, n}; current_idx++; @@ -232,12 +279,22 @@ struct VectorWriter> { private: friend class DynamicListWriter; + void ReserveElements(idx_t required) { + if (required <= child_capacity) { + return; + } + VectorWriterReserveList(list_vec, required); + child_capacity = ListVector::GetListCapacity(list_vec); + child_writer.RefreshRows(); + } + list_entry_t *list_data; ValidityMask &validity; Vector &list_vec; idx_t count; idx_t current_idx; idx_t child_offset; + idx_t child_capacity; //! Writes the elements of all lists, its rows start at the list size of the vector when this writer was created VectorWriter child_writer; }; @@ -264,7 +321,7 @@ class DynamicListWriter { // the previous element must have been written D_ASSERT(parent.child_writer.current_idx == parent.child_offset + length); length++; - VectorWriterReserveList(parent.list_vec, parent.child_offset + length); + parent.ReserveElements(parent.child_offset + length); parent.child_writer.Extend(1); return parent.child_writer; } diff --git a/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp b/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp index c81dbeeca..2c02ca0a4 100644 --- a/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp +++ b/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp @@ -43,12 +43,20 @@ enum class VectorBufferType : uint8_t { enum class VectorAppendMode { ALLOW_RESIZE, ERROR_ON_NO_SPACE }; +//! Identifies the holders that are looked up again in the auxiliary data of a buffer +enum class AuxiliaryDataType : uint8_t { GENERIC, VARIANT_WRITER_STATE }; + struct AuxiliaryDataHolder { + AuxiliaryDataHolder() = default; + explicit AuxiliaryDataHolder(AuxiliaryDataType type) : type(type) { + } virtual ~AuxiliaryDataHolder() = default; virtual idx_t GetAllocationSize() const { return 0; } + + AuxiliaryDataType type = AuxiliaryDataType::GENERIC; }; struct AuxiliaryDataSet { diff --git a/src/duckdb/src/include/duckdb/function/aggregate_function.hpp b/src/duckdb/src/include/duckdb/function/aggregate_function.hpp index f2974d43c..cb000643e 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate_function.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate_function.hpp @@ -139,6 +139,8 @@ typedef void (*aggregate_window_batch_t)(AggregateInputData &aggr_input_data, co const SubFrames *subframes_per_row, idx_t count, Vector &result, idx_t row_idx); +//! Creates the state the custom window callbacks run on, in place of an aggregate state (optional) +typedef unique_ptr (*aggregate_init_window_state_t)(AggregateStateInput &input); //! The type used for initializing shared complex/custom windowed aggregate state (optional) typedef void (*aggregate_wininit_t)(AggregateInputData &aggr_input_data, const WindowPartitionInput &partition, data_ptr_t g_state); @@ -262,6 +264,10 @@ class AggregateFunctionCallbacks { aggregate_window_batch_t GetWindowBatchCallback() const { return window_batch; } void SetWindowBatchCallback(aggregate_window_batch_t callback) { window_batch = callback; } + bool HasInitWindowStateCallback() const { return init_window_state != nullptr; } + aggregate_init_window_state_t GetInitWindowStateCallback() const { return init_window_state; } + void SetInitWindowStateCallback(aggregate_init_window_state_t callback) { init_window_state = callback; } + bool HasStatisticsCallback() const { return statistics != nullptr; } aggregate_statistics_t GetStatisticsCallback() const { return statistics; } void SetStatisticsCallback(aggregate_statistics_t callback) { statistics = callback; } @@ -314,6 +320,8 @@ class AggregateFunctionCallbacks { aggregate_wininit_t window_init = nullptr; //! Batched windowed aggregate function (may be null; preferred when set) aggregate_window_batch_t window_batch = nullptr; + //! Creates the state of the custom window callbacks (may be null, then they run on an aggregate state) + aggregate_init_window_state_t init_window_state = nullptr; //! The bind function (may be null) bind_aggregate_function_t bind = nullptr; @@ -363,6 +371,9 @@ class AggregateFunctionProperties : public FunctionProperties { //! Whether an aggregate is holistic (e.g., don't use it for window segment trees...) bool is_holistic = false; + //! Whether a holistic aggregate still uses the window segment and distinct trees (each level copies its input) + bool allow_window_trees = false; + //! Whether combining can leave the target referencing the source's memory AggregateCombineSourceRetention combine_source_retention = AggregateCombineSourceRetention::MAY_RETAIN; @@ -419,6 +430,10 @@ class BaseAggregateFunction { auto IsHolistic() const -> bool { return properties.is_holistic; } auto SetIsHolistic(bool value) -> void { properties.is_holistic = value; } + //! Whether a holistic aggregate still uses the window segment and distinct trees (each level copies its input) + auto AllowsWindowTrees() const -> bool { return properties.allow_window_trees; } + auto SetAllowsWindowTrees(bool value) -> void { properties.allow_window_trees = value; } + //! Whether combining can leave the target referencing the source's memory auto GetCombineSourceRetention() const -> AggregateCombineSourceRetention { return properties.combine_source_retention; } auto SetCombineSourceRetention(AggregateCombineSourceRetention value) -> void { properties.combine_source_retention = value; } @@ -484,6 +499,10 @@ class BaseAggregateFunction { auto GetWindowBatchCallback() const -> aggregate_window_batch_t { return callbacks.window_batch; } auto SetWindowBatchCallback(aggregate_window_batch_t callback) -> void { callbacks.window_batch = callback; } + bool HasInitWindowStateCallback() const { return callbacks.init_window_state != nullptr; } + aggregate_init_window_state_t GetInitWindowStateCallback() const { return callbacks.init_window_state; } + void SetInitWindowStateCallback(aggregate_init_window_state_t callback) { callbacks.init_window_state = callback; } + auto HasStatisticsCallback() const -> bool { return callbacks.statistics != nullptr; } auto GetStatisticsCallback() const -> aggregate_statistics_t { return callbacks.statistics; } auto SetStatisticsCallback(aggregate_statistics_t callback) -> void { callbacks.statistics = callback; } 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 f70f44987..be62e3fbe 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 @@ -51,7 +51,7 @@ struct VariantPathFunction { const auto &path_type_id = input.data[1].GetType().id(); if (path_type_id == LogicalTypeId::LIST) { - ExecuteMany(variant_vec, info.paths, result, count, write_fn); + ExecuteMany(variant_vec, info, result, count, write_fn); return; } D_ASSERT(path_type_id == LogicalTypeId::VARCHAR || path_type_id == LogicalTypeId::BIGINT); @@ -80,10 +80,10 @@ struct VariantPathFunction { //! Executes a list of paths and writes LIST per input row. template - static void ExecuteMany(const Vector &input, const vector> &paths, Vector &result, - const idx_t count, const WRITE_FUNCTION &write_fn) { + static void ExecuteMany(const Vector &input, const VariantPathBindData &info, Vector &result, const idx_t count, + const WRITE_FUNCTION &write_fn) { const VectorIterator variants(input); - const auto keys = GetSingleKeys(paths); + const auto &paths = info.paths; result.Initialize(VectorDataInitialization::UNINITIALIZED, count); auto result_writer = FlatVector::Writer>(result, count); @@ -96,7 +96,7 @@ struct VariantPathFunction { continue; } - ResolvePaths(variants[row_idx], paths, keys, selected); + ResolvePaths(variants[row_idx], info, selected); idx_t path_idx = 0; for (auto &path_writer : result_writer.WriteList(paths.size())) { @@ -106,11 +106,9 @@ struct VariantPathFunction { } } - //! Returns the key of each path that is a single key lookup, and an empty optional for the other paths - static vector> GetSingleKeys(const vector> &paths); //! Resolves every path for 'root' into 'selected', the single key paths in one pass over the children of the object - static void ResolvePaths(const VariantNode &root, const vector> &paths, - const vector> &keys, vector> &selected); + static void ResolvePaths(const VariantNode &root, const VariantPathBindData &info, + vector> &selected); //! Returns the element at a 0-based index of an ARRAY, negative indexes count from the end. Returns nullopt if the //! node is not an ARRAY or the index is out of range. diff --git a/src/duckdb/src/include/duckdb/function/scalar/variant_utils.hpp b/src/duckdb/src/include/duckdb/function/scalar/variant_utils.hpp index 7a285e7a0..4fc164b36 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/variant_utils.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/variant_utils.hpp @@ -13,24 +13,67 @@ #include "duckdb/function/built_in_functions.hpp" #include "duckdb/common/types/variant.hpp" #include "duckdb/common/owning_string_map.hpp" +#include "duckdb/common/optional.hpp" +#include "duckdb/common/types/hash.hpp" namespace duckdb { class VariantIterator; +//! The positions of the single-key paths in a list of paths, looked up by key +class VariantPathKeyIndex { +public: + explicit VariantPathKeyIndex(const vector> &keys); + + //! The positions of the paths that look up 'key', as an entry into GetPositions(). Empty if no path does. + list_entry_t Find(const string_t &key) const { + const auto slot_data = slots.data(); + for (auto slot_idx = Hash(key) & mask;; slot_idx = (slot_idx + 1) & mask) { + auto &slot = slot_data[slot_idx]; + if (slot.positions.length == 0 || slot.key == key) { + return slot.positions; + } + } + } + const idx_t *GetPositions() const { + return positions.data(); + } + +private: + struct Slot { + string_t key; + //! empty for an unused slot + list_entry_t positions; + }; + vector slots; + idx_t mask; + vector positions; +}; + struct VariantPathBindData : public FunctionData { public: explicit VariantPathBindData(); explicit VariantPathBindData(const string &input_path); explicit VariantPathBindData(const vector &input_paths); explicit VariantPathBindData(int64_t index); - VariantPathBindData(const VariantPathBindData &other) = default; + VariantPathBindData(const VariantPathBindData &other); public: unique_ptr Copy() const override; bool Equals(const FunctionData &other) const override; + //! The number of single-key paths from which on they are looked up through the key index + static constexpr idx_t KEY_INDEX_THRESHOLD = 8; + public: vector> paths; + //! The key of every path that is a single key lookup, and an empty optional for the other paths. Points into + //! 'paths'. + vector> single_keys; + //! Only built when there are at least KEY_INDEX_THRESHOLD single-key paths + unique_ptr key_index; + +private: + void IndexPaths(); }; struct VariantExtractBindData : public FunctionData { diff --git a/src/duckdb/src/include/duckdb/optimizer/aggregate_reuse_internal.hpp b/src/duckdb/src/include/duckdb/optimizer/aggregate_reuse_internal.hpp index 0cc330a8f..de7387736 100644 --- a/src/duckdb/src/include/duckdb/optimizer/aggregate_reuse_internal.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/aggregate_reuse_internal.hpp @@ -1,26 +1,11 @@ #pragma once -#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" -#include "duckdb/common/column_index.hpp" -#include "duckdb/common/optional.hpp" -#include "duckdb/planner/logical_operator.hpp" +#include "duckdb/optimizer/column_origin.hpp" namespace duckdb { -class Expression; class LogicalAggregate; -struct TableColumnOrigin { - reference table; - ColumnIndex column; -}; - -optional_idx GetDirectReferenceIndex(const Expression &expression, LogicalOperator &input); -optional_idx GetInvertibleReferenceIndex(const Expression &expression, LogicalOperator &input); -optional GetTableColumnOrigin(LogicalOperator &op, idx_t output_idx, bool allow_filtered = false); -optional GetTableColumnOrigin(LogicalOperator &op, const Expression &expression, - bool allow_filtered = false); -bool SameOrigin(const TableColumnOrigin &left, const TableColumnOrigin &right); bool HasCompleteGrouping(const LogicalAggregate &aggregate); optional_ptr FindUnaryAggregate(LogicalOperator &op); diff --git a/src/duckdb/src/include/duckdb/optimizer/column_origin.hpp b/src/duckdb/src/include/duckdb/optimizer/column_origin.hpp new file mode 100644 index 000000000..aaee83a16 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/column_origin.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" +#include "duckdb/common/column_index.hpp" +#include "duckdb/common/optional.hpp" +#include "duckdb/planner/logical_operator.hpp" + +namespace duckdb { + +class Expression; + +struct TableColumnOrigin { + reference table; + ColumnIndex column; +}; + +struct ColumnOriginHelper { + static optional_idx GetDirectReferenceIndex(const Expression &expression, LogicalOperator &input); + static optional_idx GetInvertibleReferenceIndex(const Expression &expression, LogicalOperator &input); + + static optional GetTableColumnOrigin(LogicalOperator &op, idx_t output_idx, + bool allow_filtered = false); + static optional GetTableColumnOrigin(LogicalOperator &op, const Expression &expression, + bool allow_filtered = false); + //! Resolve complete-population origins together, sharing binding lookup across columns. + static vector> GetTableColumnOrigins(LogicalOperator &op); + static bool SameOrigin(const TableColumnOrigin &left, const TableColumnOrigin &right); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp index c3220c1f0..c1723ae30 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp @@ -18,12 +18,29 @@ namespace duckdb { -enum class DistinctCountSource : uint8_t { CARDINALITY, MIN_MAX, HLL, EXACT }; +enum class DistinctCountSource : uint8_t { + CARDINALITY, + MIN_MAX, + HLL, + EXACT, + //! Combined domains estimate equality denominators without establishing value coverage. + COMBINED +}; struct DistinctCount { public: DistinctCount(CardinalityValue distinct_count, DistinctCountSource source); +public: + //! Counts obtained from observations or exact expressions, excluding range estimates. + bool IsObserved() const { + return source == DistinctCountSource::HLL || source == DistinctCountSource::EXACT; + } + + bool CanEstimateCoverage() const { + return IsObserved() || source == DistinctCountSource::MIN_MAX; + } + public: CardinalityValue distinct_count; DistinctCountSource source; diff --git a/src/duckdb/src/include/duckdb/parallel/pipeline.hpp b/src/duckdb/src/include/duckdb/parallel/pipeline.hpp index 337b8cae1..80e46a482 100644 --- a/src/duckdb/src/include/duckdb/parallel/pipeline.hpp +++ b/src/duckdb/src/include/duckdb/parallel/pipeline.hpp @@ -271,6 +271,8 @@ class Pipeline : public enable_shared_from_this { shared_ptr source_state DUCKDB_GUARDED_BY(source_state_lock); //! Lock for resetting or inspecting the global source state pointer annotated_mutex source_state_lock; + //! Intermediate operator that finished this run of the pipeline, or nullptr + atomic> finished_operator {nullptr}; //! The parent pipelines (i.e. pipelines that are dependent on this pipeline to finish) vector> parents; diff --git a/src/duckdb/src/optimizer/aggregate_reuse.cpp b/src/duckdb/src/optimizer/aggregate_reuse.cpp index 69339b3ed..a8bcd8f57 100644 --- a/src/duckdb/src/optimizer/aggregate_reuse.cpp +++ b/src/duckdb/src/optimizer/aggregate_reuse.cpp @@ -23,10 +23,6 @@ namespace duckdb { -optional_idx GetDirectReferenceIndex(const Expression &expression, LogicalOperator &input) { - return AggregateRewriteHelper::GetDirectReferenceIndex(expression, input); -} - struct AggregateJoinCandidate { idx_t owner_child; idx_t probe_child; @@ -35,87 +31,6 @@ struct AggregateJoinCandidate { vector owner_groups; }; -optional_idx GetInvertibleReferenceIndex(const Expression &expression, LogicalOperator &input) { - auto result = GetDirectReferenceIndex(expression, input); - if (result.IsValid() || !BoundCastExpression::IsCast(expression)) { - return result; - } - auto &cast = expression.Cast(); - if (!BoundCastExpression::CastIsInvertible(BoundCastExpression::SourceType(cast), - BoundCastExpression::TargetType(cast))) { - return optional_idx(); - } - return GetInvertibleReferenceIndex(BoundCastExpression::Child(cast), input); -} - -optional GetTableColumnOrigin(LogicalOperator &op, idx_t output_idx, bool allow_filtered) { - if (output_idx >= op.GetColumnBindings().size()) { - return nullopt; - } - if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { - auto &projection = op.Cast(); - if (projection.children.size() != 1 || output_idx >= projection.expressions.size()) { - return nullopt; - } - auto child_idx = allow_filtered - ? GetInvertibleReferenceIndex(*projection.expressions[output_idx], *projection.children[0]) - : GetDirectReferenceIndex(*projection.expressions[output_idx], *projection.children[0]); - return child_idx.IsValid() ? GetTableColumnOrigin(*projection.children[0], child_idx.GetIndex(), allow_filtered) - : nullopt; - } - if (op.type == LogicalOperatorType::LOGICAL_FILTER) { - if (!allow_filtered) { - return nullopt; - } - auto &filter = op.Cast(); - if (filter.children.size() != 1) { - return nullopt; - } - if (!filter.projection_map.empty()) { - if (output_idx >= filter.projection_map.size()) { - return nullopt; - } - output_idx = filter.projection_map[output_idx].GetIndex(); - } - return GetTableColumnOrigin(*filter.children[0], output_idx, allow_filtered); - } - if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { - if (!allow_filtered) { - return nullopt; - } - auto binding = op.GetColumnBindings()[output_idx]; - for (auto &child : op.children) { - auto bindings = child->GetColumnBindings(); - auto entry = std::find(bindings.begin(), bindings.end(), binding); - if (entry != bindings.end()) { - return GetTableColumnOrigin(*child, NumericCast(entry - bindings.begin()), allow_filtered); - } - } - return nullopt; - } - if (op.type != LogicalOperatorType::LOGICAL_GET) { - return nullopt; - } - auto &get = op.Cast(); - auto table = get.GetTable(); - if (!table || !get.children.empty() || !get.scan_partition_indices.empty() || - (!allow_filtered && - (get.table_filters.HasFilters() || (get.dynamic_filters && get.dynamic_filters->HasFilters())))) { - return nullopt; - } - return TableColumnOrigin {*table, get.GetColumnIndex(ProjectionIndex(output_idx))}; -} - -optional GetTableColumnOrigin(LogicalOperator &op, const Expression &expression, - bool allow_filtered) { - auto output_idx = GetDirectReferenceIndex(expression, op); - return output_idx.IsValid() ? GetTableColumnOrigin(op, output_idx.GetIndex(), allow_filtered) : nullopt; -} - -bool SameOrigin(const TableColumnOrigin &left, const TableColumnOrigin &right) { - return &left.table.get() == &right.table.get() && left.column == right.column; -} - static optional_idx GetJoinOutputReference(const Expression &expression, LogicalComparisonJoin &join, idx_t &child_index) { if (expression.GetExpressionClass() == ExpressionClass::BOUND_REF) { @@ -136,7 +51,7 @@ static optional_idx GetJoinOutputReference(const Expression &expression, Logical return optional_idx(); } for (idx_t side = 0; side < 2; side++) { - auto index = GetDirectReferenceIndex(expression, *join.children[side]); + auto index = ColumnOriginHelper::GetDirectReferenceIndex(expression, *join.children[side]); if (index.IsValid()) { child_index = side; return index; @@ -175,8 +90,8 @@ static optional GetCandidate(LogicalAggregate &aggregate condition.GetLHS().GetReturnType() != condition.GetRHS().GetReturnType()) { return nullopt; } - auto left_key = GetDirectReferenceIndex(condition.GetLHS(), *join.children[0]); - auto right_key = GetDirectReferenceIndex(condition.GetRHS(), *join.children[1]); + auto left_key = ColumnOriginHelper::GetDirectReferenceIndex(condition.GetLHS(), *join.children[0]); + auto right_key = ColumnOriginHelper::GetDirectReferenceIndex(condition.GetRHS(), *join.children[1]); if (!left_key.IsValid() || !right_key.IsValid()) { return nullopt; } @@ -191,7 +106,8 @@ static optional GetCandidate(LogicalAggregate &aggregate } for (idx_t owner_child = 0; owner_child < 2; owner_child++) { const auto probe_child = 1 - owner_child; - if (!GetDirectReferenceIndex(*outer_aggregate.GetChildren()[0], *join.children[probe_child]).IsValid()) { + if (!ColumnOriginHelper::GetDirectReferenceIndex(*outer_aggregate.GetChildren()[0], *join.children[probe_child]) + .IsValid()) { continue; } const auto owner_key = owner_child == 0 ? left_key.GetIndex() : right_key.GetIndex(); @@ -247,7 +163,8 @@ static optional_idx FindTracedOutput(LogicalOperator &op, const ColumnBinding &t return optional_idx(); } for (idx_t output_idx = 0; output_idx < projection.expressions.size(); output_idx++) { - auto child_idx = GetInvertibleReferenceIndex(*projection.expressions[output_idx], *projection.children[0]); + auto child_idx = ColumnOriginHelper::GetInvertibleReferenceIndex(*projection.expressions[output_idx], + *projection.children[0]); if (child_idx == traced) { return optional_idx(output_idx); } @@ -349,9 +266,9 @@ static bool SameReusableAggregate(const BoundAggregateExpression &outer, Logical !FunctionData::Equals(outer.BindInfo().get(), inner.BindInfo().get())) { return false; } - auto outer_origin = GetTableColumnOrigin(outer_input, *outer.GetChildren()[0]); - auto inner_origin = GetTableColumnOrigin(inner_input, *inner.GetChildren()[0]); - return outer_origin && inner_origin && SameOrigin(*outer_origin, *inner_origin); + auto outer_origin = ColumnOriginHelper::GetTableColumnOrigin(outer_input, *outer.GetChildren()[0]); + auto inner_origin = ColumnOriginHelper::GetTableColumnOrigin(inner_input, *inner.GetChildren()[0]); + return outer_origin && inner_origin && ColumnOriginHelper::SameOrigin(*outer_origin, *inner_origin); } static optional PromoteReusableAggregate(Optimizer &optimizer, unique_ptr &op, @@ -367,7 +284,8 @@ static optional PromoteReusableAggregate(Optimizer &optimizer, un return nullopt; } auto key_idx = NumericCast(key_entry - bindings.begin()); - auto child_idx = GetDirectReferenceIndex(*projection.expressions[key_idx], *projection.children[0]); + auto child_idx = + ColumnOriginHelper::GetDirectReferenceIndex(*projection.expressions[key_idx], *projection.children[0]); if (!child_idx.IsValid()) { return nullopt; } @@ -425,8 +343,8 @@ static optional PromoteReusableAggregate(Optimizer &optimizer, un join.children[1]->type != LogicalOperatorType::LOGICAL_PROJECTION) { return nullopt; } - auto left_key = GetDirectReferenceIndex(join.conditions[0].GetLHS(), *join.children[0]); - auto right_key = GetDirectReferenceIndex(join.conditions[0].GetRHS(), *join.children[1]); + auto left_key = ColumnOriginHelper::GetDirectReferenceIndex(join.conditions[0].GetLHS(), *join.children[0]); + auto right_key = ColumnOriginHelper::GetDirectReferenceIndex(join.conditions[0].GetRHS(), *join.children[1]); if (!left_key.IsValid() || !right_key.IsValid() || join.children[0]->GetColumnBindings()[left_key.GetIndex()] != key_binding) { return nullopt; @@ -444,13 +362,14 @@ static optional PromoteReusableAggregate(Optimizer &optimizer, un } auto group_binding = ColumnBinding(inner_aggregate->group_index, ProjectionIndex(0)); auto traced_group = FindTracedOutput(*right_projection.children[0], group_binding); - auto projected_key = GetInvertibleReferenceIndex(*right_projection.expressions[right_key.GetIndex()], - *right_projection.children[0]); + auto projected_key = ColumnOriginHelper::GetInvertibleReferenceIndex( + *right_projection.expressions[right_key.GetIndex()], *right_projection.children[0]); if (!traced_group.IsValid() || projected_key != traced_group) { return nullopt; } - auto right_key_origin = GetTableColumnOrigin(*inner_aggregate->children[0], *inner_aggregate->groups[0]); - if (!right_key_origin || !SameOrigin(*right_key_origin, outer_key_origin)) { + auto right_key_origin = + ColumnOriginHelper::GetTableColumnOrigin(*inner_aggregate->children[0], *inner_aggregate->groups[0]); + if (!right_key_origin || !ColumnOriginHelper::SameOrigin(*right_key_origin, outer_key_origin)) { return nullopt; } idx_t aggregate_idx = DConstants::INVALID_INDEX; @@ -569,7 +488,7 @@ bool AggregateReuseOptimizer::TryReuseSemiAggregate(unique_ptr auto &owner = join.children[candidate->owner_child]; auto &probe = join.children[candidate->probe_child]; auto owner_bindings = owner->GetColumnBindings(); - auto outer_key_origin = GetTableColumnOrigin(*probe, candidate->probe_key); + auto outer_key_origin = ColumnOriginHelper::GetTableColumnOrigin(*probe, candidate->probe_key); if (!outer_key_origin || candidate->owner_key >= owner_bindings.size()) { return false; } diff --git a/src/duckdb/src/optimizer/aggregate_rewrite_helper.cpp b/src/duckdb/src/optimizer/aggregate_rewrite_helper.cpp index e7c769abe..89836dda9 100644 --- a/src/duckdb/src/optimizer/aggregate_rewrite_helper.cpp +++ b/src/duckdb/src/optimizer/aggregate_rewrite_helper.cpp @@ -1,6 +1,7 @@ #include "duckdb/optimizer/aggregate_rewrite_helper.hpp" #include "duckdb/common/string_util.hpp" +#include "duckdb/optimizer/column_origin.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" @@ -14,21 +15,7 @@ namespace duckdb { optional_idx AggregateRewriteHelper::GetDirectReferenceIndex(const Expression &expression, LogicalOperator &input) { - auto bindings = input.GetColumnBindings(); - if (expression.GetExpressionClass() == ExpressionClass::BOUND_REF) { - auto index = expression.Cast().Index(); - return index < bindings.size() ? optional_idx(index) : optional_idx(); - } - if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - return optional_idx(); - } - auto binding = expression.Cast().Binding(); - for (idx_t index = 0; index < bindings.size(); index++) { - if (bindings[index] == binding) { - return optional_idx(index); - } - } - return optional_idx(); + return ColumnOriginHelper::GetDirectReferenceIndex(expression, input); } vector AggregateRewriteHelper::GenerateColumnNames(const string &prefix, idx_t column_count) { diff --git a/src/duckdb/src/optimizer/column_origin.cpp b/src/duckdb/src/optimizer/column_origin.cpp new file mode 100644 index 000000000..5f1d67854 --- /dev/null +++ b/src/duckdb/src/optimizer/column_origin.cpp @@ -0,0 +1,171 @@ +#include "duckdb/optimizer/column_origin.hpp" + +#include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/expression/bound_cast_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" + +namespace duckdb { + +optional_idx ColumnOriginHelper::GetDirectReferenceIndex(const Expression &expression, LogicalOperator &input) { + auto bindings = input.GetColumnBindings(); + if (expression.GetExpressionClass() == ExpressionClass::BOUND_REF) { + auto index = expression.Cast().Index(); + return index < bindings.size() ? optional_idx(index) : optional_idx(); + } + if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return optional_idx(); + } + auto binding = expression.Cast().Binding(); + for (idx_t index = 0; index < bindings.size(); index++) { + if (bindings[index] == binding) { + return optional_idx(index); + } + } + return optional_idx(); +} + +optional_idx ColumnOriginHelper::GetInvertibleReferenceIndex(const Expression &expression, LogicalOperator &input) { + auto result = GetDirectReferenceIndex(expression, input); + if (result.IsValid() || !BoundCastExpression::IsCast(expression)) { + return result; + } + auto &cast = expression.Cast(); + if (!BoundCastExpression::CastIsInvertible(BoundCastExpression::SourceType(cast), + BoundCastExpression::TargetType(cast))) { + return optional_idx(); + } + return GetInvertibleReferenceIndex(BoundCastExpression::Child(cast), input); +} + +optional ColumnOriginHelper::GetTableColumnOrigin(LogicalOperator &op, idx_t output_idx, + bool allow_filtered) { + if (op.type == LogicalOperatorType::LOGICAL_GET) { + auto &get = op.Cast(); + auto table = get.GetTable(); + if (!table || !get.children.empty() || !get.scan_partition_indices.empty() || + (!allow_filtered && (get.extra_info.sample_options || get.table_filters.HasFilters() || + (get.dynamic_filters && get.dynamic_filters->HasFilters())))) { + return nullopt; + } + auto column_count = get.projection_ids.empty() ? get.GetColumnIds().size() : get.projection_ids.size(); + if (output_idx >= column_count) { + return nullopt; + } + auto index = get.projection_ids.empty() ? ProjectionIndex(output_idx) : get.projection_ids[output_idx]; + return TableColumnOrigin {*table, get.GetColumnIndex(index)}; + } + if (output_idx >= op.GetColumnBindings().size()) { + return nullopt; + } + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto &projection = op.Cast(); + if (projection.children.size() != 1 || output_idx >= projection.expressions.size()) { + return nullopt; + } + auto child_idx = allow_filtered + ? GetInvertibleReferenceIndex(*projection.expressions[output_idx], *projection.children[0]) + : GetDirectReferenceIndex(*projection.expressions[output_idx], *projection.children[0]); + return child_idx.IsValid() ? GetTableColumnOrigin(*projection.children[0], child_idx.GetIndex(), allow_filtered) + : nullopt; + } + if (op.type == LogicalOperatorType::LOGICAL_FILTER) { + if (!allow_filtered) { + return nullopt; + } + auto &filter = op.Cast(); + if (filter.children.size() != 1) { + return nullopt; + } + if (!filter.projection_map.empty()) { + if (output_idx >= filter.projection_map.size()) { + return nullopt; + } + output_idx = filter.projection_map[output_idx].GetIndex(); + } + return GetTableColumnOrigin(*filter.children[0], output_idx, allow_filtered); + } + if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + if (!allow_filtered) { + return nullopt; + } + auto binding = op.GetColumnBindings()[output_idx]; + for (auto &child : op.children) { + auto bindings = child->GetColumnBindings(); + auto entry = std::find(bindings.begin(), bindings.end(), binding); + if (entry != bindings.end()) { + return GetTableColumnOrigin(*child, NumericCast(entry - bindings.begin()), allow_filtered); + } + } + return nullopt; + } + return nullopt; +} + +vector> ColumnOriginHelper::GetTableColumnOrigins(LogicalOperator &op) { + if (op.type != LogicalOperatorType::LOGICAL_GET && op.type != LogicalOperatorType::LOGICAL_PROJECTION) { + return {}; + } + vector indices; + auto column_count = op.GetColumnBindings().size(); + indices.reserve(column_count); + for (idx_t index = 0; index < column_count; index++) { + indices.emplace_back(index); + } + + optional_ptr input = op; + while (input->type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto &projection = input->Cast(); + if (projection.children.size() != 1) { + return {}; + } + auto child_bindings = projection.children[0]->GetColumnBindings(); + column_binding_map_t child_indices; + child_indices.reserve(child_bindings.size()); + for (idx_t index = 0; index < child_bindings.size(); index++) { + child_indices.emplace(child_bindings[index], index); + } + for (auto &index : indices) { + if (!index.IsValid()) { + continue; + } + auto &expression = *projection.expressions[index.GetIndex()]; + if (expression.GetExpressionClass() == ExpressionClass::BOUND_REF) { + auto child_index = expression.Cast().Index(); + index = child_index < child_bindings.size() ? optional_idx(child_index) : optional_idx(); + } else if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto entry = child_indices.find(expression.Cast().Binding()); + index = entry != child_indices.end() ? optional_idx(entry->second) : optional_idx(); + } else { + index = optional_idx(); + } + } + input = projection.children[0].get(); + } + if (input->type != LogicalOperatorType::LOGICAL_GET) { + return {}; + } + + vector> result; + result.reserve(indices.size()); + for (auto &index : indices) { + result.push_back(index.IsValid() ? GetTableColumnOrigin(*input, index.GetIndex()) : nullopt); + } + return result; +} + +optional ColumnOriginHelper::GetTableColumnOrigin(LogicalOperator &op, const Expression &expression, + bool allow_filtered) { + auto output_idx = GetDirectReferenceIndex(expression, op); + return output_idx.IsValid() ? GetTableColumnOrigin(op, output_idx.GetIndex(), allow_filtered) : nullopt; +} + +bool ColumnOriginHelper::SameOrigin(const TableColumnOrigin &left, const TableColumnOrigin &right) { + return &left.table.get() == &right.table.get() && left.column == right.column; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp b/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp index 5577bf0bd..b8e3218c6 100644 --- a/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp +++ b/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp @@ -157,7 +157,7 @@ void CTEJoinFilterPusher::Optimize(LogicalOperator &op) { } auto &source_distinct = source_stats->columns[source_col].total_domain; auto &target_distinct = target_stats->columns[target_col].total_domain; - if (target_distinct.source == DistinctCountSource::CARDINALITY || target_distinct.distinct_count == 0) { + if (!target_distinct.CanEstimateCoverage() || target_distinct.distinct_count == 0) { continue; } auto source_count = MinValue(source_distinct.distinct_count, source_stats->cardinality); diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp index d828ac914..0fac6b12b 100644 --- a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp @@ -772,8 +772,7 @@ double DomainCostModel::EstimateRecoveryDomainRows(const RelationStats &domain) CardinalityValue distinct_count(1); for (auto &column : domain.columns) { // Key independence and range-based estimates can hide repeated tuples. - if (column.total_domain.source == DistinctCountSource::HLL || - column.total_domain.source == DistinctCountSource::EXACT) { + if (column.total_domain.IsObserved()) { distinct_count = MaxValue(distinct_count, column.current_domain.distinct_count); } } diff --git a/src/duckdb/src/optimizer/grouping_sets_optimizer.cpp b/src/duckdb/src/optimizer/grouping_sets_optimizer.cpp index 19c79dc1e..c6d36a863 100644 --- a/src/duckdb/src/optimizer/grouping_sets_optimizer.cpp +++ b/src/duckdb/src/optimizer/grouping_sets_optimizer.cpp @@ -64,6 +64,10 @@ static bool CanRewriteAggregate(const BoundAggregateExpression &aggregate) { } // mirror the requirements of ExportAggregateFunction::Bind so that binding the export cannot fail auto &function = aggregate.Function(); + if (function.IsHolistic()) { + // combining holistic states copies all their values - computing each grouping set separately is cheaper + return false; + } if (!function.HasStateCombineCallback() || function.HasStateDestructorCallback() || !function.HasStateSizeCallback() || !function.HasStateFinalizeCallback() || !function.HasGetStateTypeCallback()) { diff --git a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp index a494b0454..2124a0d51 100644 --- a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp +++ b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp @@ -25,8 +25,13 @@ struct DomainEstimate { void AddSource(const JoinColumnSource &source); void Restrict(idx_t bound); +private: + CardinalityValue GetSourceDistinctCount(const JoinPredicate &predicate) const; + private: optional estimate; + //! Combined domains affect the whole equality class without becoming observed evidence. + optional combined_distinct_count; //! Row-count fallbacks apply only to predicates involving their relation. column_binding_map_t local_fallbacks; column_binding_set_t sources; @@ -39,6 +44,16 @@ DomainEstimate::DomainEstimate() { } CardinalityValue DomainEstimate::GetDistinctCount(const JoinPredicate &predicate) const { + auto result = GetSourceDistinctCount(predicate); + auto comparison = predicate.GetComparisonType(); + if (combined_distinct_count && + (comparison == ExpressionType::COMPARE_EQUAL || comparison == ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { + return MaxValue(result, *combined_distinct_count); + } + return result; +} + +CardinalityValue DomainEstimate::GetSourceDistinctCount(const JoinPredicate &predicate) const { auto domain = estimate; for (bool left : {true, false}) { auto entry = local_fallbacks.find(predicate.GetStatsBinding(left)); @@ -71,7 +86,7 @@ CardinalityValue DomainEstimate::GetDistinctCount(const JoinPredicate &predicate } bool DomainEstimate::HasReliableDistinctCount() const { - return estimate && (estimate->source == DistinctCountSource::HLL || estimate->source == DistinctCountSource::EXACT); + return estimate && estimate->IsObserved(); } CardinalityValue DomainEstimate::GetReliableDistinctCount() const { @@ -82,6 +97,8 @@ CardinalityValue DomainEstimate::GetReliableDistinctCount() const { } void DomainEstimate::Restrict(idx_t bound) { + // RestrictFilterDomains excludes classes containing combined domains. + D_ASSERT(!combined_distinct_count); D_ASSERT(estimate); if (!estimate) { return; @@ -95,7 +112,7 @@ void DomainEstimate::AddSource(const JoinColumnSource &source) { if (!sources.insert(source.binding).second) { return; } - if (source.domain.source == DistinctCountSource::HLL || source.domain.source == DistinctCountSource::EXACT) { + if (source.domain.IsObserved()) { reliable_source_cardinality = MinValue(reliable_source_cardinality, source.source_cardinality); reliable_source_count++; } @@ -103,6 +120,14 @@ void DomainEstimate::AddSource(const JoinColumnSource &source) { void DomainEstimate::Update(ColumnBinding binding, const DistinctCount &distinct_count, optional_ptr column_sources) { + if (distinct_count.source == DistinctCountSource::COMBINED) { + combined_distinct_count = combined_distinct_count + ? MaxValue(*combined_distinct_count, distinct_count.distinct_count) + : distinct_count.distinct_count; + local_fallbacks.emplace(binding, + DistinctCount(distinct_count.distinct_count, DistinctCountSource::CARDINALITY)); + return; + } if (column_sources) { AddSource(column_sources->direct); for (auto &source : column_sources->equivalents) { @@ -111,9 +136,8 @@ void DomainEstimate::Update(ColumnBinding binding, const DistinctCount &distinct } else if (distinct_count.source == DistinctCountSource::CARDINALITY) { local_fallbacks.emplace(binding, distinct_count); return; - } else if (distinct_count.source == DistinctCountSource::HLL || - distinct_count.source == DistinctCountSource::EXACT) { - // A reliable derived domain has no known source population for the uplift guard. + } else if (distinct_count.IsObserved()) { + // Observed counts without scan origins have no population for the uplift guard. reliable_source_cardinality = 0; } if (column_sources && distinct_count.source == DistinctCountSource::MIN_MAX) { @@ -1000,8 +1024,8 @@ SemiAntiJoinCardinalityEstimate CardinalityEstimator::EstimateMembership(const L has_residual = true; continue; } - // Row-count fallbacks bound domains but do not estimate membership coverage. - if (total->source == DistinctCountSource::CARDINALITY) { + // Domain bounds alone do not estimate membership coverage. + if (!total->CanEstimateCoverage()) { has_residual = true; } domains.push_back({total->distinct_count, *supported, key.first, key.second}); @@ -1517,7 +1541,7 @@ void CardinalityEstimator::RestrictFilterDomains(const vector &re auto &column = relation_stats[binding.table_index.index].columns[binding.column_index.GetIndex()]; auto bound = column.semi_anti_join_domain_evidence.GetDomainBound(); // Unknown-NDV filters need their scan selectivities refined before shrinking the join domain. - if (!bound.IsValid() || column.total_domain.source == DistinctCountSource::CARDINALITY) { + if (!bound.IsValid() || !column.total_domain.CanEstimateCoverage()) { all_filtered = false; break; } diff --git a/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp b/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp index 5ba9834ee..5f2eae3ed 100644 --- a/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp +++ b/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp @@ -42,7 +42,7 @@ static optional FindBindingOrigin(LogicalOperator &op, const auto bindings = op.GetColumnBindings(); auto entry = std::find(bindings.begin(), bindings.end(), binding); if (entry != bindings.end()) { - auto result = GetTableColumnOrigin(op, NumericCast(entry - bindings.begin()), true); + auto result = ColumnOriginHelper::GetTableColumnOrigin(op, NumericCast(entry - bindings.begin()), true); if (result) { return result; } @@ -60,8 +60,10 @@ static bool SameEdge(const RelationEdge &left, const RelationEdge &right) { if (left.comparison != right.comparison) { return false; } - return (SameOrigin(left.left, right.left) && SameOrigin(left.right, right.right)) || - (SameOrigin(left.left, right.right) && SameOrigin(left.right, right.left)); + return (ColumnOriginHelper::SameOrigin(left.left, right.left) && + ColumnOriginHelper::SameOrigin(left.right, right.right)) || + (ColumnOriginHelper::SameOrigin(left.left, right.right) && + ColumnOriginHelper::SameOrigin(left.right, right.left)); } static bool CollectInnerGraph(LogicalOperator &op, optional_ptr domain_semi, @@ -106,8 +108,8 @@ static bool CollectInnerGraph(LogicalOperator &op, optional_ptr= projection.expressions.size()) { return optional_idx(); } - auto child_idx = GetInvertibleReferenceIndex(*projection.expressions[output_idx], *op.children[0]); + auto child_idx = + ColumnOriginHelper::GetInvertibleReferenceIndex(*projection.expressions[output_idx], *op.children[0]); return child_idx.IsValid() ? TraceDomainOutput(*op.children[0], child_idx.GetIndex(), cte_index) : optional_idx(); } @@ -165,7 +168,8 @@ static optional_idx TraceDomainOutput(LogicalOperator &op, idx_t output_idx, Tab if (output_idx >= aggregate.groups.size()) { return optional_idx(); } - auto child_idx = GetInvertibleReferenceIndex(*aggregate.groups[output_idx], *op.children[0]); + auto child_idx = + ColumnOriginHelper::GetInvertibleReferenceIndex(*aggregate.groups[output_idx], *op.children[0]); return child_idx.IsValid() ? TraceDomainOutput(*op.children[0], child_idx.GetIndex(), cte_index) : optional_idx(); } @@ -221,8 +225,8 @@ static optional FindDomainSemi(LogicalOperator &op) { } auto &core_expression = core_child == 0 ? condition.GetLHS() : condition.GetRHS(); auto &domain_expression = domain_child == 0 ? condition.GetLHS() : condition.GetRHS(); - auto core_key = GetTableColumnOrigin(*join.children[core_child], core_expression, true); - auto domain_idx = GetDirectReferenceIndex(domain_expression, *join.children[domain_child]); + auto core_key = ColumnOriginHelper::GetTableColumnOrigin(*join.children[core_child], core_expression, true); + auto domain_idx = ColumnOriginHelper::GetDirectReferenceIndex(domain_expression, *join.children[domain_child]); if (!core_key || !domain_idx.IsValid()) { return nullopt; } @@ -305,7 +309,8 @@ static bool IsDomainCorrelationFilter(const TableFilter &filter, const TableColu return false; } for (idx_t idx = 0; idx < domain_keys.size(); idx++) { - if (SameOrigin(subject, core_keys[idx]) && SameOrigin(*external, domain_keys[idx])) { + if (ColumnOriginHelper::SameOrigin(subject, core_keys[idx]) && + ColumnOriginHelper::SameOrigin(*external, domain_keys[idx])) { return true; } } @@ -337,7 +342,7 @@ static bool SourceFiltersMatch(const RelationGraph &core, const RelationGraph &p } TableColumnOrigin subject {*table, column}; bool is_core_key = std::find_if(core_keys.begin(), core_keys.end(), [&](const TableColumnOrigin &key) { - return SameOrigin(subject, key); + return ColumnOriginHelper::SameOrigin(subject, key); }) != core_keys.end(); if (!is_core_key || !IsDomainCorrelationFilter(entry.Filter(), subject, producer_op, core_keys, domain_keys)) { @@ -351,8 +356,8 @@ static bool SourceFiltersMatch(const RelationGraph &core, const RelationGraph &p static optional_idx FindProducerOutput(LogicalOperator &producer, const TableColumnOrigin &origin) { auto bindings = producer.GetColumnBindings(); for (idx_t idx = 0; idx < bindings.size(); idx++) { - auto candidate = GetTableColumnOrigin(producer, idx, true); - if (candidate && SameOrigin(*candidate, origin)) { + auto candidate = ColumnOriginHelper::GetTableColumnOrigin(producer, idx, true); + if (candidate && ColumnOriginHelper::SameOrigin(*candidate, origin)) { return optional_idx(idx); } } @@ -365,7 +370,7 @@ static unique_ptr RewriteToCTE(const Expression &expression, Logical bool &success) { if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF || expression.GetExpressionClass() == ExpressionClass::BOUND_REF) { - auto output_idx = GetDirectReferenceIndex(expression, scope); + auto output_idx = ColumnOriginHelper::GetDirectReferenceIndex(expression, scope); if (!output_idx.IsValid()) { success = false; return nullptr; @@ -379,13 +384,13 @@ static unique_ptr RewriteToCTE(const Expression &expression, Logical return RewriteToCTE(*projection.expressions[output_idx.GetIndex()], *projection.children[0], producer, cte_ref, key_map, success); } - auto origin = GetTableColumnOrigin(scope, output_idx.GetIndex(), true); + auto origin = ColumnOriginHelper::GetTableColumnOrigin(scope, output_idx.GetIndex(), true); if (!origin) { success = false; return nullptr; } for (auto &entry : key_map) { - if (SameOrigin(*origin, entry.first)) { + if (ColumnOriginHelper::SameOrigin(*origin, entry.first)) { origin = entry.second; break; } @@ -506,9 +511,10 @@ bool AggregateReuseOptimizer::TryReuseMaterializedAggregate(unique_ptrcte_columns[key_idx] >= producer_op.GetColumnBindings().size()) { return false; } - auto domain_key = GetTableColumnOrigin(producer_op, domain->cte_columns[key_idx], true); - auto group_key = GetTableColumnOrigin(*aggregate.children[0], *aggregate.groups[key_idx], true); - if (!domain_key || !group_key || !SameOrigin(*group_key, domain->core_keys[key_idx]) || + auto domain_key = ColumnOriginHelper::GetTableColumnOrigin(producer_op, domain->cte_columns[key_idx], true); + auto group_key = + ColumnOriginHelper::GetTableColumnOrigin(*aggregate.children[0], *aggregate.groups[key_idx], true); + if (!domain_key || !group_key || !ColumnOriginHelper::SameOrigin(*group_key, domain->core_keys[key_idx]) || &domain_key->table.get() != extra_source->GetTable().get()) { return false; } @@ -518,8 +524,10 @@ bool AggregateReuseOptimizer::TryReuseMaterializedAggregate(unique_ptrcore_keys[key_idx]) && SameOrigin(edge.right, *domain_key)) || - (SameOrigin(edge.right, domain->core_keys[key_idx]) && SameOrigin(edge.left, *domain_key))) { + if ((ColumnOriginHelper::SameOrigin(edge.left, domain->core_keys[key_idx]) && + ColumnOriginHelper::SameOrigin(edge.right, *domain_key)) || + (ColumnOriginHelper::SameOrigin(edge.right, domain->core_keys[key_idx]) && + ColumnOriginHelper::SameOrigin(edge.left, *domain_key))) { matched_cross = true; matched_cross_edges[edge_idx] = true; break; diff --git a/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp b/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp index 70ff51264..4fc997c9c 100644 --- a/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp +++ b/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp @@ -1142,9 +1142,7 @@ bool PartialAggregatePushdown::TryOwnerOuterCountPushdown(unique_ptrGetColumnStats(aggregate_key) : nullptr; - if (!aggregate_stats || !key_stats || - (key_stats->total_domain.source != DistinctCountSource::EXACT && - key_stats->total_domain.source != DistinctCountSource::HLL)) { + if (!aggregate_stats || !key_stats || !key_stats->total_domain.IsObserved()) { return false; } const auto aggregate_cardinality = aggregate_stats->cardinality; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_inner_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_inner_join.cpp index 58f6e0f58..5713cb4bc 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_inner_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_inner_join.cpp @@ -4,6 +4,7 @@ #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cross_product.hpp" #include "duckdb/planner/operator/logical_empty_result.hpp" +#include "duckdb/planner/subquery/column_binding_layout.hpp" namespace duckdb { @@ -54,7 +55,7 @@ unique_ptr FilterPushdown::PushdownInnerJoin(unique_ptrtype) { case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: case LogicalOperatorType::LOGICAL_ANY_JOIN: { @@ -65,12 +66,29 @@ unique_ptr FilterPushdown::PushdownInnerJoin(unique_ptrGetColumnBindings()); LogicalOperatorVisitor::RemapProjectionMap(result_join.right_projection_map, right_bindings_before, result_join.children[1]->GetColumnBindings()); - break; + return result; } default: break; } - return result; + if (!join.HasProjectionMap()) { + return result; + } + // Other replacements must expose the same columns in the same order as the original join. + auto projected_bindings = LogicalOperator::MapBindings(left_bindings_before, join.left_projection_map); + auto projected_right = LogicalOperator::MapBindings(right_bindings_before, join.right_projection_map); + projected_bindings.insert(projected_bindings.end(), projected_right.begin(), projected_right.end()); + auto result_bindings = result->GetColumnBindings(); + if (result_bindings == projected_bindings) { + return result; + } + auto projection_map = ColumnBindingLayout(std::move(result_bindings)).CreateProjectionMap(projected_bindings); + if (result->type == LogicalOperatorType::LOGICAL_EMPTY_RESULT) { + auto &empty = result->Cast(); + return make_uniq(LogicalOperator::MapTypes(empty.return_types, projection_map), + std::move(projected_bindings)); + } + return LogicalJoin::PromoteJoinSide(std::move(result), std::move(projection_map)); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp index 3ee732cc5..dc92bd231 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp @@ -35,6 +35,7 @@ optional RelationStatisticsHelper::SelectTotalDomain(const vector } break; case DistinctCountSource::CARDINALITY: + case DistinctCountSource::COMBINED: if (!fallback || domain.distinct_count < fallback->distinct_count) { fallback = domain; } @@ -427,7 +428,7 @@ RelationStatisticsHelper::EstimateTupleDomainRestriction(LogicalComparisonJoin & auto &input_column = input.columns[input_index.GetIndex()]; auto &key_column = keys.columns[key_index.GetIndex()]; auto total = SelectTotalDomain({input_column.total_domain, key_column.total_domain}); - if (!total || total->source == DistinctCountSource::CARDINALITY || total->distinct_count == 0) { + if (!total || !total->CanEstimateCoverage() || total->distinct_count == 0) { return {}; } auto supported = key_column.GetSupportedSemiAntiDomainSize(); diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp index 6b312282e..828139295 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp @@ -2,6 +2,7 @@ #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/multiply.hpp" +#include "duckdb/optimizer/column_origin.hpp" #include "duckdb/optimizer/join_order/join_predicate.hpp" #include "duckdb/planner/operator/list.hpp" @@ -94,8 +95,8 @@ static vector ExtractSemiAntiJoinDomains(LogicalComparisonJo has_residual = true; continue; } - // Row-count fallbacks bound domains but do not estimate membership coverage. - if (total_domain->source == DistinctCountSource::CARDINALITY) { + // Domain bounds alone do not estimate membership coverage. + if (!total_domain->CanEstimateCoverage()) { has_residual = true; } domains.push_back( @@ -280,6 +281,33 @@ static optional ExtractCrossProductStats(LogicalOperator &op, return ProjectChildStats(op, child_stats, cardinality, maximum); } +static optional +EstimateUnionColumn(const vector> &children, + const vector>> &child_origins, idx_t column_index, + ColumnBinding binding) { + DistinctCount total(0, DistinctCountSource::COMBINED); + DistinctCount current(0, DistinctCountSource::CARDINALITY); + for (idx_t child_index = 0; child_index < children.size(); child_index++) { + auto &column = children[child_index].get().columns[column_index]; + if (!column.total_domain.IsObserved()) { + return {}; + } + if (column_index >= child_origins[child_index].size()) { + return {}; + } + auto &origin = child_origins[child_index][column_index]; + // Filtered inputs do not describe complete populations, even when their NDV came from a native scan. + if (!origin || !origin->table.get().TryGetDuckTableEntry() || !origin->column.HasPrimaryIndex() || + origin->column.HasChildren() || origin->column.IsPushdownExtract()) { + return {}; + } + // The arms may share values. Use the largest input domain for unknown overlap. + total.distinct_count = MaxValue(total.distinct_count, column.total_domain.distinct_count); + current.distinct_count = MaxValue(current.distinct_count, column.current_domain.distinct_count); + } + return RelationColumnStats(binding, total, current, children[0].get().columns[column_index].name); +} + static optional ExtractSetOperationStats(LogicalSetOperation &setop, const vector> &child_stats) { if (child_stats.empty()) { @@ -319,18 +347,32 @@ static optional ExtractSetOperationStats(LogicalSetOperation &set return {}; } + vector>> child_origins; + if (setop.type == LogicalOperatorType::LOGICAL_UNION && child_stats.size() > 1) { + child_origins.reserve(child_stats.size()); + for (idx_t child_index = 0; child_index < child_stats.size(); child_index++) { + child_origins.push_back(ColumnOriginHelper::GetTableColumnOrigins(*setop.children[child_index])); + } + } + auto bindings = setop.GetColumnBindings(); for (idx_t column_idx = 0; column_idx < bindings.size(); column_idx++) { - if (column_idx >= child_stats[0].get().columns.size()) { - return {}; + for (auto &child : child_stats) { + if (column_idx >= child.get().columns.size()) { + return {}; + } + } + if (setop.type == LogicalOperatorType::LOGICAL_UNION && child_stats.size() > 1) { + auto column = EstimateUnionColumn(child_stats, child_origins, column_idx, bindings[column_idx]); + if (column) { + result.columns.push_back(std::move(*column)); + continue; + } } auto &first_column = child_stats[0].get().columns[column_idx]; auto total_domain = first_column.total_domain; auto current_domain = first_column.current_domain; for (idx_t child_idx = 1; child_idx < child_stats.size(); child_idx++) { - if (column_idx >= child_stats[child_idx].get().columns.size()) { - return {}; - } auto &child_column = child_stats[child_idx].get().columns[column_idx]; switch (setop.type) { case LogicalOperatorType::LOGICAL_UNION: diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp index 27ea0c190..0f1e5c8df 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp @@ -237,21 +237,29 @@ static FilterEstimate EstimateNullCheckRows(CardinalityValue cardinality, const } static FilterEstimate EstimateEqualityRows(CardinalityValue cardinality, ExpressionType type, - const RelationColumnStats &column) { + const RelationColumnStats &column, bool can_have_null) { const auto selectivity = RelationStatisticsHelper::DEFAULT_SELECTIVITY; bool equal = type == ExpressionType::COMPARE_EQUAL || type == ExpressionType::COMPARE_NOT_DISTINCT_FROM; if (cardinality == 0) { return {0, true}; } - if (column.total_domain.source == DistinctCountSource::CARDINALITY) { + if (!column.total_domain.CanEstimateCoverage()) { return {FilterFraction(cardinality, equal ? selectivity : 1 - selectivity), true}; } auto domain = MinValue(cardinality, column.current_domain.distinct_count); if (domain == 0) { return {cardinality, false}; } + CardinalityValue null_rows(0); + if (can_have_null && + (type == ExpressionType::COMPARE_DISTINCT_FROM || type == ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { + null_rows = cardinality * CardinalityValue(selectivity); + } auto fraction = MinValue(CardinalityValue(1), CardinalityValue(1) / domain); - auto rows = cardinality * (equal ? fraction : CardinalityValue(1) - fraction); + auto rows = (cardinality - null_rows) * (equal ? fraction : CardinalityValue(1) - fraction); + if (type == ExpressionType::COMPARE_DISTINCT_FROM) { + rows += null_rows; + } // Retain the existing equality-filter ceiling independently of fractional join estimates. // Do not inflate a fractional input or materialize a scaled estimate outside double's range. if (equal && rows > 1) { @@ -269,7 +277,8 @@ static FilterEstimate EstimateEqualityRows(CardinalityValue cardinality, Express static FilterEstimate EstimateComparisonRows(CardinalityValue cardinality, const BoundFunctionExpression &comparison, const RelationColumnStatsLookup &columns, const vector &positional_bindings, - FilterPropagateResult pruning, optional_ptr range) { + FilterPropagateResult pruning, optional_ptr range, + bool can_have_null) { const auto selectivity = RelationStatisticsHelper::DEFAULT_SELECTIVITY; auto &children = comparison.GetChildren(); auto type = comparison.GetExpressionType(); @@ -302,7 +311,7 @@ static FilterEstimate EstimateComparisonRows(CardinalityValue cardinality, const case ExpressionType::COMPARE_NOTEQUAL: case ExpressionType::COMPARE_DISTINCT_FROM: case ExpressionType::COMPARE_NOT_DISTINCT_FROM: - return EstimateEqualityRows(cardinality, type, *column); + return EstimateEqualityRows(cardinality, type, *column, can_have_null); case ExpressionType::COMPARE_LESSTHAN: case ExpressionType::COMPARE_LESSTHANOREQUALTO: case ExpressionType::COMPARE_GREATERTHAN: @@ -361,7 +370,7 @@ static FilterEstimate EstimateFilterRows(CardinalityValue cardinality, const Exp } if (BoundComparisonExpression::IsComparison(expr)) { return EstimateComparisonRows(cardinality, expr.Cast(), columns, positional_bindings, - pruning, range); + pruning, range, !scan_statistics || scan_statistics->CanHaveNull()); } return {cardinality, false}; } diff --git a/src/duckdb/src/parallel/pipeline.cpp b/src/duckdb/src/parallel/pipeline.cpp index 3a465ec84..c78c01946 100644 --- a/src/duckdb/src/parallel/pipeline.cpp +++ b/src/duckdb/src/parallel/pipeline.cpp @@ -467,6 +467,7 @@ void Pipeline::InvalidateOperatorStateForReschedule(ClientContext &client, Physi void Pipeline::ResetSourceForReschedule() { NotifyProgressReset(); + finished_operator = nullptr; if (source && !source->IsSource()) { throw InternalException("Source of pipeline does not have IsSource set"); } diff --git a/src/duckdb/src/parallel/pipeline_executor.cpp b/src/duckdb/src/parallel/pipeline_executor.cpp index 6e944d03c..5feac7df1 100644 --- a/src/duckdb/src/parallel/pipeline_executor.cpp +++ b/src/duckdb/src/parallel/pipeline_executor.cpp @@ -380,6 +380,17 @@ PipelineExecuteResult PipelineExecutor::Execute(idx_t max_chunks) { } else if (!exhausted_pipeline || next_batch_blocked) { SourceFetchResult source_result; if (!next_batch_blocked) { + auto finished_operator = pipeline.finished_operator.load(std::memory_order_relaxed); + if (finished_operator) { + for (idx_t i = 0; i < pipeline.operators.size(); i++) { + if (&pipeline.operators[i].get() == finished_operator.get()) { + // Preserve cached output downstream of the finishing operator. + FinishProcessing(NumericCast(i + 1)); + return FlushAndFinalize(chunk_budget); + } + } + throw InternalException("Finishing operator was not found in pipeline"); + } // "Regular" path: fetch a chunk from the source and push it through the pipeline source_chunk.Reset(); source_result = FetchFromSource(source_chunk); @@ -602,6 +613,7 @@ OperatorResultType PipelineExecutor::ExecutePushInternal(DataChunk &input, Execu if (sink_result == SinkResultType::BLOCKED) { return OperatorResultType::BLOCKED; } else if (sink_result == SinkResultType::FINISHED) { + // A finished sink stops only this task, e.g. PhysicalLimit counts rows per task FinishProcessing(); return OperatorResultType::FINISHED; } @@ -789,6 +801,8 @@ OperatorResultType PipelineExecutor::Execute(DataChunk &input, DataChunk &result } else if (result == OperatorResultType::FINISHED) { D_ASSERT(current_chunk.size() == 0); FinishProcessing(NumericCast(current_idx)); + // An intermediate operator that finished stops every task of the pipeline + pipeline.finished_operator.store(current_operator, std::memory_order_relaxed); return OperatorResultType::FINISHED; } current_chunk.Verify(context.client.db); diff --git a/src/duckdb/src/parallel/scan_read_ahead.cpp b/src/duckdb/src/parallel/scan_read_ahead.cpp index ce0f45b98..9d3e8a4b3 100644 --- a/src/duckdb/src/parallel/scan_read_ahead.cpp +++ b/src/duckdb/src/parallel/scan_read_ahead.cpp @@ -119,8 +119,8 @@ class ReadAheadIOTask : public BaseExecutorTask { } ~RunningRead() { if (read_ahead && read_ahead->running_reads.fetch_sub(1) == 1) { - // A parked consumer must retry even when the remaining reads have not started. - read_ahead->SignalProgress(false); + // Wake every parked scan, since a resumed task may stop without fetching again + read_ahead->SignalProgress(true); } } diff --git a/src/duckdb/src/storage/data_table.cpp b/src/duckdb/src/storage/data_table.cpp index 75420de48..ada1f09e9 100644 --- a/src/duckdb/src/storage/data_table.cpp +++ b/src/duckdb/src/storage/data_table.cpp @@ -1633,11 +1633,17 @@ void DataTable::Update(TableUpdateState &state, ClientContext &context, DuckTabl SelectionVector sel_local_update(count), sel_global_update(count); idx_t n_local_update = 0; idx_t n_global_update = 0; - for (auto row_id : row_ids.Values()) { - if (row_id.GetValue() >= MAX_ROW_ID) { - sel_local_update.set_index(n_local_update++, row_id.GetIndex()); + auto ids = row_ids.Values(); + for (idx_t i = 0; i < count; i++) { + auto row_id = ids[i].GetValue(); + if (i + 1 < count && ids[i + 1].GetValue() == row_id) { + // of adjacent entries for the same row only the last one is written, all of them were checked above + continue; + } + if (row_id >= MAX_ROW_ID) { + sel_local_update.set_index(n_local_update++, i); } else { - sel_global_update.set_index(n_global_update++, row_id.GetIndex()); + sel_global_update.set_index(n_global_update++, i); } } diff --git a/src/duckdb/src/storage/table/update_segment.cpp b/src/duckdb/src/storage/table/update_segment.cpp index f47c0d7da..d0be5bca5 100644 --- a/src/duckdb/src/storage/table/update_segment.cpp +++ b/src/duckdb/src/storage/table/update_segment.cpp @@ -1480,7 +1480,9 @@ static idx_t SortSelectionVector(SelectionVector &sel, idx_t count, row_t *ids) for (idx_t i = 0; i < count; i++) { sorted_sel.set_index(i, sel.get_index(i)); } - std::sort(sorted_sel.data(), sorted_sel.data() + count, [&](sel_t l, sel_t r) { return ids[l] < ids[r]; }); + // every column keeps the last entry of a repeated row id, so a row never mixes values of different entries + std::sort(sorted_sel.data(), sorted_sel.data() + count, + [&](sel_t l, sel_t r) { return ids[l] == ids[r] ? l > r : ids[l] < ids[r]; }); // eliminate any duplicates idx_t pos = 1; for (idx_t i = 1; i < count; i++) { diff --git a/src/duckdb/ub_src_optimizer.cpp b/src/duckdb/ub_src_optimizer.cpp index 947ef2223..c22328768 100644 --- a/src/duckdb/ub_src_optimizer.cpp +++ b/src/duckdb/ub_src_optimizer.cpp @@ -14,6 +14,8 @@ #include "src/optimizer/column_lifetime_analyzer.cpp" +#include "src/optimizer/column_origin.cpp" + #include "src/optimizer/common_aggregate_optimizer.cpp" #include "src/optimizer/common_subplan_optimizer.cpp" From b2ef778d37b225567d96d50e62b15e25971c26c8 Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Mon, 30 Nov 2026 14:42:49 +0000 Subject: [PATCH 7/8] Update vendored DuckDB sources to 17c33f61e20 --- ...nerated_extension_loader_package_build.cpp | 8 +- src/duckdb/src/execution/index/art/art.cpp | 4 +- .../src/execution/index/art/art_merger.cpp | 127 +++++++++++------- src/duckdb/src/execution/index/art/node.cpp | 4 - .../function/table/version/pragma_version.cpp | 6 +- .../function/window/window_value_function.cpp | 6 +- .../duckdb/execution/index/art/art_merger.hpp | 32 +++-- .../duckdb/execution/index/art/node.hpp | 2 - .../execution/index/art/node_handle.hpp | 9 +- .../src/include/duckdb/main/settings.hpp | 6 +- .../join_order/cardinality_estimator.hpp | 5 +- .../src/optimizer/column_binding_replacer.cpp | 14 +- .../join_order/cardinality_estimator.cpp | 45 +++++-- .../relation_statistics_helper.cpp | 8 ++ .../caching_file_system.cpp | 7 +- 15 files changed, 186 insertions(+), 97 deletions(-) diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index b2f66228b..ab8a37a47 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-alpha58348"; + descriptor->api_version = "v2.1.0-alpha58374"; 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-alpha58348"; + descriptor->api_version = "v2.1.0-alpha58374"; 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-alpha58348"; + descriptor->api_version = "v2.1.0-alpha58374"; 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-alpha58348"; + descriptor->api_version = "v2.1.0-alpha58374"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/execution/index/art/art.cpp b/src/duckdb/src/execution/index/art/art.cpp index feddfecbf..8a6807b81 100644 --- a/src/duckdb/src/execution/index/art/art.cpp +++ b/src/duckdb/src/execution/index/art/art.cpp @@ -1489,7 +1489,9 @@ bool ART::MergeIndexes(IndexLock &state, BoundIndex &source_index) { ArenaAllocator arena(Allocator::Get(db)); ARTMerger merger(arena, *this); merger.Init(root_ptr, other_art.root_ptr); - return merger.Merge() == ARTConflictType::NO_CONFLICT; + const auto conflict_type = merger.Merge(); + other_art.root_ptr.Clear(); + return conflict_type == ARTConflictType::NO_CONFLICT; } root_ptr = other_art.root_ptr; diff --git a/src/duckdb/src/execution/index/art/art_merger.cpp b/src/duckdb/src/execution/index/art/art_merger.cpp index 3b7ccd790..0d4b15669 100644 --- a/src/duckdb/src/execution/index/art/art_merger.cpp +++ b/src/duckdb/src/execution/index/art/art_merger.cpp @@ -13,8 +13,9 @@ namespace duckdb { -void ARTMerger::Init(NodePtr &left_ptr, NodePtr &right_ptr) { - Emplace(left_ptr, right_ptr, GateStatus::GATE_NOT_SET, 0); +void ARTMerger::Init(NodePtr &left_ptr, const NodePtr right_ptr) { + root_ptr = left_ptr; + Emplace(left_ptr, NodePtr(), 0, right_ptr, GateStatus::GATE_NOT_SET, 0); } ARTConflictType ARTMerger::Merge() { @@ -23,7 +24,11 @@ ARTConflictType ARTMerger::Merge() { auto entry = s.top(); s.pop(); - const auto left_type = entry.left_ptr.GetType(); + // Pin the location of the left NodePtr for this step. + auto left_ptr_handle = PinLeft(entry); + auto &left_ptr = left_ptr_handle.Get(); + + const auto left_type = left_ptr.GetType(); const auto right_type = entry.right_ptr.GetType(); // Early-out due to a constraint violation. @@ -37,13 +42,13 @@ ARTConflictType ARTMerger::Merge() { if (left_type == NType::LEAF_INLINED) { // Both left and right are inlined leaves. D_ASSERT(right_type == NType::LEAF_INLINED); - Leaf::MergeInlined(arena, art, entry.left_ptr, entry.right_ptr, entry.status, entry.depth); + Leaf::MergeInlined(arena, art, left_ptr, entry.right_ptr, entry.status, entry.depth); continue; } if (right_type == NType::LEAF_INLINED) { // Left is any node except LEAF_INLINED, right is LEAF_INLINED. - auto result = MergeNodeAndInlined(entry); + auto result = MergeNodeAndInlined(left_ptr, entry); if (result != ARTConflictType::NO_CONFLICT) { return result; } @@ -52,32 +57,33 @@ ARTConflictType ARTMerger::Merge() { if (entry.right_ptr.IsNestedLeaf()) { // Both left and right are nested leaves. - D_ASSERT(entry.left_ptr.IsNestedLeaf()); - MergeLeaves(entry); + D_ASSERT(left_ptr.IsNestedLeaf()); + MergeLeaves(left_ptr, entry); continue; } - if (entry.left_ptr.IsInternalNode() && entry.right_ptr.IsInternalNode()) { + if (left_ptr.IsInternalNode() && entry.right_ptr.IsInternalNode()) { // Both left and right are internal nodes. - MergeNodes(entry); + MergeNodes(left_ptr, entry); continue; } D_ASSERT(right_type == NType::PREFIX); if (left_type == NType::PREFIX) { // Both left and right are prefixes. - MergePrefixes(entry); + MergePrefixes(left_ptr, entry); continue; } // Left is a node, right is a PREFIX. - MergeNodeAndPrefix(entry.left_ptr, entry.right_ptr, entry.status, entry.depth); + MergeNodeAndPrefix(left_ptr, entry.right_ptr, entry.status, entry.depth); } // We exhausted the stack. return ARTConflictType::NO_CONFLICT; } -void ARTMerger::Emplace(NodePtr &left_ptr, NodePtr &right_ptr, const GateStatus parent_status, const idx_t depth) { +void ARTMerger::Emplace(NodePtr &left_ptr, const NodePtr left_parent_ptr, const uint8_t left_byte, NodePtr right_ptr, + const GateStatus parent_status, const idx_t depth) { const auto left_type = left_ptr.GetType(); const auto right_type = right_ptr.GetType(); @@ -91,23 +97,39 @@ void ARTMerger::Emplace(NodePtr &left_ptr, NodePtr &right_ptr, const GateStatus // When outside the gate, we propagate the parent_status (GATE_NOT_SET) and the depth. // When inside the gate, we already reset the depth, and we propagate the parent_status (GATE_SET). if (left_ptr.GetGateStatus() == GateStatus::GATE_NOT_SET) { - s.emplace(left_ptr, right_ptr, parent_status, depth); + s.emplace(left_parent_ptr, left_byte, right_ptr, parent_status, depth); return; } // Enter a gate. // Reset the depth. D_ASSERT(parent_status == GateStatus::GATE_NOT_SET); - s.emplace(left_ptr, right_ptr, GateStatus::GATE_SET, 0); + s.emplace(left_parent_ptr, left_byte, right_ptr, GateStatus::GATE_SET, 0); +} + +NodePtrHandle ARTMerger::PinLeft(const NodeEntry &entry) { + if (!entry.left_parent_ptr.HasMetadata()) { + return NodePtrHandle::Unpinned(*root_ptr); + } + NodeHandle parent_handle(art, entry.left_parent_ptr); + if (entry.left_parent_ptr.GetType() == NType::PREFIX) { + return NodePtrHandle::PrefixChild(art, std::move(parent_handle)); + } + D_ASSERT(entry.left_parent_ptr.IsInternalNode()); + auto child_ptr_handle = NodePtrHandle::Child(std::move(parent_handle), entry.left_byte); + if (!child_ptr_handle) { + throw InternalException("ARTMerger: no child at byte %d of the parent of a stack entry", entry.left_byte); + } + return std::move(*child_ptr_handle); } -ARTConflictType ARTMerger::MergeNodeAndInlined(NodeEntry &entry) { +ARTConflictType ARTMerger::MergeNodeAndInlined(NodePtr &left_ptr, NodeEntry &entry) { D_ASSERT(entry.right_ptr.GetType() == NType::LEAF_INLINED); D_ASSERT(entry.status == GateStatus::GATE_SET); // We fall back to the ART insertion code. auto row_id_key = ARTKey::CreateARTKey(arena, entry.right_ptr.GetRowId()); - return ARTOperator::Insert(arena, art, entry.left_ptr, row_id_key, entry.depth, row_id_key, GateStatus::GATE_SET, + return ARTOperator::Insert(arena, art, left_ptr, row_id_key, entry.depth, row_id_key, GateStatus::GATE_SET, DeleteIndexInfo(), IndexAppendMode::DEFAULT); } @@ -125,15 +147,15 @@ array_ptr ARTMerger::GetBytes(NodePtr &leaf_ptr) { } } -void ARTMerger::MergeLeaves(NodeEntry &entry) { - D_ASSERT(entry.left_ptr.IsNestedLeaf()); +void ARTMerger::MergeLeaves(NodePtr &left_ptr, NodeEntry &entry) { + D_ASSERT(left_ptr.IsNestedLeaf()); D_ASSERT(entry.right_ptr.IsNestedLeaf()); - D_ASSERT(entry.left_ptr.GetGateStatus() == GateStatus::GATE_NOT_SET); + D_ASSERT(left_ptr.GetGateStatus() == GateStatus::GATE_NOT_SET); D_ASSERT(entry.right_ptr.GetGateStatus() == GateStatus::GATE_NOT_SET); // Merge the smaller leaf into the bigger leaf. - if (entry.left_ptr.GetType() < entry.right_ptr.GetType()) { - swap(entry.left_ptr, entry.right_ptr); + if (left_ptr.GetType() < entry.right_ptr.GetType()) { + swap(left_ptr, entry.right_ptr); } // Get the bytes of the right node. @@ -143,7 +165,7 @@ void ARTMerger::MergeLeaves(NodeEntry &entry) { // FIXME: Obtain a reference to left once and // FIXME: handle the different node type combinations. for (idx_t i = 0; i < bytes.size(); i++) { - NodePtr::InsertChild(art, entry.left_ptr, bytes[i]); + NodePtr::InsertChild(art, left_ptr, bytes[i]); } NodePtr::FreeNode(art, entry.right_ptr); } @@ -164,13 +186,13 @@ NodeChildren ARTMerger::ExtractChildren(NodePtr &node_ptr) { } } -void ARTMerger::MergeNodes(NodeEntry &entry) { - D_ASSERT(entry.left_ptr.IsInternalNode()); +void ARTMerger::MergeNodes(NodePtr &left_ptr, NodeEntry &entry) { + D_ASSERT(left_ptr.IsInternalNode()); D_ASSERT(entry.right_ptr.IsInternalNode()); // Merge the smaller node into the bigger node. - if (entry.left_ptr.GetType() < entry.right_ptr.GetType()) { - swap(entry.left_ptr, entry.right_ptr); + if (left_ptr.GetType() < entry.right_ptr.GetType()) { + swap(left_ptr, entry.right_ptr); } // Get the children of the right node. @@ -185,13 +207,11 @@ void ARTMerger::MergeNodes(NodeEntry &entry) { vector remaining; for (idx_t i = 0; i < children.bytes.size(); i++) { const auto byte = children.bytes[i]; - auto child_ptr_ref = entry.left_ptr.GetChildMutableUnsafe(art, byte); - - if (!child_ptr_ref) { + if (!left_ptr.GetChildNode(art, byte)) { // There is no child at this byte. // We can insert the right node's child at byte and are done. auto &right_child_ptr = children.children[i]; - NodePtr::InsertChild(art, entry.left_ptr, byte, right_child_ptr); + NodePtr::InsertChild(art, left_ptr, byte, right_child_ptr); continue; } // There is a left and a right child at this byte. @@ -200,11 +220,14 @@ void ARTMerger::MergeNodes(NodeEntry &entry) { } // Emplace all remaining children. + // The node no longer grows, so the entries can store it as their parent. + NodeHandle node_handle(art, left_ptr); for (idx_t i = 0; i < remaining.size(); i++) { const auto byte = children.bytes[remaining[i]]; - auto &right_child_ptr = children.children[remaining[i]]; - auto child_ptr_ref = entry.left_ptr.GetChildMutableUnsafe(art, byte); - Emplace(*child_ptr_ref, right_child_ptr, entry.status, entry.depth + 1); + auto right_child_ptr = children.children[remaining[i]]; + auto child_ptr = NodePtr::GetChildMutable(node_handle, byte); + D_ASSERT(child_ptr); + Emplace(*child_ptr, left_ptr, byte, right_child_ptr, entry.status, entry.depth + 1); } } @@ -213,17 +236,20 @@ void ARTMerger::MergeNodeAndPrefix(NodePtr &node_ptr, NodePtr &prefix_ptr, const D_ASSERT(node_ptr.IsInternalNode()); D_ASSERT(prefix_ptr.GetType() == NType::PREFIX); - // Get the child at the prefix byte, or nullptr, if there is no child. const auto byte = Prefix::GetByte(art, prefix_ptr, pos); - auto child_ptr_ref = node_ptr.GetChildMutableUnsafe(art, byte); - // Reduce the prefix to the bytes after pos. Prefix::Reduce(art, prefix_ptr, pos); - if (child_ptr_ref) { - // Iterate on the child and the remaining prefix. - Emplace(*child_ptr_ref, prefix_ptr, parent_status, parent_depth + 1); - return; + { + // Get the child at the prefix byte, or nullptr, if there is no child. + NodeHandle node_handle(art, node_ptr); + auto child_ptr = NodePtr::GetChildMutable(node_handle, byte); + if (child_ptr) { + // Iterate on the child and the remaining prefix. + // The node does not grow, so the entry can store it as its parent. + Emplace(*child_ptr, node_ptr, byte, prefix_ptr, parent_status, parent_depth + 1); + return; + } } // There is no child at this prefix byte, @@ -240,8 +266,8 @@ void ARTMerger::MergeNodeAndPrefix(NodePtr &node_ptr, NodePtr &prefix_ptr, const MergeNodeAndPrefix(node_ptr, prefix_ptr, parent_status, parent_depth, 0); } -void ARTMerger::MergePrefixes(NodeEntry &entry) { - D_ASSERT(entry.left_ptr.GetType() == NType::PREFIX); +void ARTMerger::MergePrefixes(NodePtr &left_ptr, NodeEntry &entry) { + D_ASSERT(left_ptr.GetType() == NType::PREFIX); D_ASSERT(entry.right_ptr.GetType() == NType::PREFIX); // We traverse prefixes until we @@ -255,7 +281,7 @@ void ARTMerger::MergePrefixes(NodeEntry &entry) { // the prefixes are the same. That means, we only need to keep // one of them around. - Prefix l_prefix(art, entry.left_ptr, true); + Prefix l_prefix(art, left_ptr, true); Prefix r_prefix(art, entry.right_ptr, true); const auto count = art.PrefixCount(); @@ -276,13 +302,13 @@ void ARTMerger::MergePrefixes(NodeEntry &entry) { // Then, we insert both remainders into a new Node4. // Then, we are done. const auto split_pos = UnsafeNumericCast(pos.GetIndex()); - const auto l_byte = Prefix::GetByte(art, entry.left_ptr, split_pos); + const auto l_byte = Prefix::GetByte(art, left_ptr, split_pos); const auto r_byte = Prefix::GetByte(art, entry.right_ptr, split_pos); // Split and reduce. NodePtr branching_node4_ptr; Node4::New(art, branching_node4_ptr); - auto l_child_ptr = PrefixHandle::Split(art, entry.left_ptr, branching_node4_ptr, split_pos); + auto l_child_ptr = PrefixHandle::Split(art, left_ptr, branching_node4_ptr, split_pos); Prefix::Reduce(art, entry.right_ptr, split_pos); Node4::InsertChild(art, branching_node4_ptr, l_byte, l_child_ptr); @@ -300,7 +326,8 @@ void ARTMerger::MergePrefixes(NodeEntry &entry) { entry.right_ptr = r_child_ptr; auto depth = entry.depth + l_prefix.data[count]; - Emplace(*l_prefix.child_slot, entry.right_ptr, entry.status, depth); + auto l_child_ptr_handle = NodePtrHandle::PrefixChild(art, NodeHandle(art, left_ptr)); + Emplace(l_child_ptr_handle.Get(), left_ptr, 0, entry.right_ptr, entry.status, depth); return; } @@ -308,13 +335,15 @@ void ARTMerger::MergePrefixes(NodeEntry &entry) { if (r_prefix.data[count] == max_count) { // We exhausted the right prefix. // Ensure that we continue merging into left. - swap(entry.left_ptr, entry.right_ptr); - MergeNodeAndPrefix(*r_prefix.child_slot, entry.right_ptr, entry.status, entry.depth + max_count, max_count); + swap(left_ptr, entry.right_ptr); + auto r_child_ptr_handle = NodePtrHandle::PrefixChild(art, NodeHandle(art, left_ptr)); + MergeNodeAndPrefix(r_child_ptr_handle.Get(), entry.right_ptr, entry.status, entry.depth + max_count, max_count); return; } // We exhausted the left prefix. - MergeNodeAndPrefix(*l_prefix.child_slot, entry.right_ptr, entry.status, entry.depth + max_count, max_count); + auto l_child_ptr_handle = NodePtrHandle::PrefixChild(art, NodeHandle(art, left_ptr)); + MergeNodeAndPrefix(l_child_ptr_handle.Get(), entry.right_ptr, entry.status, entry.depth + max_count, max_count); } } // namespace duckdb diff --git a/src/duckdb/src/execution/index/art/node.cpp b/src/duckdb/src/execution/index/art/node.cpp index 298976a96..5c815de70 100644 --- a/src/duckdb/src/execution/index/art/node.cpp +++ b/src/duckdb/src/execution/index/art/node.cpp @@ -230,10 +230,6 @@ const unsafe_optional_ptr NodePtr::GetChild(ART &art, const uint8_t byt return GetChildInternal(art, *this, byte, false); } -unsafe_optional_ptr NodePtr::GetChildMutableUnsafe(ART &art, const uint8_t byte) const { - return GetChildInternal(art, *this, byte, false); -} - OptionalNodePtr NodePtr::GetChildNode(const ART &art, const uint8_t byte) const { D_ASSERT(HasMetadata()); auto type = GetType(); diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index b171f5bd4..dc843998a 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-alpha58348" +#define DUCKDB_PATCH_VERSION "0-alpha58374" #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-alpha58348" +#define DUCKDB_VERSION "v2.1.0-alpha58374" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "a044966347" +#define DUCKDB_SOURCE_ID "17c33f61e2" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/function/window/window_value_function.cpp b/src/duckdb/src/function/window/window_value_function.cpp index 48fc16883..4d7048736 100644 --- a/src/duckdb/src/function/window/window_value_function.cpp +++ b/src/duckdb/src/function/window/window_value_function.cpp @@ -710,7 +710,11 @@ void WindowLeadLagExecutor::GetData(ExecutionContext &context, DataChunk &eval_c // (4) evaluate the expression provided to LEAD/LAG on this row. if (nth_index.second) { // Overflow - FlatVector::SetNull(result, i, true); + if (has_default) { + leadlag_default.CopyCell(result, i); + } else { + FlatVector::SetNull(result, i, true); + } } else { cursor.CopyCell(0, nth_index.first, result, i); } diff --git a/src/duckdb/src/include/duckdb/execution/index/art/art_merger.hpp b/src/duckdb/src/include/duckdb/execution/index/art/art_merger.hpp index e30b3cdd3..b827305cd 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/art_merger.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/art_merger.hpp @@ -10,6 +10,7 @@ #include "duckdb/common/stack.hpp" #include "duckdb/execution/index/art/art.hpp" +#include "duckdb/execution/index/art/node_handle.hpp" namespace duckdb { @@ -26,7 +27,7 @@ class ARTMerger { public: //! Init the merge by setting the initial nodes. - void Init(NodePtr &left_ptr, NodePtr &right_ptr); + void Init(NodePtr &left_ptr, const NodePtr right_ptr); //! Merge until (1) triggering constraint violation or (2) all nodes have been processed. ARTConflictType Merge(); @@ -35,13 +36,18 @@ class ARTMerger { //! The ARTMerger always merges into the left node. //! If inside a gate, status is always GATE_SET, otherwise, it is GATE_NOT_SET. //! The depth resets when entering a gate. + //! The left NodePtr is stored as its location: the child at left_byte of the inner node left_parent_ptr, + //! the child of the prefix left_parent_ptr, or the root, if left_parent_ptr is empty. struct NodeEntry { NodeEntry() = delete; - NodeEntry(NodePtr &left_ptr, NodePtr &right_ptr, const GateStatus status, const idx_t depth) - : left_ptr(left_ptr), right_ptr(right_ptr), status(status), depth(depth) {}; + NodeEntry(const NodePtr left_parent_ptr, const uint8_t left_byte, const NodePtr right_ptr, + const GateStatus status, const idx_t depth) + : left_parent_ptr(left_parent_ptr), left_byte(left_byte), right_ptr(right_ptr), status(status), + depth(depth) {}; - NodePtr &left_ptr; - NodePtr &right_ptr; + NodePtr left_parent_ptr; + uint8_t left_byte; + NodePtr right_ptr; GateStatus status; idx_t depth; }; @@ -50,6 +56,8 @@ class ARTMerger { ArenaAllocator &arena; //! The ART holding the node memory. ART &art; + //! The root of the ART merged into. + optional_ptr root_ptr; //! The stack. While merging, NodeEntry elements are pushed onto of the stack. stack s; @@ -57,15 +65,19 @@ class ARTMerger { // When pushing anything on the stack, we ensure that: // - if left is LEAF_INLINED, then right is also LEAF_INLINED. // - if left is PREFIX, then right is also PREFIX (except for PREFIX + LEAF_INLINED). - void Emplace(NodePtr &left_ptr, NodePtr &right_ptr, const GateStatus parent_status, const idx_t depth); + // left_parent_ptr is the node that contains left_ptr. The caller keeps it pinned. + void Emplace(NodePtr &left_ptr, const NodePtr left_parent_ptr, const uint8_t left_byte, NodePtr right_ptr, + const GateStatus parent_status, const idx_t depth); + //! Pins the location of the entry's left NodePtr. + NodePtrHandle PinLeft(const NodeEntry &entry); - ARTConflictType MergeNodeAndInlined(NodeEntry &entry); + ARTConflictType MergeNodeAndInlined(NodePtr &left_ptr, NodeEntry &entry); array_ptr GetBytes(NodePtr &leaf_ptr); - void MergeLeaves(NodeEntry &entry); + void MergeLeaves(NodePtr &left_ptr, NodeEntry &entry); NodeChildren ExtractChildren(NodePtr &node_ptr); - void MergeNodes(NodeEntry &entry); + void MergeNodes(NodePtr &left_ptr, NodeEntry &entry); //! Merges a node and a prefix. //! pos determines up to which position we need to reduce the prefix. @@ -75,7 +87,7 @@ class ARTMerger { const idx_t parent_depth, const uint8_t pos); void MergeNodeAndPrefix(NodePtr &node_ptr, NodePtr &prefix_ptr, const GateStatus parent_status, const idx_t parent_depth); - void MergePrefixes(NodeEntry &entry); + void MergePrefixes(NodePtr &left_ptr, NodeEntry &entry); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/index/art/node.hpp b/src/duckdb/src/include/duckdb/execution/index/art/node.hpp index a2f50304d..d8ec1ca36 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/node.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/node.hpp @@ -163,8 +163,6 @@ class NodePtr : public IndexPointer { OptionalNodePtr GetNextChildNode(const ART &art, uint8_t &byte) const; //! Get the immutable child at byte. const unsafe_optional_ptr GetChild(ART &art, const uint8_t byte) const; - //! Get the child at byte. - unsafe_optional_ptr GetChildMutableUnsafe(ART &art, const uint8_t byte) const; //! Get the first immutable child greater than or equal to the byte. const unsafe_optional_ptr GetNextChild(ART &art, uint8_t &byte) const; //! Returns true, if the byte exists, else false. diff --git a/src/duckdb/src/include/duckdb/execution/index/art/node_handle.hpp b/src/duckdb/src/include/duckdb/execution/index/art/node_handle.hpp index 4fa9e7a6a..aa38b535e 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/node_handle.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/node_handle.hpp @@ -88,11 +88,14 @@ class ConstNodeHandle { //! NodePtrHandle refers to a mutable NodePtr and owns the pin on the node storing it. //! NodeHandle pins the node that a NodePtr points to; NodePtrHandle pins the node that contains the NodePtr. -//! Use it only to pass a NodePtr to a callee that may free the node storing it, as in Delete: the callee releases -//! the pin before that free. Otherwise, keep a NodeHandle in scope and use a NodePtr reference, as Insert does. -//! Only ARTOperator can create an unpinned NodePtrHandle, for a NodePtr that no node stores, e.g., the ART root. +//! Use it to pass a NodePtr to a callee that may free the node storing it, as in Delete: the callee releases +//! the pin before that free. ARTMerger uses it to pin the node that contains the left NodePtr of a merge step. +//! Otherwise, keep a NodeHandle in scope and use a NodePtr reference, as Insert does. +//! Only ARTOperator and ARTMerger can create an unpinned NodePtrHandle, for a NodePtr that no node stores, +//! e.g., the ART root. class NodePtrHandle { friend class ARTOperator; + friend class ARTMerger; public: NodePtrHandle(const NodePtrHandle &) = delete; diff --git a/src/duckdb/src/include/duckdb/main/settings.hpp b/src/duckdb/src/include/duckdb/main/settings.hpp index cf61992d1..af32e289a 100644 --- a/src/duckdb/src/include/duckdb/main/settings.hpp +++ b/src/duckdb/src/include/duckdb/main/settings.hpp @@ -1819,9 +1819,9 @@ struct ExternalFileCacheRequestSizingSetting { using RETURN_TYPE = ExternalFileCacheRequestSizing; static constexpr const char *Name = "external_file_cache_request_sizing"; static constexpr const char *Description = - "How reads of cached files are sized: AUTO lets each reader choose, GRID reads the aligned blocks of the cache " - "block size around each read, EXACT reads exactly the requested bytes. Reads of files that are not cached are " - "always exact."; + "How external file reads are sized: AUTO lets each reader choose, GRID aligns cached reads to cache block " + "boundaries, and EXACT uses reader-sized ranges. When the external file cache is disabled, EXACT also skips " + "splitting reads at the cache block size."; static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp index 7e90a1f6d..272fcef2a 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp @@ -48,7 +48,10 @@ class CardinalityEstimator { optional_ptr FindBoundary(JoinRelationSet &set, optional_ptr ®ion); optional ProjectColumn(JoinRelationSet &set, ColumnBinding binding); SemiAntiJoinCardinalityEstimate EstimateMembership(const LogicalJoinStats &boundary, JoinRelationSet &left, - JoinRelationSet &right, vector &domains); + JoinRelationSet &right, JoinType join_type, + vector &domains); + CardinalityValue EstimateLeftJoinCardinality(const LogicalJoinStats &boundary, JoinRelationSet &left, + JoinRelationSet &right); void InitEquivalentRelations(); void UpdateTotalDomains(RelationIndex relation, const RelationStats &stats, const join_column_sources_t &sources); void RestrictFilterDomains(const vector &relation_stats); diff --git a/src/duckdb/src/optimizer/column_binding_replacer.cpp b/src/duckdb/src/optimizer/column_binding_replacer.cpp index 64fe81d1e..630a71a54 100644 --- a/src/duckdb/src/optimizer/column_binding_replacer.cpp +++ b/src/duckdb/src/optimizer/column_binding_replacer.cpp @@ -389,9 +389,8 @@ BindingReplacementGraph BindingReplacementGraph::ScopedToBoundary(const vector ScopeToOutput(const vector &new_output, +static vector ScopeToOutput(const column_binding_set_t &new_bindings, const BindingReplacementGraph &replacements) { - column_binding_set_t new_bindings(new_output.begin(), new_output.end()); vector result; for (auto &replacement : replacements) { if (new_bindings.find(replacement.old_binding) != new_bindings.end()) { @@ -452,9 +451,18 @@ void ColumnBindingRewrite::ApplyToChild(unique_ptr &op, idx_t c if (child_index >= op->children.size()) { throw InternalException("Binding rewrite child index %llu out of range", child_index); } + if (replacements.Empty()) { + if (op->HasProjectionMap()) { + auto projection_map = LogicalOperatorVisitor::GetProjectionMap(*op, child_index); + D_ASSERT(projection_map); + RemapProjectionMapStrict(*projection_map, old_child_bindings, + op->children[child_index]->GetColumnBindings()); + } + return; + } auto new_child_bindings = op->children[child_index]->GetColumnBindings(); - auto boundary_replacements = ScopeToOutput(new_child_bindings, replacements); column_binding_set_t new_bindings(new_child_bindings.begin(), new_child_bindings.end()); + auto boundary_replacements = ScopeToOutput(new_bindings, replacements); CorrelatedColumnBindingReplacer replacer; replacer.replacement_bindings = std::move(boundary_replacements); replacer.BuildIndex(); diff --git a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp index 2124a0d51..78901ff79 100644 --- a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp +++ b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp @@ -1009,18 +1009,28 @@ static bool ContainsBinding(const JoinRelationSet &set, ColumnBinding binding) { SemiAntiJoinCardinalityEstimate CardinalityEstimator::EstimateMembership(const LogicalJoinStats &boundary, JoinRelationSet &left, JoinRelationSet &right, + JoinType join_type, vector &domains) { auto has_residual = boundary.has_residual; for (auto &key : boundary.equality_keys) { - auto lhs = ProjectColumn(left, key.first); auto rhs = ProjectColumn(right, key.second); - if (!lhs || !rhs) { + if (!rhs) { has_residual = true; continue; } auto supported = rhs->GetSupportedSemiAntiDomainSize(); + if (!supported) { + has_residual = true; + continue; + } + // Avoid projecting the preserved input when the build side cannot estimate membership. + auto lhs = ProjectColumn(left, key.first); + if (!lhs) { + has_residual = true; + continue; + } auto total = RelationStatisticsHelper::SelectTotalDomain({lhs->total_domain, rhs->total_domain}); - if (!supported || !total || total->distinct_count.IsZero()) { + if (!total || total->distinct_count.IsZero()) { has_residual = true; continue; } @@ -1030,11 +1040,24 @@ SemiAntiJoinCardinalityEstimate CardinalityEstimator::EstimateMembership(const L } domains.push_back({total->distinct_count, *supported, key.first, key.second}); } - auto type = boundary.op.get().type == JoinOrderOperatorType::SEMI ? JoinType::SEMI : JoinType::ANTI; auto &left_stats = state->cardinalities.at(left); auto &right_stats = state->cardinalities.at(right); return RelationStatisticsHelper::EstimateSemiAntiJoinCardinality( - left_stats.cardinality, right_stats.cardinality, right_stats.row_retention, type, domains, has_residual); + left_stats.cardinality, right_stats.cardinality, right_stats.row_retention, join_type, domains, has_residual); +} + +CardinalityValue CardinalityEstimator::EstimateLeftJoinCardinality(const LogicalJoinStats &boundary, + JoinRelationSet &left, JoinRelationSet &right) { + auto left_rows = state->cardinalities.at(left).cardinality; + auto inner_rows = left_rows * state->cardinalities.at(right).cardinality * boundary.selectivity; + if (boundary.has_residual || boundary.equality_keys.empty()) { + return MaxValue(left_rows, inner_rows); + } + vector domains; + auto unmatched = EstimateMembership(boundary, left, right, JoinType::ANTI, domains); + // Matching pairs and unmatched preserved rows both contribute to a LEFT join. + auto result = unmatched.used_domain_evidence ? inner_rows + unmatched.cardinality : inner_rows; + return MaxValue(left_rows, result); } CardinalityValue CardinalityEstimator::EstimateCardinality(JoinRelationSet &set) { @@ -1067,9 +1090,9 @@ CardinalityValue CardinalityEstimator::EstimateCardinality(JoinRelationSet &set) auto &right = set_manager.Intersection(set, op.right_relations); D_ASSERT(!left.Empty() && !right.Empty() && left.count < set.count && right.count < set.count); auto left_rows = EstimateCardinality(left); - auto right_rows = EstimateCardinality(right); + EstimateCardinality(right); if (op.type == JoinOrderOperatorType::LEFT) { - result = MaxValue(left_rows, left_rows * right_rows * boundary->selectivity); + result = EstimateLeftJoinCardinality(*boundary, left, right); maximum = RelationStatisticsHelper::JoinCardinalityBound( JoinType::LEFT, state->cardinalities.at(left).maximum, state->cardinalities.at(right).maximum); } else if (op.type == JoinOrderOperatorType::MARK) { @@ -1079,7 +1102,7 @@ CardinalityValue CardinalityEstimator::EstimateCardinality(JoinRelationSet &set) } else { auto type = op.type == JoinOrderOperatorType::SEMI ? JoinType::SEMI : JoinType::ANTI; vector domains; - result = EstimateMembership(*boundary, left, right, domains).cardinality; + result = EstimateMembership(*boundary, left, right, type, domains).cardinality; maximum = RelationStatisticsHelper::JoinCardinalityBound(type, state->cardinalities.at(left).maximum, state->cardinalities.at(right).maximum); retention = left_rows.IsZero() ? CardinalityValue(0) @@ -1188,14 +1211,14 @@ optional CardinalityEstimator::ColumnProjection::ProjectInp auto left_rows = estimator.state->cardinalities.at(left).cardinality; CardinalityValue join_rows; if (op.type == JoinOrderOperatorType::LEFT) { - join_rows = MaxValue(left_rows, - left_rows * estimator.state->cardinalities.at(right).cardinality * boundary->selectivity); + join_rows = estimator.EstimateLeftJoinCardinality(*boundary, left, right); result->semi_anti_join_domain_evidence.Invalidate(); } else if (op.type == JoinOrderOperatorType::MARK) { join_rows = left_rows; } else { vector domains; - auto estimate = estimator.EstimateMembership(*boundary, left, right, domains); + auto type = op.type == JoinOrderOperatorType::SEMI ? JoinType::SEMI : JoinType::ANTI; + auto estimate = estimator.EstimateMembership(*boundary, left, right, type, domains); join_rows = estimate.cardinality; result->current_domain = RelationStatisticsHelper::EstimateCurrentDomain(result->current_domain, left_rows, join_rows); diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp index dc92bd231..5e78d33cb 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp @@ -811,6 +811,14 @@ optional RelationStatisticsHelper::ExtractLimitStats(LogicalLimit default: break; } + // LIMIT also bounds existing membership support; it does not establish coverage for other columns. + if (result->max_cardinality.IsValid()) { + for (auto &column : result->columns) { + if (column.semi_anti_join_domain_evidence.GetDomainBound().IsValid()) { + column.semi_anti_join_domain_evidence.TightenDomainBound(result->max_cardinality.GetIndex()); + } + } + } ApplyCardinality(*result, cardinality); return result; } diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp index ad4e004de..4977e9c88 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp @@ -514,12 +514,15 @@ void CachingFileHandle::ReadUncached(data_ptr_t buffer, idx_t nr_bytes, idx_t lo auto &scheduler = TaskScheduler::GetScheduler(db); // idle worker threads also run async tasks, so the pieces are only sure to run serially without any other thread const bool single_threaded = scheduler.NumberOfThreads() <= 1 && scheduler.NumberOfAsyncThreads() == 0; + const bool exact_uncached = + !external_file_cache.IsEnabled() && + Settings::Get(db) == ExternalFileCacheRequestSizing::EXACT; if (nr_bytes <= max_block_size || !external_file_cache.ShouldCacheFile(path.path) || !CanSeek() || - single_threaded) { + single_threaded || exact_uncached) { ReadAndRecord(context, buffer, nr_bytes, location); return; } - // split like cached reads, so the requests are the same whether or not the cache is enabled + // Split at the same block size as cached reads. TaskExecutor executor(scheduler, TaskSchedulerType::ASYNC); for (idx_t offset = 0; offset < nr_bytes; offset += max_block_size) { executor.ScheduleTask(make_uniq(*this, executor, context, buffer + offset, From c4c797d444c4d8681418c537405095acf195ecf8 Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Tue, 1 Dec 2026 09:22:27 +0000 Subject: [PATCH 8/8] C API v2 changes fixes --- duckdb_java.def | 65 ------------------------ duckdb_java.exp | 65 ------------------------ duckdb_java.map | 65 ------------------------ src/jni/bindings_table_function.cpp | 44 +++++++++------- src/jni/bindings_table_function.hpp | 8 +-- src/jni/bindings_table_function_init.cpp | 18 +++---- src/jni/capi_v2.hpp | 1 + src/jni/config.cpp | 43 +++++++++++----- src/jni/config.hpp | 15 +++++- src/jni/duckdb_java.cpp | 9 +++- 10 files changed, 91 insertions(+), 242 deletions(-) diff --git a/duckdb_java.def b/duckdb_java.def index 9ad70e84e..b335ddbe4 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -880,28 +880,7 @@ duckdb_v2_copy_from_bind_get_option_value duckdb_v2_copy_from_bind_get_user_data duckdb_v2_copy_from_bind_set_bind_data duckdb_v2_copy_from_bind_set_cardinality -duckdb_v2_copy_from_exec_get_bind_data -duckdb_v2_copy_from_exec_get_global_state -duckdb_v2_copy_from_exec_get_local_state -duckdb_v2_copy_from_exec_get_output_chunk -duckdb_v2_copy_from_exec_get_user_data -duckdb_v2_copy_from_init_global_get_bind_data -duckdb_v2_copy_from_init_global_get_user_data -duckdb_v2_copy_from_init_global_set_global_state -duckdb_v2_copy_from_init_global_set_max_threads -duckdb_v2_copy_from_init_local_get_bind_data -duckdb_v2_copy_from_init_local_get_global_state -duckdb_v2_copy_from_init_local_get_user_data -duckdb_v2_copy_from_init_local_set_local_state -duckdb_v2_copy_from_progress_get_bind_data -duckdb_v2_copy_from_progress_get_global_state -duckdb_v2_copy_from_progress_get_user_data -duckdb_v2_copy_from_progress_set_progress duckdb_v2_copy_from_set_bind_callback -duckdb_v2_copy_from_set_exec_callback -duckdb_v2_copy_from_set_init_global_callback -duckdb_v2_copy_from_set_init_local_callback -duckdb_v2_copy_from_set_progress_callback duckdb_v2_copy_function_create duckdb_v2_copy_function_destroy duckdb_v2_copy_function_set_file_extension @@ -1192,20 +1171,8 @@ duckdb_v2_table_description_is_readonly duckdb_v2_table_function_bind_add_result_column duckdb_v2_table_function_bind_set_cardinality duckdb_v2_table_function_bind_set_order_preservation -duckdb_v2_table_function_claim_batch_get_bind_data -duckdb_v2_table_function_claim_batch_get_global_state -duckdb_v2_table_function_claim_batch_get_local_state -duckdb_v2_table_function_claim_batch_get_user_data -duckdb_v2_table_function_claim_batch_set_claimed duckdb_v2_table_function_create duckdb_v2_table_function_destroy -duckdb_v2_table_function_exec_get_bind_data -duckdb_v2_table_function_exec_get_column_count -duckdb_v2_table_function_exec_get_column_index -duckdb_v2_table_function_exec_get_global_state -duckdb_v2_table_function_exec_get_local_state -duckdb_v2_table_function_exec_get_output_chunk -duckdb_v2_table_function_exec_get_user_data duckdb_v2_table_function_filter_pushdown_accept duckdb_v2_table_function_filter_pushdown_get_bind_data duckdb_v2_table_function_filter_pushdown_get_column_count @@ -1219,48 +1186,16 @@ duckdb_v2_table_function_get_bind_info_set_column_identifier duckdb_v2_table_function_get_bind_info_set_option duckdb_v2_table_function_get_docs duckdb_v2_table_function_get_signature -duckdb_v2_table_function_init_global_get_bind_data -duckdb_v2_table_function_init_global_get_column_count -duckdb_v2_table_function_init_global_get_column_index -duckdb_v2_table_function_init_global_get_user_data -duckdb_v2_table_function_init_global_set_global_state -duckdb_v2_table_function_init_global_set_max_threads -duckdb_v2_table_function_init_local_get_bind_data -duckdb_v2_table_function_init_local_get_column_count -duckdb_v2_table_function_init_local_get_column_index -duckdb_v2_table_function_init_local_get_global_state -duckdb_v2_table_function_init_local_get_user_data -duckdb_v2_table_function_init_local_set_local_state -duckdb_v2_table_function_partition_data_get_bind_data -duckdb_v2_table_function_partition_data_get_global_state -duckdb_v2_table_function_partition_data_get_local_state -duckdb_v2_table_function_partition_data_get_partition_column_count -duckdb_v2_table_function_partition_data_get_partition_column_index -duckdb_v2_table_function_partition_data_get_user_data -duckdb_v2_table_function_partition_data_requires_batch_index -duckdb_v2_table_function_partition_data_requires_partition_columns -duckdb_v2_table_function_partition_data_set_batch_index -duckdb_v2_table_function_partition_data_set_partition_value duckdb_v2_table_function_partitioning_get_bind_data duckdb_v2_table_function_partitioning_get_partition_column_count duckdb_v2_table_function_partitioning_get_partition_column_index duckdb_v2_table_function_partitioning_get_user_data duckdb_v2_table_function_partitioning_set_partition_info -duckdb_v2_table_function_progress_get_bind_data -duckdb_v2_table_function_progress_get_global_state -duckdb_v2_table_function_progress_get_user_data -duckdb_v2_table_function_progress_set_progress duckdb_v2_table_function_set_bind_callback -duckdb_v2_table_function_set_claim_batch_callback -duckdb_v2_table_function_set_exec_callback duckdb_v2_table_function_set_filter_pushdown_callback duckdb_v2_table_function_set_get_bind_info_callback -duckdb_v2_table_function_set_init_global_callback -duckdb_v2_table_function_set_init_local_callback duckdb_v2_table_function_set_name -duckdb_v2_table_function_set_partition_data_callback duckdb_v2_table_function_set_partitioning_callback -duckdb_v2_table_function_set_progress_callback duckdb_v2_table_function_set_projection_pushdown duckdb_v2_table_function_set_user_data duckdb_v2_token_iterator_destroy diff --git a/duckdb_java.exp b/duckdb_java.exp index aceb8881f..47bd9d12c 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -877,28 +877,7 @@ _duckdb_v2_copy_from_bind_get_option_value _duckdb_v2_copy_from_bind_get_user_data _duckdb_v2_copy_from_bind_set_bind_data _duckdb_v2_copy_from_bind_set_cardinality -_duckdb_v2_copy_from_exec_get_bind_data -_duckdb_v2_copy_from_exec_get_global_state -_duckdb_v2_copy_from_exec_get_local_state -_duckdb_v2_copy_from_exec_get_output_chunk -_duckdb_v2_copy_from_exec_get_user_data -_duckdb_v2_copy_from_init_global_get_bind_data -_duckdb_v2_copy_from_init_global_get_user_data -_duckdb_v2_copy_from_init_global_set_global_state -_duckdb_v2_copy_from_init_global_set_max_threads -_duckdb_v2_copy_from_init_local_get_bind_data -_duckdb_v2_copy_from_init_local_get_global_state -_duckdb_v2_copy_from_init_local_get_user_data -_duckdb_v2_copy_from_init_local_set_local_state -_duckdb_v2_copy_from_progress_get_bind_data -_duckdb_v2_copy_from_progress_get_global_state -_duckdb_v2_copy_from_progress_get_user_data -_duckdb_v2_copy_from_progress_set_progress _duckdb_v2_copy_from_set_bind_callback -_duckdb_v2_copy_from_set_exec_callback -_duckdb_v2_copy_from_set_init_global_callback -_duckdb_v2_copy_from_set_init_local_callback -_duckdb_v2_copy_from_set_progress_callback _duckdb_v2_copy_function_create _duckdb_v2_copy_function_destroy _duckdb_v2_copy_function_set_file_extension @@ -1189,20 +1168,8 @@ _duckdb_v2_table_description_is_readonly _duckdb_v2_table_function_bind_add_result_column _duckdb_v2_table_function_bind_set_cardinality _duckdb_v2_table_function_bind_set_order_preservation -_duckdb_v2_table_function_claim_batch_get_bind_data -_duckdb_v2_table_function_claim_batch_get_global_state -_duckdb_v2_table_function_claim_batch_get_local_state -_duckdb_v2_table_function_claim_batch_get_user_data -_duckdb_v2_table_function_claim_batch_set_claimed _duckdb_v2_table_function_create _duckdb_v2_table_function_destroy -_duckdb_v2_table_function_exec_get_bind_data -_duckdb_v2_table_function_exec_get_column_count -_duckdb_v2_table_function_exec_get_column_index -_duckdb_v2_table_function_exec_get_global_state -_duckdb_v2_table_function_exec_get_local_state -_duckdb_v2_table_function_exec_get_output_chunk -_duckdb_v2_table_function_exec_get_user_data _duckdb_v2_table_function_filter_pushdown_accept _duckdb_v2_table_function_filter_pushdown_get_bind_data _duckdb_v2_table_function_filter_pushdown_get_column_count @@ -1216,48 +1183,16 @@ _duckdb_v2_table_function_get_bind_info_set_column_identifier _duckdb_v2_table_function_get_bind_info_set_option _duckdb_v2_table_function_get_docs _duckdb_v2_table_function_get_signature -_duckdb_v2_table_function_init_global_get_bind_data -_duckdb_v2_table_function_init_global_get_column_count -_duckdb_v2_table_function_init_global_get_column_index -_duckdb_v2_table_function_init_global_get_user_data -_duckdb_v2_table_function_init_global_set_global_state -_duckdb_v2_table_function_init_global_set_max_threads -_duckdb_v2_table_function_init_local_get_bind_data -_duckdb_v2_table_function_init_local_get_column_count -_duckdb_v2_table_function_init_local_get_column_index -_duckdb_v2_table_function_init_local_get_global_state -_duckdb_v2_table_function_init_local_get_user_data -_duckdb_v2_table_function_init_local_set_local_state -_duckdb_v2_table_function_partition_data_get_bind_data -_duckdb_v2_table_function_partition_data_get_global_state -_duckdb_v2_table_function_partition_data_get_local_state -_duckdb_v2_table_function_partition_data_get_partition_column_count -_duckdb_v2_table_function_partition_data_get_partition_column_index -_duckdb_v2_table_function_partition_data_get_user_data -_duckdb_v2_table_function_partition_data_requires_batch_index -_duckdb_v2_table_function_partition_data_requires_partition_columns -_duckdb_v2_table_function_partition_data_set_batch_index -_duckdb_v2_table_function_partition_data_set_partition_value _duckdb_v2_table_function_partitioning_get_bind_data _duckdb_v2_table_function_partitioning_get_partition_column_count _duckdb_v2_table_function_partitioning_get_partition_column_index _duckdb_v2_table_function_partitioning_get_user_data _duckdb_v2_table_function_partitioning_set_partition_info -_duckdb_v2_table_function_progress_get_bind_data -_duckdb_v2_table_function_progress_get_global_state -_duckdb_v2_table_function_progress_get_user_data -_duckdb_v2_table_function_progress_set_progress _duckdb_v2_table_function_set_bind_callback -_duckdb_v2_table_function_set_claim_batch_callback -_duckdb_v2_table_function_set_exec_callback _duckdb_v2_table_function_set_filter_pushdown_callback _duckdb_v2_table_function_set_get_bind_info_callback -_duckdb_v2_table_function_set_init_global_callback -_duckdb_v2_table_function_set_init_local_callback _duckdb_v2_table_function_set_name -_duckdb_v2_table_function_set_partition_data_callback _duckdb_v2_table_function_set_partitioning_callback -_duckdb_v2_table_function_set_progress_callback _duckdb_v2_table_function_set_projection_pushdown _duckdb_v2_table_function_set_user_data _duckdb_v2_token_iterator_destroy diff --git a/duckdb_java.map b/duckdb_java.map index 972f0db48..1371be4c5 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -879,28 +879,7 @@ DUCKDB_JAVA { duckdb_v2_copy_from_bind_get_user_data; duckdb_v2_copy_from_bind_set_bind_data; duckdb_v2_copy_from_bind_set_cardinality; - duckdb_v2_copy_from_exec_get_bind_data; - duckdb_v2_copy_from_exec_get_global_state; - duckdb_v2_copy_from_exec_get_local_state; - duckdb_v2_copy_from_exec_get_output_chunk; - duckdb_v2_copy_from_exec_get_user_data; - duckdb_v2_copy_from_init_global_get_bind_data; - duckdb_v2_copy_from_init_global_get_user_data; - duckdb_v2_copy_from_init_global_set_global_state; - duckdb_v2_copy_from_init_global_set_max_threads; - duckdb_v2_copy_from_init_local_get_bind_data; - duckdb_v2_copy_from_init_local_get_global_state; - duckdb_v2_copy_from_init_local_get_user_data; - duckdb_v2_copy_from_init_local_set_local_state; - duckdb_v2_copy_from_progress_get_bind_data; - duckdb_v2_copy_from_progress_get_global_state; - duckdb_v2_copy_from_progress_get_user_data; - duckdb_v2_copy_from_progress_set_progress; duckdb_v2_copy_from_set_bind_callback; - duckdb_v2_copy_from_set_exec_callback; - duckdb_v2_copy_from_set_init_global_callback; - duckdb_v2_copy_from_set_init_local_callback; - duckdb_v2_copy_from_set_progress_callback; duckdb_v2_copy_function_create; duckdb_v2_copy_function_destroy; duckdb_v2_copy_function_set_file_extension; @@ -1191,20 +1170,8 @@ DUCKDB_JAVA { duckdb_v2_table_function_bind_add_result_column; duckdb_v2_table_function_bind_set_cardinality; duckdb_v2_table_function_bind_set_order_preservation; - duckdb_v2_table_function_claim_batch_get_bind_data; - duckdb_v2_table_function_claim_batch_get_global_state; - duckdb_v2_table_function_claim_batch_get_local_state; - duckdb_v2_table_function_claim_batch_get_user_data; - duckdb_v2_table_function_claim_batch_set_claimed; duckdb_v2_table_function_create; duckdb_v2_table_function_destroy; - duckdb_v2_table_function_exec_get_bind_data; - duckdb_v2_table_function_exec_get_column_count; - duckdb_v2_table_function_exec_get_column_index; - duckdb_v2_table_function_exec_get_global_state; - duckdb_v2_table_function_exec_get_local_state; - duckdb_v2_table_function_exec_get_output_chunk; - duckdb_v2_table_function_exec_get_user_data; duckdb_v2_table_function_filter_pushdown_accept; duckdb_v2_table_function_filter_pushdown_get_bind_data; duckdb_v2_table_function_filter_pushdown_get_column_count; @@ -1218,48 +1185,16 @@ DUCKDB_JAVA { duckdb_v2_table_function_get_bind_info_set_option; duckdb_v2_table_function_get_docs; duckdb_v2_table_function_get_signature; - duckdb_v2_table_function_init_global_get_bind_data; - duckdb_v2_table_function_init_global_get_column_count; - duckdb_v2_table_function_init_global_get_column_index; - duckdb_v2_table_function_init_global_get_user_data; - duckdb_v2_table_function_init_global_set_global_state; - duckdb_v2_table_function_init_global_set_max_threads; - duckdb_v2_table_function_init_local_get_bind_data; - duckdb_v2_table_function_init_local_get_column_count; - duckdb_v2_table_function_init_local_get_column_index; - duckdb_v2_table_function_init_local_get_global_state; - duckdb_v2_table_function_init_local_get_user_data; - duckdb_v2_table_function_init_local_set_local_state; - duckdb_v2_table_function_partition_data_get_bind_data; - duckdb_v2_table_function_partition_data_get_global_state; - duckdb_v2_table_function_partition_data_get_local_state; - duckdb_v2_table_function_partition_data_get_partition_column_count; - duckdb_v2_table_function_partition_data_get_partition_column_index; - duckdb_v2_table_function_partition_data_get_user_data; - duckdb_v2_table_function_partition_data_requires_batch_index; - duckdb_v2_table_function_partition_data_requires_partition_columns; - duckdb_v2_table_function_partition_data_set_batch_index; - duckdb_v2_table_function_partition_data_set_partition_value; duckdb_v2_table_function_partitioning_get_bind_data; duckdb_v2_table_function_partitioning_get_partition_column_count; duckdb_v2_table_function_partitioning_get_partition_column_index; duckdb_v2_table_function_partitioning_get_user_data; duckdb_v2_table_function_partitioning_set_partition_info; - duckdb_v2_table_function_progress_get_bind_data; - duckdb_v2_table_function_progress_get_global_state; - duckdb_v2_table_function_progress_get_user_data; - duckdb_v2_table_function_progress_set_progress; duckdb_v2_table_function_set_bind_callback; - duckdb_v2_table_function_set_claim_batch_callback; - duckdb_v2_table_function_set_exec_callback; duckdb_v2_table_function_set_filter_pushdown_callback; duckdb_v2_table_function_set_get_bind_info_callback; - duckdb_v2_table_function_set_init_global_callback; - duckdb_v2_table_function_set_init_local_callback; duckdb_v2_table_function_set_name; - duckdb_v2_table_function_set_partition_data_callback; duckdb_v2_table_function_set_partitioning_callback; - duckdb_v2_table_function_set_progress_callback; duckdb_v2_table_function_set_projection_pushdown; duckdb_v2_table_function_set_user_data; duckdb_v2_token_iterator_destroy; diff --git a/src/jni/bindings_table_function.cpp b/src/jni/bindings_table_function.cpp index 8ffe8e50e..bc0b567d8 100644 --- a/src/jni/bindings_table_function.cpp +++ b/src/jni/bindings_table_function.cpp @@ -260,10 +260,10 @@ static void table_function_bind(duckdb_v2_function_bind_info_handle info, } } -static void table_function_init(duckdb_v2_table_function_init_global_info_handle info, duckdb_v2_context_handle, +static void table_function_init(duckdb_v2_data_source_init_global_info_handle info, duckdb_v2_context_handle, duckdb_v2_error_info_handle *err) { void *user_data_ptr = nullptr; - duckdb_v2_table_function_init_global_get_user_data(info, &user_data_ptr, nullptr); + duckdb_v2_data_source_init_global_get_user_data(info, &user_data_ptr, nullptr); auto callback_holder = user_data_ptr != nullptr ? reinterpret_cast(user_data_ptr)->callback.get() : nullptr; if (callback_holder == nullptr) { @@ -284,15 +284,15 @@ static void table_function_init(duckdb_v2_table_function_init_global_info_handle GlobalRefHolder *init_data = init_info.init_data ? init_info.init_data->release() : nullptr; duckdb_v2_opaque opaque = {new TableFunctionState(init_data), TableFunctionState::destroy, nullptr}; v2_error call_err; - if (duckdb_v2_table_function_init_global_set_global_state(info, &opaque, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + if (duckdb_v2_data_source_init_global_set_global_state(info, &opaque, call_err.out()) != DUCKDB_V2_ERROR_NONE) { set_callback_error(err, call_err.code(), call_err.raw_message()); } } -static void table_function_local_init(duckdb_v2_table_function_init_local_info_handle info, duckdb_v2_context_handle, +static void table_function_local_init(duckdb_v2_data_source_init_local_info_handle info, duckdb_v2_context_handle, duckdb_v2_error_info_handle *err) { void *user_data_ptr = nullptr; - duckdb_v2_table_function_init_local_get_user_data(info, &user_data_ptr, nullptr); + duckdb_v2_data_source_init_local_get_user_data(info, &user_data_ptr, nullptr); auto callback_holder = user_data_ptr != nullptr ? reinterpret_cast(user_data_ptr)->callback.get() : nullptr; if (callback_holder == nullptr) { @@ -311,15 +311,15 @@ static void table_function_local_init(duckdb_v2_table_function_init_local_info_h GlobalRefHolder *init_data = init_info.init_data ? init_info.init_data->release() : nullptr; duckdb_v2_opaque opaque = {new TableFunctionState(init_data), TableFunctionState::destroy, nullptr}; v2_error call_err; - if (duckdb_v2_table_function_init_local_set_local_state(info, &opaque, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + if (duckdb_v2_data_source_init_local_set_local_state(info, &opaque, call_err.out()) != DUCKDB_V2_ERROR_NONE) { set_callback_error(err, call_err.code(), call_err.raw_message()); } } -static void table_function_exec(duckdb_v2_table_function_exec_info_handle info, duckdb_v2_context_handle, +static void table_function_exec(duckdb_v2_data_source_exec_info_handle info, duckdb_v2_context_handle, duckdb_v2_error_info_handle *err) { void *user_data_ptr = nullptr; - duckdb_v2_table_function_exec_get_user_data(info, &user_data_ptr, nullptr); + duckdb_v2_data_source_exec_get_user_data(info, &user_data_ptr, nullptr); if (user_data_ptr == nullptr) { set_callback_error(err, DUCKDB_V2_ERROR_INPUT_INVALID, "Table function callback not found"); return; @@ -333,7 +333,7 @@ static void table_function_exec(duckdb_v2_table_function_exec_info_handle info, // the output chunk is borrowed duckdb_v2_data_chunk_handle output = nullptr; v2_error call_err; - if (duckdb_v2_table_function_exec_get_output_chunk(info, &output, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + if (duckdb_v2_data_source_exec_get_output_chunk(info, &output, call_err.out()) != DUCKDB_V2_ERROR_NONE) { set_callback_error(err, call_err.code(), call_err.raw_message()); return; } @@ -399,14 +399,21 @@ static jint register_table_function(duckdb_v2_connection_handle conn, TableFunct return static_cast(CAPI_STATE_ERROR); } } - if (duckdb_v2_table_function_set_bind_callback(function.get(), table_function_bind, nullptr) != - DUCKDB_V2_ERROR_NONE || - duckdb_v2_table_function_set_init_global_callback(function.get(), table_function_init, nullptr) != + // the scan callbacks are set on a data source, the table function keeps a copy of it, + // data source callbacks get the user data of the table function as the data source has none + v2_data_source data_source; + if (duckdb_v2_data_source_create(factory, data_source.out(), nullptr) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_data_source_set_init_global_callback(data_source.get(), table_function_init, nullptr) != DUCKDB_V2_ERROR_NONE || - (spec.has_local_init && duckdb_v2_table_function_set_init_local_callback( - function.get(), table_function_local_init, nullptr) != DUCKDB_V2_ERROR_NONE) || - duckdb_v2_table_function_set_exec_callback(function.get(), table_function_exec, nullptr) != + (spec.has_local_init && duckdb_v2_data_source_set_init_local_callback( + data_source.get(), table_function_local_init, nullptr) != DUCKDB_V2_ERROR_NONE) || + duckdb_v2_data_source_set_exec_callback(data_source.get(), table_function_exec, nullptr) != + DUCKDB_V2_ERROR_NONE) { + return static_cast(CAPI_STATE_ERROR); + } + if (duckdb_v2_table_function_set_bind_callback(function.get(), table_function_bind, nullptr) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_table_function_set_data_source(function.get(), data_source.get(), nullptr) != DUCKDB_V2_ERROR_NONE || duckdb_v2_table_function_set_projection_pushdown(function.get(), spec.projection_pushdown, nullptr) != DUCKDB_V2_ERROR_NONE) { return static_cast(CAPI_STATE_ERROR); @@ -720,7 +727,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1function_1get_1 void *bind_data = nullptr; v2_error err; - if (duckdb_v2_table_function_exec_get_bind_data(fi->info, &bind_data, err.out()) != DUCKDB_V2_ERROR_NONE) { + if (duckdb_v2_data_source_exec_get_bind_data(fi->info, &bind_data, err.out()) != DUCKDB_V2_ERROR_NONE) { throw_sql_exception(env, err); return nullptr; } @@ -743,8 +750,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1function_1get_1 void *global_init_data = nullptr; v2_error err; - if (duckdb_v2_table_function_exec_get_global_state(fi->info, &global_init_data, err.out()) != - DUCKDB_V2_ERROR_NONE) { + if (duckdb_v2_data_source_exec_get_global_state(fi->info, &global_init_data, err.out()) != DUCKDB_V2_ERROR_NONE) { throw_sql_exception(env, err); return nullptr; } @@ -770,7 +776,7 @@ Java_org_duckdb_DuckDBBindings_duckdb_1function_1get_1local_1init_1data(JNIEnv * } void *local_init_data = nullptr; v2_error err; - if (duckdb_v2_table_function_exec_get_local_state(fi->info, &local_init_data, err.out()) != DUCKDB_V2_ERROR_NONE) { + if (duckdb_v2_data_source_exec_get_local_state(fi->info, &local_init_data, err.out()) != DUCKDB_V2_ERROR_NONE) { throw_sql_exception(env, err); return nullptr; } diff --git a/src/jni/bindings_table_function.hpp b/src/jni/bindings_table_function.hpp index 416c9f717..cec1e9b18 100644 --- a/src/jni/bindings_table_function.hpp +++ b/src/jni/bindings_table_function.hpp @@ -82,8 +82,8 @@ struct TableFunctionBindInfoHolder { * Init info that is passed to Java during the global and local init calls. */ struct TableFunctionInitInfoHolder { - duckdb_v2_table_function_init_global_info_handle global_info = nullptr; - duckdb_v2_table_function_init_local_info_handle local_info = nullptr; + duckdb_v2_data_source_init_global_info_handle global_info = nullptr; + duckdb_v2_data_source_init_local_info_handle local_info = nullptr; std::unique_ptr init_data; bool has_error = false; std::string error; @@ -93,11 +93,11 @@ struct TableFunctionInitInfoHolder { * Function info that is passed to Java during the function call. */ struct TableFunctionInfoHolder { - TableFunctionInfoHolder(duckdb_v2_table_function_exec_info_handle info_p, bool has_local_init_p) + TableFunctionInfoHolder(duckdb_v2_data_source_exec_info_handle info_p, bool has_local_init_p) : info(info_p), has_local_init(has_local_init_p) { } - duckdb_v2_table_function_exec_info_handle info; + duckdb_v2_data_source_exec_info_handle info; bool has_local_init; bool has_error = false; std::string error; diff --git a/src/jni/bindings_table_function_init.cpp b/src/jni/bindings_table_function_init.cpp index 69d73b535..5a7b87646 100644 --- a/src/jni/bindings_table_function_init.cpp +++ b/src/jni/bindings_table_function_init.cpp @@ -31,8 +31,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1init_1get_1bind void *bind_data = nullptr; v2_error err; auto state = ii->global_info != nullptr - ? duckdb_v2_table_function_init_global_get_bind_data(ii->global_info, &bind_data, err.out()) - : duckdb_v2_table_function_init_local_get_bind_data(ii->local_info, &bind_data, err.out()); + ? duckdb_v2_data_source_init_global_get_bind_data(ii->global_info, &bind_data, err.out()) + : duckdb_v2_data_source_init_local_get_bind_data(ii->local_info, &bind_data, err.out()); if (state != DUCKDB_V2_ERROR_NONE) { throw_sql_exception(env, err); return nullptr; @@ -82,8 +82,8 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1init_1get_1column idx_t count = 0; v2_error err; auto state = ii->global_info != nullptr - ? duckdb_v2_table_function_init_global_get_column_count(ii->global_info, &count, err.out()) - : duckdb_v2_table_function_init_local_get_column_count(ii->local_info, &count, err.out()); + ? duckdb_v2_data_source_init_global_get_column_count(ii->global_info, &count, err.out()) + : duckdb_v2_data_source_init_local_get_column_count(ii->local_info, &count, err.out()); if (state != DUCKDB_V2_ERROR_NONE) { throw_sql_exception(env, err); return 0; @@ -114,16 +114,16 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1init_1get_1column idx_t count = 0; idx_t idx = 0; if (ii->global_info != nullptr) { - if (duckdb_v2_table_function_init_global_get_column_count(ii->global_info, &count, nullptr) == + if (duckdb_v2_data_source_init_global_get_column_count(ii->global_info, &count, nullptr) == DUCKDB_V2_ERROR_NONE && column_index_idx < count) { - duckdb_v2_table_function_init_global_get_column_index(ii->global_info, column_index_idx, &idx, nullptr); + duckdb_v2_data_source_init_global_get_column_index(ii->global_info, column_index_idx, &idx, nullptr); } } else { - if (duckdb_v2_table_function_init_local_get_column_count(ii->local_info, &count, nullptr) == + if (duckdb_v2_data_source_init_local_get_column_count(ii->local_info, &count, nullptr) == DUCKDB_V2_ERROR_NONE && column_index_idx < count) { - duckdb_v2_table_function_init_local_get_column_index(ii->local_info, column_index_idx, &idx, nullptr); + duckdb_v2_data_source_init_local_get_column_index(ii->local_info, column_index_idx, &idx, nullptr); } } return uint64_to_jlong(idx); @@ -152,7 +152,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1init_1set_1max_1th return; } v2_error err; - if (duckdb_v2_table_function_init_global_set_max_threads(ii->global_info, mt, err.out()) != DUCKDB_V2_ERROR_NONE) { + if (duckdb_v2_data_source_init_global_set_max_threads(ii->global_info, mt, err.out()) != DUCKDB_V2_ERROR_NONE) { throw_sql_exception(env, err); } } diff --git a/src/jni/capi_v2.hpp b/src/jni/capi_v2.hpp index d1d9e1b7c..d4ff6e36e 100644 --- a/src/jni/capi_v2.hpp +++ b/src/jni/capi_v2.hpp @@ -161,6 +161,7 @@ using v2_schema = v2_handle; using v2_result = v2_handle; using v2_scalar_function = v2_handle; using v2_table_function = v2_handle; +using v2_data_source = v2_handle; /** * The factory of a process-wide DuckDB instance that has no databases attached to it, or nullptr if diff --git a/src/jni/config.cpp b/src/jni/config.cpp index 396d3d11d..c9225e289 100644 --- a/src/jni/config.cpp +++ b/src/jni/config.cpp @@ -86,31 +86,50 @@ static bool is_allowed_paths_option(const std::string &key) { } // 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. +// SetOptionByName before the database is started. Their values are collected +// here and set directly on the DBConfig of the database after it is started +// (see apply_allowed_paths_options), the paths are sanitized using the +// context of the database instance. // 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) { +static void collect_allowed_paths_option(duckdb::DBConfig &config, const std::string &key, const duckdb::Value &value, + std::vector &allowed_paths_options) { 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; + AllowedPathsOption option; + option.key = key; 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); + option.paths.push_back(val.GetValue()); } + allowed_paths_options.push_back(std::move(option)); // 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; } -std::unique_ptr create_db_config(JNIEnv *env, jboolean read_only, jobject java_config) { +void apply_allowed_paths_options(duckdb::DatabaseInstance &db, + const std::vector &allowed_paths_options) { + auto &config = duckdb::DBConfig::GetConfig(db); + for (auto &option : allowed_paths_options) { + try { + if (duckdb::StringUtil::CIEquals(option.key, "allowed_directories")) { + config.SetAllowedDirectories(db.GetContext(), option.paths); + } else { + config.SetAllowedPaths(db.GetContext(), option.paths); + } + } catch (const std::exception &e) { + duckdb::ErrorData error(e); + throw duckdb::CatalogException("Failed to set configuration option \"%s\", error: %s", option.key, + error.RawMessage()); + } + } +} + +std::unique_ptr create_db_config(JNIEnv *env, jboolean read_only, jobject java_config, + std::vector &allowed_paths_options) { auto config = std::unique_ptr(new duckdb::DBConfig()); // Required for setting like 'allowed_directories' that use // file separator when checking the property value. @@ -148,7 +167,7 @@ std::unique_ptr create_db_config(JNIEnv *env, jboolean read_on try { if (is_allowed_paths_option(key_str)) { - set_allowed_paths_option(*config, key_str, dvalue); + collect_allowed_paths_option(*config, key_str, dvalue, allowed_paths_options); continue; } config->SetOptionByName(duckdb::Identifier(key_str), dvalue); diff --git a/src/jni/config.hpp b/src/jni/config.hpp index 8218226fe..8a6aeb519 100644 --- a/src/jni/config.hpp +++ b/src/jni/config.hpp @@ -4,5 +4,18 @@ #include #include +#include +#include -std::unique_ptr create_db_config(JNIEnv *env, jboolean read_only, jobject java_config); +// Value of the 'allowed_directories' or 'allowed_paths' option, these options +// can only be applied after the database is started +struct AllowedPathsOption { + std::string key; + duckdb::vector paths; +}; + +std::unique_ptr create_db_config(JNIEnv *env, jboolean read_only, jobject java_config, + std::vector &allowed_paths_options); + +void apply_allowed_paths_options(duckdb::DatabaseInstance &db, + const std::vector &allowed_paths_options); diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index 4cf0f2c83..baca16e59 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -80,9 +80,14 @@ duckdb::DBInstanceCache instance_cache; 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); + std::vector allowed_paths_options; + std::unique_ptr config = create_db_config(env, read_only, props, allowed_paths_options); bool should_cache = cache_instance && database != ":memory:" && !database.empty(); - auto shared_db = instance_cache.GetOrCreateInstance(database, *config, should_cache); + // runs only when a new instance is created, before it is published in the instance cache + auto on_create = [&allowed_paths_options](duckdb::DuckDB &db) { + apply_allowed_paths_options(*db.instance, allowed_paths_options); + }; + auto shared_db = instance_cache.GetOrCreateInstance(database, *config, should_cache, on_create); auto conn_ref = new ConnectionHolder(shared_db); return env->NewDirectByteBuffer(conn_ref, 0);