diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/lttb.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/lttb.cpp index ccb0a15b2..eeae36673 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/lttb.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/lttb.cpp @@ -382,7 +382,7 @@ auto LTTBStateLayout(AggregateLayoutInput &input) -> AggregateStateLayout { auto &function = input.function; using ST = LTTBState::STATE_TYPE; AggregateStateLayout layout; - if (function.GetReturnType().IsAggregateState()) { + if (function.ReturnsExportedState()) { // The function has been modified for state export, its return type IS the state type already layout.type = function.GetReturnType(); } else { diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp index 363fcfe68..324f5825a 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp @@ -159,7 +159,7 @@ struct ModeString { AggregateInputData &aggr_input_data) { if (key.IsInlined()) { if (!mode) { - mode = aggr_input_data.allocator.Make(nullptr, 0); + mode = aggr_input_data.allocator.Make(); } *mode = key; alloc_size = 0; @@ -177,7 +177,7 @@ struct ModeString { alloc_size = NextPowerOfTwo(len); ptr = char_ptr_cast(aggr_input_data.allocator.Allocate(alloc_size)); if (!mode) { - mode = aggr_input_data.allocator.Make(nullptr, 0); + mode = aggr_input_data.allocator.Make(); } } memcpy(ptr, key.GetData(), len); diff --git a/src/duckdb/extension/core_functions/aggregate/variant/variant_group_object.cpp b/src/duckdb/extension/core_functions/aggregate/variant/variant_group_object.cpp index 1ca57c1e6..43487b2cc 100644 --- a/src/duckdb/extension/core_functions/aggregate/variant/variant_group_object.cpp +++ b/src/duckdb/extension/core_functions/aggregate/variant/variant_group_object.cpp @@ -177,7 +177,7 @@ void VariantObjClusterUpdate(Vector inputs[], AggregateInputData &aggr_input_dat AggregateStateLayout VariantObjStateLayout(AggregateLayoutInput &input) { AggregateStateLayout layout; - if (input.function.GetReturnType().IsAggregateState()) { + if (input.function.ReturnsExportedState()) { layout.type = input.function.GetReturnType(); } else { layout.type = LogicalType::LIST(GetInternalBufferType()); 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 e080945cf..efc396ed4 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 @@ -417,7 +417,7 @@ template >> AggregateStateLayout QuantileStateLayout(AggregateLayoutInput &input) { auto &function = input.function; AggregateStateLayout layout; - if (function.GetReturnType().IsAggregateState()) { + 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(); diff --git a/src/duckdb/extension/icu/icu-datesub.cpp b/src/duckdb/extension/icu/icu-datesub.cpp index c2fc3ae2f..f38d01a4b 100644 --- a/src/duckdb/extension/icu/icu-datesub.cpp +++ b/src/duckdb/extension/icu/icu-datesub.cpp @@ -10,12 +10,27 @@ namespace duckdb { struct ICUCalendarSub : public ICUDateFunc { + static bool SubtractsElapsedTime(DatePartSpecifier part) { + switch (part) { + case DatePartSpecifier::HOUR: + case DatePartSpecifier::MINUTE: + case DatePartSpecifier::SECOND: + case DatePartSpecifier::EPOCH: + case DatePartSpecifier::MILLISECONDS: + case DatePartSpecifier::MICROSECONDS: + return true; + default: + return false; + } + } + static unique_ptr Bind(BindScalarFunctionInput &input) { auto part_value = input.TryGetConstant(0); if (part_value && !part_value->IsNull()) { DatePartSpecifier part; - if (TryGetDatePartSpecifier(part_value->GetValue(), part) && part == DatePartSpecifier::ERA) { - // date_sub is not monotone for eras because era boundaries can occur partway through a year + if (!TryGetDatePartSpecifier(part_value->GetValue(), part) || !SubtractsElapsedTime(part)) { + // calendar parts count whole local units, so moving one argument can step the result back, + // e.g. a month boundary that falls between two timestamps or a local day that repeats input.GetBoundFunction().SetArgProperties({}); } } @@ -221,14 +236,25 @@ ICUDateFunc::part_sub_t ICUDateFunc::SubtractFactory(DatePartSpecifier type) { // MS-SQL differences can be computed using ICU by truncating both arguments // to the desired part precision and then applying ICU subtraction/difference struct ICUCalendarDiff : public ICUDateFunc { + static bool TruncatesToSecondOrFiner(DatePartSpecifier part) { + switch (part) { + case DatePartSpecifier::SECOND: + case DatePartSpecifier::EPOCH: + case DatePartSpecifier::MILLISECONDS: + case DatePartSpecifier::MICROSECONDS: + return true; + default: + return false; + } + } + static unique_ptr Bind(BindScalarFunctionInput &input) { auto part_value = input.TryGetConstant(0); if (part_value && !part_value->IsNull()) { DatePartSpecifier part; - if (TryGetDatePartSpecifier(part_value->GetValue(), part) && - (part == DatePartSpecifier::DECADE || part == DatePartSpecifier::CENTURY || - part == DatePartSpecifier::MILLENNIUM)) { - // date_diff is not monotone for these parts because ICU years skip year 0 at the BC/AD boundary + if (!TryGetDatePartSpecifier(part_value->GetValue(), part) || !TruncatesToSecondOrFiner(part)) { + // date_diff truncates both arguments first, and truncating to a coarser part follows the local + // time, which repeats or moves backwards when the UTC offset changes input.GetBoundFunction().SetArgProperties({}); } } diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 6a049df07..cbecf7160 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-alpha57387"; + descriptor->api_version = "v2.1.0-alpha57486"; 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-alpha57387"; + descriptor->api_version = "v2.1.0-alpha57486"; 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-alpha57387"; + descriptor->api_version = "v2.1.0-alpha57486"; 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-alpha57387"; + descriptor->api_version = "v2.1.0-alpha57486"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp b/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp index 499098891..c897463d7 100644 --- a/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp +++ b/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp @@ -90,6 +90,10 @@ struct ColumnMapper { virtual ~ColumnMapper() = default; virtual unique_ptr Create(const vector &columns) const = 0; virtual MultiFileLocalIndex Find(const MultiFileColumnDefinition &column) const = 0; + //! Find the element of a LIST among the children of the list + virtual MultiFileLocalIndex FindListChild(const MultiFileColumnDefinition &column) const { + return Find(column); + } virtual unique_ptr GetDefaultExpression(ClientContext &context, const MultiFileColumnDefinition &column, bool is_root) const = 0; virtual idx_t MapCount() const = 0; @@ -169,6 +173,14 @@ struct NameMapper : public ColumnMapper { } return entry->second; } + MultiFileLocalIndex FindListChild(const MultiFileColumnDefinition &column) const override { + if (name_map.size() != 1) { + return Find(column); + } + // A LIST has exactly one child, and a file names it after its repeated group ("list", "array", "bag", ...). + // That name is not part of the logical schema, so the single child is the element whatever it is called. + return MultiFileLocalIndex(0); + } unique_ptr GetDefaultExpression(ClientContext &context, const MultiFileColumnDefinition &column, bool is_root) const override { if (column.default_expression) { @@ -249,6 +261,13 @@ static ColumnMapResult MapColumn(ClientContext &context, const MultiFileColumnDe const vector &local_columns, const ColumnMapper &mapper, MultiFileLocalIndex top_level_index = MultiFileLocalIndex()); +//! Map a global column to the local column the mapper found for it (invalid if the file does not have it) +static ColumnMapResult MapColumnToLocal(ClientContext &context, const MultiFileColumnDefinition &global_column, + const ColumnIndex &global_index, + const vector &local_columns, + const ColumnMapper &mapper, MultiFileLocalIndex local_idx, + MultiFileLocalIndex top_level_index = MultiFileLocalIndex()); + static ColumnMapResult MapColumnList(ClientContext &context, const MultiFileColumnDefinition &global_column, const ColumnIndex &global_index, const MultiFileColumnDefinition &local_column, const MultiFileLocalIndex &local_id, const ColumnMapper &mapper, @@ -289,7 +308,8 @@ static ColumnMapResult MapColumnList(ClientContext &context, const MultiFileColu ColumnMapResult child_map; if (is_selected) { - child_map = MapColumn(context, global_child, global_child_index.get(), local_column.children, *nested_mapper); + child_map = MapColumnToLocal(context, global_child, global_child_index.get(), local_column.children, + *nested_mapper, nested_mapper->FindListChild(global_child)); } else { // column is not relevant for the query - push a NULL value child_map.default_value = make_uniq(Value(global_child.type)); @@ -306,8 +326,8 @@ static ColumnMapResult MapColumnList(ClientContext &context, const MultiFileColu ColumnMapResult result; result.local_column = local_column; - if (!column_mapping.empty()) { - // we have column mappings at this level - construct the struct + if (!column_mapping.empty() || !is_root) { + // A nested source still supplies the list entries when the element comes from a default. result.column_map = Value::STRUCT(std::move(column_mapping)); if (!is_root) { // if this is nested we need to refer to the current column at this level @@ -385,8 +405,8 @@ static ColumnMapResult MapColumnMap(ClientContext &context, const MultiFileColum global_column.children.size()); } + // the single child is the repeated group of the map, which most files call "key_value" and some "map" D_ASSERT(local_column.children.size() == 1); - D_ASSERT(local_column.children[0].name == "key_value"); auto &local_key_value = local_column.children[0]; auto nested_mapper = mapper.Create(local_key_value.children); @@ -435,8 +455,8 @@ static ColumnMapResult MapColumnMap(ClientContext &context, const MultiFileColum ColumnMapResult result; result.local_column = local_column; - if (!column_mapping.empty()) { - // we have column mappings at this level - construct the struct + if (!column_mapping.empty() || !is_root) { + // A nested source still supplies the map entries when the key and value come from defaults. result.column_map = Value::STRUCT(std::move(column_mapping)); if (!is_root) { // if this is nested we need to refer to the current column at this level @@ -582,9 +602,17 @@ static ColumnMapResult MapColumn(ClientContext &context, const MultiFileColumnDe const ColumnIndex &global_index, const vector &local_columns, const ColumnMapper &mapper, MultiFileLocalIndex top_level_index) { + return MapColumnToLocal(context, global_column, global_index, local_columns, mapper, mapper.Find(global_column), + top_level_index); +} + +static ColumnMapResult MapColumnToLocal(ClientContext &context, const MultiFileColumnDefinition &global_column, + const ColumnIndex &global_index, + const vector &local_columns, + const ColumnMapper &mapper, MultiFileLocalIndex local_idx, + MultiFileLocalIndex top_level_index) { bool is_root = top_level_index.IsValid(); ColumnMapResult result; - auto local_idx = mapper.Find(global_column); if (!local_idx.IsValid()) { // entry not present in map, use default value result.default_value = mapper.GetDefaultExpression(context, global_column, is_root); diff --git a/src/duckdb/src/common/random_engine.cpp b/src/duckdb/src/common/random_engine.cpp index ab93811b3..aec84813c 100644 --- a/src/duckdb/src/common/random_engine.cpp +++ b/src/duckdb/src/common/random_engine.cpp @@ -2,6 +2,8 @@ #include "duckdb/common/numeric_utils.hpp" #include "pcg_random.hpp" +#include + #ifdef __linux__ #include #include diff --git a/src/duckdb/src/common/types/validity_mask.cpp b/src/duckdb/src/common/types/validity_mask.cpp index 07c8468f8..72ebf13b0 100644 --- a/src/duckdb/src/common/types/validity_mask.cpp +++ b/src/duckdb/src/common/types/validity_mask.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/types/validity_mask.hpp" +#include "duckdb/common/bit_utils.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/limits.hpp" #include "duckdb/common/numeric_utils.hpp" @@ -278,13 +279,20 @@ void ValidityMask::Write(WriteStream &writer, idx_t count) { auto flag = serialize_valid ? ValiditySerialization::VALID_VALUES : ValiditySerialization::INVALID_VALUES; writer.Write(flag); writer.Write(NumericCast(MinValue(valid_values, invalid_values))); - for (idx_t i = 0; i < count; i++) { - if (RowIsValid(i) == serialize_valid) { + for (idx_t entry_idx = 0; entry_idx < EntryCount(count); entry_idx++) { + auto entry = GetValidityEntry(entry_idx); + validity_t bits = serialize_valid ? entry : ~entry; + while (bits) { + auto i = entry_idx * BITS_PER_VALUE + CountZeros::Trailing(bits); + if (i >= count) { + break; + } if (need_u32) { writer.Write(UnsafeNumericCast(i)); } else { writer.Write(UnsafeNumericCast(i)); } + bits &= bits - 1; } } } else { diff --git a/src/duckdb/src/common/vector/dictionary_vector.cpp b/src/duckdb/src/common/vector/dictionary_vector.cpp index 3dd3f7eda..cc16f06ab 100644 --- a/src/duckdb/src/common/vector/dictionary_vector.cpp +++ b/src/duckdb/src/common/vector/dictionary_vector.cpp @@ -5,6 +5,7 @@ #include "duckdb/common/types/sel_cache.hpp" #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/common/serializer/serializer.hpp" +#include "duckdb/common/bit_utils.hpp" namespace duckdb { @@ -197,6 +198,77 @@ const Vector &DictionaryVector::GetCachedHashes(const Vector &input) { return *entry.cached_hashes; } +void DictionaryVector::ApplyValidity(Vector &vector, const ValidityMask &mask) { + VerifyDictionary(vector); + if (mask.CannotHaveNull()) { + return; + } + const auto count = vector.size(); + const auto validity = mask.GetData(); + const auto full_entry_count = count / ValidityMask::BITS_PER_VALUE; + const auto tail_count = count % ValidityMask::BITS_PER_VALUE; + const auto tail_invalid = + tail_count ? ~validity[full_entry_count] & ValidityMask::EntryWithValidBits(tail_count) : 0; + idx_t first_invalid = 0; + while (first_invalid < full_entry_count && ValidityMask::AllValid(validity[first_invalid])) { + first_invalid++; + } + if (first_invalid == full_entry_count && !tail_invalid) { + return; + } + + const auto &child = Child(vector); + idx_t null_index = child.size(); + if (child.GetVectorType() == VectorType::FLAT_VECTOR && child.size() && + !FlatVector::Validity(child).RowIsValid(child.size() - 1)) { + null_index--; + } else { + UnifiedVectorFormat format; + child.ToUnifiedFormat(format); + if (!format.validity.CannotHaveNull()) { + for (idx_t i = 0; i < child.size(); i++) { + if (!format.validity.RowIsValid(format.sel->get_index(i))) { + null_index = i; + break; + } + } + } + } + + { + auto &buffer = vector.BufferMutable().Cast(); + auto &selection = buffer.GetSelVector(); + if (vector.GetBufferRef().use_count() != 1 || !selection.sel_data() || selection.sel_data().use_count() != 1) { + SelectionVector owned_selection(count); + for (idx_t i = 0; i < count; i++) { + owned_selection.set_index(i, selection.get_index(i)); + } + vector.Dictionary(buffer.GetEntryPtr(), owned_selection, count); + } + } + if (null_index == child.size()) { + // Copy dictionary entries, leaving the original dictionary and its caches unchanged. + auto entry = make_buffer(Vector(vector.GetType(), child.size() + 1)); + VectorOperations::Copy(child, entry->data, child.size(), 0, 0); + FlatVector::SetSize(entry->data, child.size() + 1); + FlatVector::SetNull(entry->data, null_index, true); + vector.BufferMutable().Cast().SetEntry(std::move(entry)); + } + unsafe_array_ptr target(SelVector(vector).data(), count); + const auto null_code = NumericCast(null_index); + auto apply_invalid = [&](idx_t entry_idx, validity_t invalid) { + const auto start = entry_idx * ValidityMask::BITS_PER_VALUE; + while (invalid) { + target[start + CountZeros::Trailing(invalid)] = null_code; + invalid &= invalid - 1; + } + }; + for (idx_t entry_idx = first_invalid; entry_idx < full_entry_count; entry_idx++) { + apply_invalid(entry_idx, ~validity[entry_idx]); + } + apply_invalid(full_entry_count, tail_invalid); +} + bool DictionaryBuffer::TrySerialize(Serializer &serializer, const LogicalType &type, bool compressed_serialization) const { auto dictionary_size = GetDictionarySize(); diff --git a/src/duckdb/src/execution/index/art/art.cpp b/src/duckdb/src/execution/index/art/art.cpp index 44b43606b..c50ab1693 100644 --- a/src/duckdb/src/execution/index/art/art.cpp +++ b/src/duckdb/src/execution/index/art/art.cpp @@ -1615,9 +1615,11 @@ void ART::Verify(IndexLock &l) { } void ART::VerifyInternal() { +#ifdef D_ASSERT_IS_ENABLED if (root_ptr.HasMetadata()) { root_ptr.Verify(*this); } +#endif } void ART::VerifyAllocations(IndexLock &l) { diff --git a/src/duckdb/src/function/function_list.cpp b/src/duckdb/src/function/function_list.cpp index 7ccb70c28..ae4eea669 100644 --- a/src/duckdb/src/function/function_list.cpp +++ b/src/duckdb/src/function/function_list.cpp @@ -286,6 +286,7 @@ static const StaticFunctionDefinition function[] = { DUCKDB_SCALAR_FUNCTION(VariantNormalizeFun), DUCKDB_SCALAR_FUNCTION_SET(VariantTypeFun), DUCKDB_SCALAR_FUNCTION(VariantTypeofFun), + DUCKDB_SCALAR_FUNCTION_SET(VariantValueFun), DUCKDB_SCALAR_FUNCTION_SET(VertexExtractFun), DUCKDB_SCALAR_FUNCTION_SET(WriteLogFun), DUCKDB_SCALAR_FUNCTION(ConcatOperatorFun), 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 271277237..8e1394d83 100644 --- a/src/duckdb/src/function/scalar/variant/variant_bind_utils.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_bind_utils.cpp @@ -21,6 +21,9 @@ VariantPathBindData::VariantPathBindData(const vector &input_paths) : Fu } } } +VariantPathBindData::VariantPathBindData(int64_t index) : FunctionData() { + paths.push_back({VariantPathComponent(index)}); +} unique_ptr VariantPathBindData::Copy() const { return make_uniq(*this); @@ -75,14 +78,15 @@ unique_ptr VariantBindUtils::VariantPathBind(BindScalarFunctionInp const auto &path_expr = *arguments[1]; const auto &return_type = path_expr.GetReturnType(); - if (return_type.id() != LogicalTypeId::VARCHAR && return_type.id() != LogicalTypeId::LIST) { - throw BinderException("%s expects the second argument to be of type VARCHAR or VARCHAR[], not %s", + if (return_type.id() != LogicalTypeId::VARCHAR && return_type.id() != LogicalTypeId::LIST && + return_type.id() != LogicalTypeId::BIGINT) { + throw BinderException("%s expects the second argument to be of type VARCHAR, VARCHAR[] or BIGINT, not %s", function_name, return_type.ToString()); } if (return_type.id() == LogicalTypeId::LIST) { const auto child_type_id = ListType::GetChildType(return_type).id(); if (child_type_id != LogicalTypeId::VARCHAR && child_type_id != LogicalTypeId::SQLNULL) { - throw BinderException("%s expects the second argument to be of type VARCHAR or VARCHAR[], not %s", + throw BinderException("%s expects the second argument to be of type VARCHAR, VARCHAR[] or BIGINT, not %s", function_name, return_type.ToString()); } } @@ -96,6 +100,9 @@ unique_ptr VariantBindUtils::VariantPathBind(BindScalarFunctionInp if (path_type_id == LogicalTypeId::LIST) { return make_uniq(CollectPaths(constant_arg, function_name.GetIdentifierName())); } + if (path_type_id == LogicalTypeId::BIGINT) { + return make_uniq(constant_arg.GetValue()); + } throw BinderException("%s received an unexpected type for the second argument", function_name); } diff --git a/src/duckdb/src/function/scalar/variant/variant_contains.cpp b/src/duckdb/src/function/scalar/variant/variant_contains.cpp index 257cfde3f..ec7eb410b 100644 --- a/src/duckdb/src/function/scalar/variant/variant_contains.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_contains.cpp @@ -1,4 +1,6 @@ #include "duckdb/common/radix.hpp" +#include "duckdb/common/optional.hpp" +#include "duckdb/common/types.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/types/variant_iterator.hpp" #include "duckdb/common/types/variant_comparison.hpp" @@ -6,118 +8,396 @@ namespace duckdb { -static bool IsEqual(const VariantNode &haystack, const VariantNode &needle); +namespace { -static bool IsObjectEqual(const VariantNode &haystack, const VariantNode &needle) { - // for every needle we need to find an occurrence in the haystack - // elements in the haystack are not consumed, so multiple needles can be satisfied by one haystack element - for (const auto &needle_child : needle.GetObjectChildren()) { - auto found = false; - for (const auto &haystack_child : haystack.GetObjectChildren()) { - if (needle_child.key != haystack_child.key) { - continue; - } - if (IsEqual(haystack_child.value, needle_child.value)) { - found = true; - break; - } - } - if (!found) { - return false; - } +//===--------------------------------------------------------------------===// +// Comparing primitive values +//===--------------------------------------------------------------------===// + +//! The value that is looked for, with its type. The key a NUMBER is compared by is built once +struct VariantNeedle { + explicit VariantNeedle(const VariantNode &node_p) + : node(node_p), type_id(node.GetTypeId()), category(GetVariantComparisonType(type_id)) { } - return true; -} -static bool IsArrayEqual(const VariantNode &haystack, const VariantNode &needle) { - for (const auto &needle_child : needle.GetArrayChildren()) { - auto found = false; - for (const auto &haystack_child : haystack.GetArrayChildren()) { - if (IsEqual(haystack_child, needle_child)) { - found = true; - break; - } - } - if (!found) { - return false; + const VariantNumberKey &NumberKey() { + if (!number_key) { + number_key = VariantGetNumberKey(type_id, node); } + return *number_key; } - return true; -} -static bool IsEqual(const VariantNode &haystack, const VariantNode &needle) { - const auto haystack_type = haystack.GetTypeId(); - const auto needle_type = needle.GetTypeId(); - const auto haystack_category = GetVariantComparisonType(haystack_type); - if (haystack_category != GetVariantComparisonType(needle_type)) { - return false; - } + VariantNode node; + VariantLogicalType type_id; + VariantComparisonType category; + optional number_key; +}; - switch (haystack_category) { - case VariantComparisonType::ARRAY: - return IsArrayEqual(haystack, needle); - case VariantComparisonType::OBJECT: - return IsObjectEqual(haystack, needle); +//! Whether two primitive values of the same comparison category are equal +bool IsPrimitiveEqual(const VariantNode &haystack, VariantLogicalType haystack_type, VariantNeedle &needle) { + switch (needle.category) { case VariantComparisonType::NULL_VALUE: return true; case VariantComparisonType::BOOLEAN: - return haystack.GetTypeId() == needle.GetTypeId(); + return haystack_type == needle.type_id; case VariantComparisonType::UUID: - return haystack.GetData() == needle.GetData(); + return haystack.GetData() == needle.node.GetData(); case VariantComparisonType::REAL: // we need to encode so NaN == NaN, -0.0 == 0.0, and infinity == infinity return Radix::EncodeDouble(VariantGetRealValue(haystack_type, haystack)) == - Radix::EncodeDouble(VariantGetRealValue(needle_type, needle)); + Radix::EncodeDouble(VariantGetRealValue(needle.type_id, needle.node)); case VariantComparisonType::NUMBER: - return VariantGetNumberKey(haystack_type, haystack) == VariantGetNumberKey(needle_type, needle); + return VariantGetNumberKey(haystack_type, haystack) == needle.NumberKey(); case VariantComparisonType::TIME: - return VariantGetTimeValue(haystack_type, haystack) == VariantGetTimeValue(needle_type, needle); + return VariantGetTimeValue(haystack_type, haystack) == VariantGetTimeValue(needle.type_id, needle.node); case VariantComparisonType::TIME_TZ: - return haystack.GetData() == needle.GetData(); + return haystack.GetData() == needle.node.GetData(); case VariantComparisonType::TIMESTAMP: - return VariantGetTimestampValue(haystack_type, haystack) == VariantGetTimestampValue(needle_type, needle); + return VariantGetTimestampValue(haystack_type, haystack) == + VariantGetTimestampValue(needle.type_id, needle.node); case VariantComparisonType::TIMESTAMP_TZ: - return VariantGetTimestampTZValue(haystack_type, haystack) == VariantGetTimestampTZValue(needle_type, needle); + return VariantGetTimestampTZValue(haystack_type, haystack) == + VariantGetTimestampTZValue(needle.type_id, needle.node); case VariantComparisonType::INTERVAL: - return haystack.GetData() == needle.GetData(); + return haystack.GetData() == needle.node.GetData(); case VariantComparisonType::BLOB: case VariantComparisonType::BITSTRING: case VariantComparisonType::GEOMETRY: case VariantComparisonType::GEOGRAPHY: case VariantComparisonType::VARCHAR: - return haystack.GetString() == needle.GetString(); + return haystack.GetString() == needle.node.GetString(); + default: + return false; } +} - return false; +//===--------------------------------------------------------------------===// +// Matching arrays and objects +//===--------------------------------------------------------------------===// +// A haystack array or object matches a needle one when every child of the needle is matched by a child of the +// haystack. Haystack children are not consumed, so one can match several needle children. + +//! The pairs of elements to compare for two arrays: every haystack element is a candidate for a needle element +class VariantArrayMatch { +public: + VariantArrayMatch(const VariantNode &haystack, const VariantNode &needle) + : haystack_elements(haystack.GetArrayChildren()), needle_elements(needle.GetArrayChildren()) { + } + + //! Returns false when all needle elements are matched, or the current one has no candidate left + bool NextPair(VariantNode &haystack_child, VariantNode &needle_child) const { + if (AllMatched() || candidate_index == haystack_elements.size()) { + return false; + } + haystack_child = haystack_elements[candidate_index]; + needle_child = needle_elements[needle_index]; + return true; + } + + void PairCompared(bool matched) { + if (!matched) { + candidate_index++; + return; + } + needle_index++; + candidate_index = 0; + } + + bool AllMatched() const { + return needle_index == needle_elements.size(); + } + +private: + VariantArrayIterator haystack_elements; + VariantArrayIterator needle_elements; + idx_t needle_index = 0; + idx_t candidate_index = 0; +}; + +//! The pairs of values to compare for two objects: only a haystack entry with the same key is a candidate for a +//! needle entry. Entries are taken by raw position, skipping the fields that are missing in the row +class VariantObjectMatch { +public: + VariantObjectMatch(const VariantNode &haystack, const VariantNode &needle) + : haystack_entries(haystack, VariantIterationOrder::INTERNAL), + needle_entries(needle, VariantIterationOrder::INTERNAL) { + } + + //! Returns false when all needle entries are matched, or the current one has no candidate left + bool NextPair(VariantNode &haystack_child, VariantNode &needle_child) { + VariantObjectEntry needle_entry; + if (!NextNeedleEntry(needle_entry)) { + return false; + } + if (!NextCandidate(needle_entry.key, haystack_child)) { + return false; + } + needle_child = needle_entry.value; + return true; + } + + void PairCompared(bool matched) { + if (!matched) { + candidates_tried++; + return; + } + // objects often hold their keys in the same order, so the next key is looked for after this match + const auto haystack_count = haystack_entries.GetRawCount(); + first_candidate = CandidatePosition(haystack_count) + 1; + if (first_candidate == haystack_count) { + first_candidate = 0; + } + candidates_tried = 0; + needle_index++; + } + + //! Only holds once NextPair has returned false, as that skips the missing needle fields + bool AllMatched() const { + return needle_index == needle_entries.GetRawCount(); + } + +private: + bool NextNeedleEntry(VariantObjectEntry &needle_entry) { + for (; needle_index < needle_entries.GetRawCount(); needle_index++) { + needle_entry = needle_entries.RawEntry(needle_index); + if (!needle_entry.value.IsMissing()) { + return true; + } + } + return false; + } + + //! Finds the next haystack entry with the key + bool NextCandidate(const string_t &key, VariantNode &haystack_child) { + const auto haystack_count = haystack_entries.GetRawCount(); + for (; candidates_tried < haystack_count; candidates_tried++) { + const auto haystack_entry = haystack_entries.RawEntry(CandidatePosition(haystack_count)); + if (haystack_entry.value.IsMissing() || haystack_entry.key != key) { + continue; + } + haystack_child = haystack_entry.value; + return true; + } + return false; + } + + //! Candidates are tried at a growing distance from the first one, alternately after and before it and wrapping + //! around, so that every haystack entry is tried once + idx_t CandidatePosition(idx_t haystack_count) const { + const auto distance = (candidates_tried + 1) / 2; + const auto after = candidates_tried % 2 == 0; + if (after) { + const auto position = first_candidate + distance; + return position < haystack_count ? position : position - haystack_count; + } + return first_candidate >= distance ? first_candidate - distance : first_candidate + haystack_count - distance; + } + +private: + VariantObjectIterator haystack_entries; + VariantObjectIterator needle_entries; + idx_t needle_index = 0; + //! The raw position of the first haystack entry tried for the needle entry, and how many are tried + idx_t first_candidate = 0; + idx_t candidates_tried = 0; +}; + +//! Proxy frame for two arrays or two objects whose children are being compared +class VariantMatchFrame { +public: + VariantMatchFrame(const VariantNode &haystack, const VariantNode &needle, VariantComparisonType category) { + if (category == VariantComparisonType::ARRAY) { + arrays.emplace(haystack, needle); + } else { + objects.emplace(haystack, needle); + } + } + + bool NextPair(VariantNode &haystack_child, VariantNode &needle_child) { + if (arrays) { + return arrays->NextPair(haystack_child, needle_child); + } + return objects->NextPair(haystack_child, needle_child); + } + + //! Moves on to the next needle child if the pair matched, and to its next candidate otherwise + void PairCompared(bool matched) { + if (arrays) { + arrays->PairCompared(matched); + return; + } + objects->PairCompared(matched); + } + + bool AllMatched() const { + return arrays ? arrays->AllMatched() : objects->AllMatched(); + } + +private: + optional arrays; + optional objects; +}; + +bool IsArrayOrObject(VariantComparisonType category) { + return category == VariantComparisonType::ARRAY || category == VariantComparisonType::OBJECT; +} + +//! Whether the haystack array or object matches the needle one. +bool ChildrenMatch(const VariantNode &haystack, const VariantNode &needle, VariantComparisonType category, + vector &frames) { + frames.clear(); + frames.emplace_back(haystack, needle, category); + + while (true) { + auto &frame = frames.back(); + VariantNode haystack_child; + VariantNode needle_child_node; + + if (!frame.NextPair(haystack_child, needle_child_node)) { + // the frame is finished, which decides the pair that it was opened for + const auto matched = frame.AllMatched(); + frames.pop_back(); + if (frames.empty()) { + return matched; + } + frames.back().PairCompared(matched); + continue; + } + + VariantNeedle needle_child(needle_child_node); + const auto haystack_child_type = haystack_child.GetTypeId(); + const auto child_category = GetVariantComparisonType(haystack_child_type); + + if (child_category != needle_child.category) { + frame.PairCompared(false); + continue; + } + if (IsArrayOrObject(child_category)) { + // the frame is not used after this, as opening another may move it + frames.emplace_back(haystack_child, needle_child_node, child_category); + continue; + } + + frame.PairCompared(IsPrimitiveEqual(haystack_child, haystack_child_type, needle_child)); + } } -static bool RecursiveHaystackWalk(const VariantNode &haystack, const VariantNode &needle) { - if (IsEqual(haystack, needle)) { +//! Whether the haystack value itself matches the needle +bool MatchesNeedle(const VariantNode &haystack, VariantLogicalType haystack_type, VariantNeedle &needle, + vector &frames) { + const auto category = GetVariantComparisonType(haystack_type); + if (category != needle.category) { + return false; + } + if (IsArrayOrObject(category)) { + return ChildrenMatch(haystack, needle.node, category, frames); + } + return IsPrimitiveEqual(haystack, haystack_type, needle); +} + +//===--------------------------------------------------------------------===// +// Searching the haystack +//===--------------------------------------------------------------------===// + +//! An array or object of the haystack, with the child to visit next +class VariantWalkFrame { +public: + VariantWalkFrame(const VariantNode &container, VariantLogicalType type_id) { + if (type_id == VariantLogicalType::ARRAY) { + elements.emplace(container.GetArrayChildren()); + } else { + entries.emplace(container, VariantIterationOrder::INTERNAL); + } + } + + bool NextChild(VariantNode &child) { + return elements ? NextElement(child) : NextEntryValue(child); + } + +private: + bool NextElement(VariantNode &child) { + if (next_index == elements->size()) { + return false; + } + child = (*elements)[next_index++]; return true; } - switch (haystack.GetTypeId()) { - case VariantLogicalType::ARRAY: - for (const auto &child : haystack.GetArrayChildren()) { - if (RecursiveHaystackWalk(child, needle)) { + bool NextEntryValue(VariantNode &child) { + while (next_index < entries->GetRawCount()) { + child = entries->RawEntry(next_index++).value; + // Shredded values may have missing object keys for a given row + if (!child.IsMissing()) { return true; } } - break; - case VariantLogicalType::OBJECT: - for (const auto &child : haystack.GetObjectChildren()) { - if (RecursiveHaystackWalk(child.value, needle)) { + return false; + } + +private: + optional elements; + optional entries; + idx_t next_index = 0; +}; + +//! Visits the haystack value and then every value nested in it, depth first. +class VariantHaystackWalk { +public: + VariantHaystackWalk(const VariantNode &haystack, vector &frames) + : frames(frames), value(haystack), type_id(haystack.GetTypeId()) { + frames.clear(); + } + + //! Moves to the next value, which is the first child of the current one if it has any + bool Next() { + if (type_id == VariantLogicalType::ARRAY || type_id == VariantLogicalType::OBJECT) { + frames.emplace_back(value, type_id); + } + while (!frames.empty()) { + if (frames.back().NextChild(value)) { + type_id = value.GetTypeId(); return true; } + frames.pop_back(); } - break; - default: return false; } + const VariantNode &Value() const { + return value; + } + VariantLogicalType Type() const { + return type_id; + } + +private: + vector &frames; + VariantNode value; + VariantLogicalType type_id; +}; + +//! The stacks of a given needle-haystack search +struct VariantContainsState { + vector match_frames; + vector walk_frames; +}; + +//! Whether the haystack value or any value nested in it matches the needle +bool HaystackContains(const VariantNode &haystack, const VariantNode &needle_node, VariantContainsState &state) { + VariantNeedle needle(needle_node); + VariantHaystackWalk walk(haystack, state.walk_frames); + + do { + if (MatchesNeedle(walk.Value(), walk.Type(), needle, state.match_frames)) { + return true; + } + } while (walk.Next()); + return false; } +} // namespace + static void VariantContainsFunction(DataChunk &input, ExpressionState &state, Vector &result) { D_ASSERT(input.ColumnCount() == 2); (void)state; @@ -129,20 +409,20 @@ static void VariantContainsFunction(DataChunk &input, ExpressionState &state, Ve result.Initialize(VectorDataInitialization::UNINITIALIZED, count); auto result_writer = FlatVector::Writer(result, count); + VariantContainsState search_state; for (idx_t row_idx = 0; row_idx < count; row_idx++) { if (!haystacks.RowIsValid(row_idx) || !needles.RowIsValid(row_idx)) { result_writer.WriteNull(); continue; } - result_writer.WriteValue(RecursiveHaystackWalk(haystacks[row_idx], needles[row_idx])); + result_writer.WriteValue(HaystackContains(haystacks[row_idx], needles[row_idx], search_state)); } } ScalarFunctionSet VariantContainsFun::GetFunctions() { - ScalarFunction function("variant_contains", {}, LogicalType::BOOLEAN, VariantContainsFunction); - function.GetSignature() - .AddParameter("variant_haystack", LogicalType::VARIANT()) - .AddParameter("variant_needle", LogicalType::VARIANT()); + ScalarFunction function("variant_contains", + {{"variant_haystack", LogicalType::VARIANT()}, {"variant_needle", LogicalType::VARIANT()}}, + LogicalType::BOOLEAN, VariantContainsFunction); return ScalarFunctionSet(function); } 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 9d98fb3db..47e66de2a 100644 --- a/src/duckdb/src/function/scalar/variant/variant_path_function.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_path_function.cpp @@ -1,7 +1,166 @@ #include "duckdb/function/scalar/variant_path_function.hpp" +#include "duckdb/common/types/variant/variant_builder.hpp" +#include "duckdb/common/vector/list_vector.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 != VariantLogicalType::OBJECT && type != VariantLogicalType::ARRAY) { + builder.EmitPrimitiveNode(node, type); + 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() != VariantLogicalType::ARRAY) { + return {}; + } + const auto elements = node.GetArrayChildren(); + const auto length = elements.size(); + if (index >= 0) { + if (static_cast(index) >= length) { + return {}; + } + return elements[static_cast(index)]; + } + // -(index + 1) cannot overflow for the minimum int64_t + const auto from_end = static_cast(-(index + 1)); + if (from_end >= length) { + return {}; + } + 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 {}; + } + return ResolvePath(variants[row], path); + }); +} + +void VariantPathFunction::ExecuteVariantMany(const Vector &input, const vector> &paths, + Vector &result, idx_t count, variant_node_filter_t keep) { + const VectorIterator variants(input); + const auto path_count = paths.size(); + + //! 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; + 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++; + } + } + + 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() != VariantLogicalType::OBJECT) { + 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]; + if (keys[path_idx] && !value && *keys[path_idx] == 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, const LogicalType &return_type, const bool path_optional, const init_local_state_t init_state) { diff --git a/src/duckdb/src/function/scalar/variant/variant_utils.cpp b/src/duckdb/src/function/scalar/variant/variant_utils.cpp index b2ceb64f8..899cfb65a 100644 --- a/src/duckdb/src/function/scalar/variant/variant_utils.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_utils.cpp @@ -127,7 +127,8 @@ void VariantUtils::FindChildValues(const UnifiedVariantVectorData &variant, cons } auto &nested_data_entry = nested_data[i]; if (component.lookup_mode == VariantChildLookupMode::BY_INDEX) { - auto child_idx = component.index; + D_ASSERT(component.index >= 0); + auto child_idx = static_cast(component.index); if (child_idx >= nested_data_entry.child_count) { //! The list is too small to contain this index res_validity.SetInvalid(i); diff --git a/src/duckdb/src/function/scalar/variant/variant_value.cpp b/src/duckdb/src/function/scalar/variant/variant_value.cpp new file mode 100644 index 000000000..17a369e1c --- /dev/null +++ b/src/duckdb/src/function/scalar/variant/variant_value.cpp @@ -0,0 +1,43 @@ +#include "duckdb/common/types/variant_iterator.hpp" +#include "duckdb/function/scalar/variant_functions.hpp" +#include "duckdb/function/scalar/variant_path_function.hpp" +#include "duckdb/function/scalar/variant_utils.hpp" + +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()) { + case VariantLogicalType::VARIANT_NULL: + case VariantLogicalType::OBJECT: + case VariantLogicalType::ARRAY: + return false; + default: + return true; + } +} + +void VariantValueFunction(DataChunk &input, ExpressionState &state, Vector &result) { + VariantPathFunction::ExecuteVariant(input, state, result, IsScalarValue); +} + +} // namespace + +ScalarFunctionSet VariantValueFun::GetFunctions() { + auto set = + VariantPathFunction::CreateFunctionSet("variant_value", VariantValueFunction, LogicalType::VARIANT(), false); + + ScalarFunction index_fun({}, LogicalType::VARIANT(), VariantValueFunction, VariantBindUtils::VariantPathBind); + index_fun.GetSignature() + .AddParameter("input_variant", LogicalType::VARIANT()) + .AddParameter("index", LogicalType::BIGINT); + set.AddFunction(std::move(index_fun)); + return set; +} + +} // namespace duckdb diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index d67a25499..a4cb72041 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-alpha57387" +#define DUCKDB_PATCH_VERSION "0-alpha57486" #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-alpha57387" +#define DUCKDB_VERSION "v2.1.0-alpha57486" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "eb318174fa" +#define DUCKDB_SOURCE_ID "f0b39a6d67" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/include/duckdb/common/enums/database_modification_type.hpp b/src/duckdb/src/include/duckdb/common/enums/database_modification_type.hpp index 15950d302..6fbfdc244 100644 --- a/src/duckdb/src/include/duckdb/common/enums/database_modification_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/database_modification_type.hpp @@ -19,9 +19,9 @@ struct DatabaseModificationType { static constexpr idx_t UPDATE_DATA = 1ULL << 2ULL; //! An ALTER TABLE that may change table storage: not renames, defaults, DROP NOT NULL or comments static constexpr idx_t ALTER_TABLE = 1ULL << 3ULL; - //! Creating a table, index or trigger, or replacing a schema: not entries without table storage + //! Creating or replacing a table with indexes, or COPY FROM DATABASE static constexpr idx_t CREATE_CATALOG_ENTRY = 1ULL << 4ULL; - //! Dropping a table, index or trigger, or anything with CASCADE: not entries without table storage + //! Dropping an index or a table with indexes, or anything with CASCADE static constexpr idx_t DROP_CATALOG_ENTRY = 1ULL << 5ULL; static constexpr idx_t SEQUENCE = 1ULL << 6ULL; static constexpr idx_t CREATE_INDEX = 1ULL << 7ULL; diff --git a/src/duckdb/src/include/duckdb/common/type_visitor.hpp b/src/duckdb/src/include/duckdb/common/type_visitor.hpp index 7d1e5329f..2d9c08fe8 100644 --- a/src/duckdb/src/include/duckdb/common/type_visitor.hpp +++ b/src/duckdb/src/include/duckdb/common/type_visitor.hpp @@ -140,6 +140,10 @@ inline LogicalType TypeVisitor::VisitReplace(const LogicalType &type, F &&func) template inline bool TypeVisitor::Contains(const LogicalType &type, F &&predicate) { + if (!type.HasParameters()) { + // a type without parameters has no children + return predicate(type); + } vector> worklist {type}; while (!worklist.empty()) { diff --git a/src/duckdb/src/include/duckdb/common/types/variant.hpp b/src/duckdb/src/include/duckdb/common/types/variant.hpp index c83672df7..ca2dcc989 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant.hpp @@ -40,7 +40,7 @@ struct VariantPathComponent { } explicit VariantPathComponent(const string &key) : lookup_mode(VariantChildLookupMode::BY_KEY), key(key) { } - explicit VariantPathComponent(uint32_t index) : lookup_mode(VariantChildLookupMode::BY_INDEX), index(index) { + explicit VariantPathComponent(int64_t index) : lookup_mode(VariantChildLookupMode::BY_INDEX), index(index) { } bool operator==(const VariantPathComponent &other) const { @@ -63,7 +63,8 @@ struct VariantPathComponent { public: VariantChildLookupMode lookup_mode; string key; - uint32_t index; + //! 0-based, negative indexes count from the end of the array + int64_t index; }; struct VariantNestedData { diff --git a/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp b/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp index 66fde704d..4f11f9621 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp @@ -336,9 +336,14 @@ class VariantObjectIterator { return ordered_entries; } -private: + //! The number of raw entries, including the fields missing in this row + idx_t GetRawCount() const { + return raw_count; + } //! Materializes the entry at the given raw position (before missing-field skipping) VariantObjectEntry RawEntry(idx_t raw_pos) const; + +private: //! The end position in the iteration space idx_t EndPos() const { return order == VariantIterationOrder::LEXICOGRAPHIC ? ordered_entries.size() : raw_count; diff --git a/src/duckdb/src/include/duckdb/common/vector/dictionary_vector.hpp b/src/duckdb/src/include/duckdb/common/vector/dictionary_vector.hpp index 6a172803c..cb183be58 100644 --- a/src/duckdb/src/include/duckdb/common/vector/dictionary_vector.hpp +++ b/src/duckdb/src/include/duckdb/common/vector/dictionary_vector.hpp @@ -169,6 +169,10 @@ struct DictionaryVector { return vector.Buffer().Cast().GetEntry().global_dictionary; } static const Vector &GetCachedHashes(const Vector &input); + //! Combine row validity while preserving dictionary encoding and existing NULLs. + //! The mask must cover vector.size() rows and is not retained. + //! May replace the selection buffer or dictionary entry. + static void ApplyValidity(Vector &vector, const ValidityMask &mask); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/aggregate_function.hpp b/src/duckdb/src/include/duckdb/function/aggregate_function.hpp index cd1fad5bd..e4800fb85 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate_function.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate_function.hpp @@ -933,6 +933,10 @@ class BoundAggregateFunction : public BaseAggregateFunction, public BoundSimpleF const LogicalType &GetLogicalReturnType() const { return logical_return_type; } + //! Whether EXPORT_STATE replaced the return type + bool ReturnsExportedState() const { + return GetReturnType().IsAggregateState() && GetReturnType() != logical_return_type; + } AggregateStateLayout GetStateType(optional_ptr bind_data) const { D_ASSERT(callbacks.get_state_type); AggregateLayoutInput input(*this, bind_data); @@ -978,7 +982,7 @@ inline AggregateStateLayout AggregateFunction::StructStateLayout(AggregateLayout using ST = typename STATE::STATE_TYPE; auto &bound = input.function; AggregateStateLayout layout; - if (bound.GetReturnType().IsAggregateState()) { + if (bound.ReturnsExportedState()) { // the function has been modified for state export (see ExportAggregateFunction::SetStateExport) - // its return type IS the state type already layout.type = bound.GetReturnType(); diff --git a/src/duckdb/src/include/duckdb/function/scalar/variant_functions.hpp b/src/duckdb/src/include/duckdb/function/scalar/variant_functions.hpp index 2115c3906..0ba9e9ae4 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/variant_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/variant_functions.hpp @@ -105,6 +105,16 @@ struct VariantTypeofFun { static ScalarFunction GetFunction(); }; +struct VariantValueFun { + static constexpr const char *Name = "variant_value"; + static constexpr const char *Parameters = "input_variant::VARIANT,path::VARCHAR\001input_variant::VARIANT,path::VARCHAR[]\001input_variant::VARIANT,index::BIGINT"; + static constexpr const char *Description = "Returns the scalar value at `path` in the `input_variant`, or `NULL` if it is an OBJECT, ARRAY or null.\001Returns the scalar value at each `path` in the `input_variant`, or `NULL` where it is an OBJECT, ARRAY or null.\001Returns the scalar element at the 0-based `index` of the `input_variant` if it's an ARRAY, negative indexes count from the end."; + static constexpr const char *Example = "variant_value({'a': 42, 'b': [1, 2, 3]}::VARIANT, 'a')\001variant_value({'a': 42, 'b': [1, 2, 3]}::VARIANT, ['a', 'b'])\001variant_value([1, 2, 3]::VARIANT, -1)"; + static constexpr const char *Categories = "variant\001variant\001variant"; + + static ScalarFunctionSet GetFunctions(); +}; + struct VariantKeysFun { static constexpr const char *Name = "variant_keys"; static constexpr const char *Parameters = "input_variant::VARIANT\001input_variant::VARIANT,path::VARCHAR\001input_variant::VARIANT,path::VARCHAR[]"; 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 a9184d79d..2b8d3c485 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 @@ -15,6 +15,9 @@ 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, @@ -59,6 +62,13 @@ struct VariantPathFunction { } } + //! 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 @@ -105,17 +115,34 @@ struct VariantPathFunction { } } + //! 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 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. + static optional ResolveIndex(const VariantNode &node, int64_t index); + //! Walks the VARIANT using a path, which may be either (partially) shredded or unshredded. Returns nullopt if the //! path is missing in the VARIANT, and the present value with VariantNode otherwise. static optional ResolvePath(VariantNode node, const vector &path) { for (const auto &component : path) { - if (component.lookup_mode == VariantChildLookupMode::BY_INDEX) { - throw InternalException("Path indexes are not supported for this function"); - } if (node.IsNull() || node.IsMissing()) { return {}; } + if (component.lookup_mode == VariantChildLookupMode::BY_INDEX) { + auto element = ResolveIndex(node, component.index); + if (!element) { + return {}; + } + node = *element; + continue; + } + if (node.GetTypeId() != VariantLogicalType::OBJECT) { return {}; } 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 81dfca8d0..7a285e7a0 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/variant_utils.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/variant_utils.hpp @@ -22,6 +22,7 @@ struct VariantPathBindData : public FunctionData { explicit VariantPathBindData(); explicit VariantPathBindData(const string &input_path); explicit VariantPathBindData(const vector &input_paths); + explicit VariantPathBindData(int64_t index); VariantPathBindData(const VariantPathBindData &other) = default; public: 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 5813725b5..eed383294 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp @@ -1562,10 +1562,72 @@ typedef struct { 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_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); + DUCKDB_V2_ERROR (*duckdb_v2_crypto_cipher_destroy)(duckdb_v2_crypto_cipher_handle *stream); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_cipher_finalize) + (duckdb_v2_crypto_cipher_handle stream, uint8_t *tag, idx_t tag_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_cipher_init) + (duckdb_v2_crypto_cipher_handle stream, const uint8_t *iv, idx_t iv_length, const uint8_t *aad, idx_t aad_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_cipher_update) + (duckdb_v2_crypto_cipher_handle stream, const uint8_t *in, idx_t in_length, uint8_t *out, idx_t out_capacity, + idx_t *out_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_hash) + (duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, const uint8_t *data, idx_t length, + uint8_t *digest, idx_t digest_capacity, idx_t *digest_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_hash_digest_size) + (DUCKDB_V2_CRYPTO_HASH_FUNCTION function, idx_t *size, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_hmac) + (duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, const uint8_t *key, idx_t key_length, + const uint8_t *data, idx_t length, uint8_t *mac, idx_t mac_capacity, idx_t *mac_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_create) + (duckdb_v2_factory_handle factory, duckdb_v2_crypto_provider_handle *provider, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_crypto_provider_destroy)(duckdb_v2_crypto_provider_handle *provider); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_cipher_create_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_create_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_cipher_destroy_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_destroy_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_cipher_finalize_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_finalize_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_cipher_init_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_init_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_cipher_update_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_update_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_hash_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_hash_callback_fn callback, + const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_hmac_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_hmac_callback_fn callback, + const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_random_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_random_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_user_data) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_random_bytes) + (duckdb_v2_instance_handle instance, uint8_t *data, idx_t length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_supports_hash) + (duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_supports_hmac) + (duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_extension_register_crypto_provider) + (duckdb_v2_extension_handle extension, duckdb_v2_crypto_provider_handle provider, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_secret_function) (duckdb_v2_extension_handle extension, duckdb_v2_secret_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_get_object_cache) (duckdb_v2_instance_handle instance, duckdb_v2_object_cache_handle *cache, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_instance_register_crypto_provider) + (duckdb_v2_instance_handle instance, duckdb_v2_crypto_provider_handle provider, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_object_cache_delete) (duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, const char *key, idx_t key_length, duckdb_v2_error_info_handle *err); @@ -1648,6 +1710,9 @@ typedef struct { const idx_t *option_names_lengths, const char *const *option_values, const idx_t *option_values_lengths, idx_t option_count, duckdb_v2_instance_init_callback_fn init, void *init_user_data, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); + 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_ext_api_v2; //===--------------------------------------------------------------------===// @@ -2355,8 +2420,34 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_context_get_object_cache = duckdb_v2_context_get_object_cache; result.duckdb_v2_context_get_secret_by_name = duckdb_v2_context_get_secret_by_name; result.duckdb_v2_context_lookup_secret = duckdb_v2_context_lookup_secret; + result.duckdb_v2_crypto_cipher_create = duckdb_v2_crypto_cipher_create; + result.duckdb_v2_crypto_cipher_destroy = duckdb_v2_crypto_cipher_destroy; + result.duckdb_v2_crypto_cipher_finalize = duckdb_v2_crypto_cipher_finalize; + result.duckdb_v2_crypto_cipher_init = duckdb_v2_crypto_cipher_init; + result.duckdb_v2_crypto_cipher_update = duckdb_v2_crypto_cipher_update; + result.duckdb_v2_crypto_hash = duckdb_v2_crypto_hash; + result.duckdb_v2_crypto_hash_digest_size = duckdb_v2_crypto_hash_digest_size; + result.duckdb_v2_crypto_hmac = duckdb_v2_crypto_hmac; + result.duckdb_v2_crypto_provider_create = duckdb_v2_crypto_provider_create; + result.duckdb_v2_crypto_provider_destroy = duckdb_v2_crypto_provider_destroy; + result.duckdb_v2_crypto_provider_set_cipher_create_callback = duckdb_v2_crypto_provider_set_cipher_create_callback; + result.duckdb_v2_crypto_provider_set_cipher_destroy_callback = + duckdb_v2_crypto_provider_set_cipher_destroy_callback; + result.duckdb_v2_crypto_provider_set_cipher_finalize_callback = + duckdb_v2_crypto_provider_set_cipher_finalize_callback; + result.duckdb_v2_crypto_provider_set_cipher_init_callback = duckdb_v2_crypto_provider_set_cipher_init_callback; + result.duckdb_v2_crypto_provider_set_cipher_update_callback = duckdb_v2_crypto_provider_set_cipher_update_callback; + result.duckdb_v2_crypto_provider_set_hash_callback = duckdb_v2_crypto_provider_set_hash_callback; + result.duckdb_v2_crypto_provider_set_hmac_callback = duckdb_v2_crypto_provider_set_hmac_callback; + result.duckdb_v2_crypto_provider_set_random_callback = duckdb_v2_crypto_provider_set_random_callback; + result.duckdb_v2_crypto_provider_set_user_data = duckdb_v2_crypto_provider_set_user_data; + result.duckdb_v2_crypto_random_bytes = duckdb_v2_crypto_random_bytes; + result.duckdb_v2_crypto_supports_hash = duckdb_v2_crypto_supports_hash; + result.duckdb_v2_crypto_supports_hmac = duckdb_v2_crypto_supports_hmac; + result.duckdb_v2_extension_register_crypto_provider = duckdb_v2_extension_register_crypto_provider; result.duckdb_v2_extension_register_secret_function = duckdb_v2_extension_register_secret_function; result.duckdb_v2_instance_get_object_cache = duckdb_v2_instance_get_object_cache; + result.duckdb_v2_instance_register_crypto_provider = duckdb_v2_instance_register_crypto_provider; result.duckdb_v2_object_cache_delete = duckdb_v2_object_cache_delete; result.duckdb_v2_object_cache_entry_destroy = duckdb_v2_object_cache_entry_destroy; result.duckdb_v2_object_cache_entry_get_data = duckdb_v2_object_cache_entry_get_data; @@ -2390,6 +2481,7 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_table_function_to_string_get_user_data = duckdb_v2_table_function_to_string_get_user_data; 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; 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 4ee25e5d4..8a80ff006 100644 --- a/src/duckdb/src/include/duckdb/main/client_context.hpp +++ b/src/duckdb/src/include/duckdb/main/client_context.hpp @@ -253,9 +253,6 @@ class ClientContext : public enable_shared_from_this { //! parsed to be run; without it the transaction stays usable, as fits statements that are only inspected. DUCKDB_API StatementIterator IterateStatements(const string &query, bool apply_invalidation_policy = true); - //! Extract the logical plan of a query - DUCKDB_API unique_ptr ExtractPlan(const string &query); - //! Runs a function with a valid transaction context, potentially starting a transaction if the context is in auto //! commit mode. DUCKDB_API void RunFunctionInTransaction(const std::function &fun, diff --git a/src/duckdb/src/include/duckdb/main/connection.hpp b/src/duckdb/src/include/duckdb/main/connection.hpp index ee59f1ffd..838e9a048 100644 --- a/src/duckdb/src/include/duckdb/main/connection.hpp +++ b/src/duckdb/src/include/duckdb/main/connection.hpp @@ -137,8 +137,6 @@ class Connection { //! works as for ClientContext::IterateStatements. DUCKDB_API vector> ExtractStatements(const string &query, bool apply_invalidation_policy = true); - //! Extract the logical plan that corresponds to a query - DUCKDB_API unique_ptr ExtractPlan(const string &query); //! Appends a ColumnDataCollection to the described table. DUCKDB_API void Append(TableDescription &description, ColumnDataCollection &collection); diff --git a/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp b/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp index 52497ab0a..0c2ea14f4 100644 --- a/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp @@ -28,8 +28,9 @@ class LogicalProjection; enum class DistinctnessPropagation : uint8_t { //! Filters, limits, orderings, windows and projections UNARY_OPERATORS, - //! Additionally samples, the left side of SEMI / ANTI / MARK / SINGLE joins, and a side of an INNER join (the - //! left side of a LEFT join) whose other side is itself distinct on its equality keys + //! Additionally samples, the left side of SEMI / ANTI / MARK / SINGLE joins, a side of an INNER join (the + //! left side of a LEFT join) whose other side is itself distinct on its equality keys, and the query of a + //! materialized CTE (the output of the CTE operator is the output of the query that reads the CTE) UNARY_OPERATORS_AND_JOINS }; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp b/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp index 138ad22c9..3b1f31b1a 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp @@ -32,12 +32,9 @@ class PipelineInfo { //! operator (LIMIT, window, set operation, ...) ends it bool ignores_duplicates = false; - //! Found in this pipeline: a pushed-down filter condition (e.g. in a table scan operator) - bool has_filter = false; - public: - //! The state a pipeline below starts with: what is inherited from the operators above, nothing that was found. - //! Whether the pipeline below ignores duplicates is decided by the operator that starts it + //! The state a pipeline below starts with: the references of the operators above. Whether the pipeline below + //! ignores duplicates is decided by the operator that starts it PipelineInfo CreateChild() { auto result = PipelineInfo(); result.ref_table_ids = ref_table_ids; @@ -83,8 +80,9 @@ class JoinElimination : public LogicalOperatorVisitor { // 3. the join cannot change how often an outer row occurs in a way that is visible. There are two separate proofs: // a) the operators above ignore duplicates (PipelineInfo::ignores_duplicates): the join only repeats outer rows // b) every outer row matches at most one inner row: the inner side is distinct on the columns its equality - // conditions compare (Distinctness: a DISTINCT / GROUP BY, a PRIMARY KEY). This holds whatever is above the - // join. A SINGLE join is only removed by this proof: it raises an error on a second match. + // conditions compare (Distinctness: a DISTINCT / GROUP BY, a PRIMARY KEY, also below filters and as the + // result of an aggregate that was split into aggregates over a materialized CTE). This holds whatever is + // above the join. A SINGLE join is only removed by this proof: it raises an error on a second match. unique_ptr Optimize(unique_ptr op); //! Whether Optimize removed a join bool RemovedJoin() const; @@ -109,7 +107,7 @@ class JoinElimination : public LogicalOperatorVisitor { void OptimizeJoin(unique_ptr &op); void OptimizeJoinChild(LogicalOperator &join, idx_t child_idx, JoinElimination &child); //! Replaces the join `op` by its outer side when it can; returns whether it did - bool TryEliminateJoin(unique_ptr &op, JoinElimination &left_child, JoinElimination &right_child); + bool TryEliminateJoin(unique_ptr &op); PipelineInfo pipe_info; //! Shared by the optimizers of all pipelines of one plan diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/dphyp_enumerator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/dphyp_enumerator.hpp new file mode 100644 index 000000000..b092e2db7 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/dphyp_enumerator.hpp @@ -0,0 +1,47 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_order/dphyp_enumerator.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/join_order/join_order_candidate.hpp" +#include "duckdb/common/unordered_map.hpp" +#include "duckdb/common/unordered_set.hpp" + +namespace duckdb { + +//! Exact enumeration retains its memo across passes, resetting traversal state before a cross-product retry. +class DPHypEnumerator { +public: + DPHypEnumerator(QueryGraphManager &graph, const QueryGraphEdges &edges, JoinOrderCandidateEvaluator &evaluator, + JoinOrderPlanMap plans); + + //! Return true when traversal finishes, even if no complete plan exists; false when the pair budget is exhausted. + bool Solve(); + //! Reset the pair budget and neighbor cache for another pass, retaining the existing memo. + void ResetAfterGraphChange(); + const JoinOrderPlanMap &GetPlans() const; + JoinOrderPlanMap TakePlans(); + +private: + //! Return false when the exact pair limit is reached. + bool TryEmitPair(JoinRelationSet &left, JoinRelationSet &right, const vector> &info); + bool EmitCSG(JoinRelationSet &node); + bool EnumerateCmpRecursive(JoinRelationSet &left, JoinRelationSet &right, + unordered_set &exclusion_set); + bool EnumerateCSGRecursive(JoinRelationSet &node, unordered_set &exclusion_set); + const vector> &GetAllNeighborRelationSets(vector neighbors); + +private: + QueryGraphManager &query_graph_manager; + const QueryGraphEdges &query_graph; + JoinOrderCandidateEvaluator &evaluator; + JoinOrderPlanMap plans; + idx_t pairs = 0; + unordered_map>> neighbor_set_cache; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/greedy_join_enumerator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/greedy_join_enumerator.hpp new file mode 100644 index 000000000..08632728b --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/greedy_join_enumerator.hpp @@ -0,0 +1,28 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_order/greedy_join_enumerator.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/join_order/join_order_candidate.hpp" + +namespace duckdb { + +class GreedyJoinEnumerator { +public: + GreedyJoinEnumerator(QueryGraphManager &graph, JoinOrderCandidateEvaluator &evaluator); + + //! The driver initializes the input plan and selects the working memo before invoking greedy search. + //! Return true if all relations were merged into a complete plan, or false if greedy cannot complete the next + //! merge. + bool Solve(JoinOrderPlanMap &plans); + +private: + QueryGraphManager &query_graph_manager; + JoinOrderCandidateEvaluator &evaluator; +}; + +} // 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 new file mode 100644 index 000000000..7b4986411 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_candidate.hpp @@ -0,0 +1,54 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_order/join_order_candidate.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/reference_map.hpp" +#include "duckdb/optimizer/join_order/cost_model.hpp" +#include "duckdb/optimizer/join_order/join_node.hpp" +#include "duckdb/optimizer/join_order/query_graph.hpp" + +namespace duckdb { + +class QueryGraphManager; + +using JoinOrderPlanMap = reference_map_t>; + +//! Shared candidate semantics and query-lifetime connection state; search memos belong to callers. +class JoinOrderCandidateEvaluator { +public: + JoinOrderCandidateEvaluator(QueryGraphManager &graph, CostModel &cost_model, const QueryGraphEdges &edges); + + void InitLeafPlans(JoinOrderPlanMap &plans); + void InitInputPlan(JoinOrderPlanMap &plans); + JoinPlanCost GetPlanCost(const DPJoinNode &node) const; + //! Connection vectors are borrowed from the cache and invalidated when either operation below changes the graph. + const vector> &GetConnections(JoinRelationSet &left, JoinRelationSet &right); + //! Create an edge, invalidate cached connections, and return fresh connections for this pair. + const vector> &CreateCrossProduct(JoinRelationSet &left, JoinRelationSet &right); + //! Invalidate cached connections if required cross-product edges are activated. + bool ActivateRequiredCrossProducts(); + + //! Return the preferred plan for the union, or nullptr when the partition is invalid. + optional_ptr EmitPair(JoinOrderPlanMap &plans, JoinRelationSet &left, JoinRelationSet &right, + const vector> &connections); + +private: + unique_ptr CreateJoinTree(JoinRelationSet &set, const vector> &connections, + DPJoinNode &left, DPJoinNode &right); + optional_ptr ConsiderJoinTree(JoinOrderPlanMap &plans, unique_ptr candidate); + +private: + QueryGraphManager &query_graph_manager; + CostModel &cost_model; + const QueryGraphEdges &query_graph; + double recursive_frontier_estimate = 0; + reference_map_t>>> + connection_cache; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp index befc53a68..7d868ff61 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp @@ -8,86 +8,30 @@ #pragma once -#include "duckdb/common/unordered_map.hpp" -#include "duckdb/common/unordered_set.hpp" -#include "duckdb/optimizer/join_order/join_relation_set.hpp" -#include "duckdb/optimizer/join_order/cardinality_estimator.hpp" -#include "duckdb/optimizer/join_order/query_graph.hpp" -#include "duckdb/optimizer/join_order/join_node.hpp" -#include "duckdb/optimizer/join_order/cost_model.hpp" -#include "duckdb/parser/expression_map.hpp" -#include "duckdb/common/reference_map.hpp" -#include "duckdb/planner/logical_operator.hpp" -#include "duckdb/planner/logical_operator_visitor.hpp" - -#include +#include "duckdb/optimizer/join_order/join_order_candidate.hpp" namespace duckdb { -class QueryGraphManager; - class PlanEnumerator { public: explicit PlanEnumerator(QueryGraphManager &query_graph_manager, CostModel &cost_model, const QueryGraphEdges &query_graph); -public: - //! Perform the join order solving bool SolveJoinOrder(); void InitLeafPlans(); - - const reference_map_t> &GetPlans() const; + const JoinOrderPlanMap &GetPlans() const; private: - unique_ptr CreateJoinTree(JoinRelationSet &set, - const vector> &possible_connections, DPJoinNode &left, - DPJoinNode &right); - - //! Emit a pair as a potential join candidate. Returns the best plan found for the (left, right) connection (either - //! the newly created plan, or an existing plan). Returns nullptr if the partition violates a non-inner join's - //! semantic input sides. - optional_ptr EmitPair(JoinRelationSet &left, JoinRelationSet &right, - const vector> &info); - //! Tries to emit a potential join candidate pair. Returns false if too many pairs have already been emitted, - //! cancelling the dynamic programming step. - bool TryEmitPair(JoinRelationSet &left, JoinRelationSet &right, const vector> &info); - const vector> &GetConnections(JoinRelationSet &left, JoinRelationSet &right); - const vector> &GetAllNeighborRelationSets(vector neighbors); - - //! Estimated cardinality of the recursive frontier when planning inside a recursive member - double recursive_frontier_estimate = 0; - - bool EnumerateCmpRecursive(JoinRelationSet &left, JoinRelationSet &right, - unordered_set &exclusion_set); - //! Emit a relation set node - bool EmitCSG(JoinRelationSet &node); - //! Enumerate the possible connected subgraphs that can be joined together in the join graph - bool EnumerateCSGRecursive(JoinRelationSet &node, unordered_set &exclusion_set); - //! Solve the join order exactly using dynamic programming. Returns true if it was completed successfully (i.e. did - //! not time-out) - bool SolveJoinOrderExactly(); - //! Solve the join order approximately using a greedy algorithm bool SolveJoinOrderApproximately(); - bool PlanUsesCrossProduct(const DPJoinNode &node) const; - bool HasCompletePlan() const; - bool ActivateRequiredCrossProducts(); + bool HasCompletePlan(const JoinOrderPlanMap &memo) const; + bool PlanUsesCrossProduct(const JoinOrderPlanMap &memo, const DPJoinNode &node) const; private: - //! The set of edges used in the join optimizer - QueryGraphEdges const &query_graph; - //! The total amount of join pairs that have been considered - idx_t pairs = 0; - //! Grant access to the set manager and the relation manager QueryGraphManager &query_graph_manager; - //! Cost model to evaluate cost of joins - CostModel &cost_model; - //! A map to store the optimal join plan found for a specific JoinRelationSet* - reference_map_t> plans; - reference_map_t>>> - connection_cache; - unordered_map>> neighbor_set_cache; - - unordered_set join_nodes_in_full_plan; + const QueryGraphEdges &query_graph; + JoinOrderCandidateEvaluator candidate_evaluator; + //! Result storage also provides the initial leaves and outlives reconstruction. + JoinOrderPlanMap plans; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp b/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp index 4d9120cbe..51f98e0e9 100644 --- a/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp @@ -24,10 +24,14 @@ class MarkJoinSimplifier { private: void Rewrite(unique_ptr &op, NotNullExpressionAnalyzer &nullability, - BindingReplacementGraph &replacements); + BindingReplacementGraph &replacements, vector> &ancestors); bool TrySimplify(unique_ptr &op, NotNullExpressionAnalyzer &nullability, BindingReplacementGraph &replacements); + bool TrySimplifyDisjunction(unique_ptr &op, NotNullExpressionAnalyzer &nullability, + const vector> &ancestors, + BindingReplacementGraph &replacements); + private: Optimizer &optimizer; }; diff --git a/src/duckdb/src/include/duckdb/planner/table_filter_state.hpp b/src/duckdb/src/include/duckdb/planner/table_filter_state.hpp index 4ea34e733..9f68b0164 100644 --- a/src/duckdb/src/include/duckdb/planner/table_filter_state.hpp +++ b/src/duckdb/src/include/duckdb/planner/table_filter_state.hpp @@ -114,9 +114,16 @@ struct ExpressionFilterState : public TableFilterState { return executor->GetContext(); } + bool TryFilterDictionary(SelectionVector &sel, Vector &vector, idx_t &approved_tuple_count); + unique_ptr executor; unique_ptr fast_executor; bool can_cache_result = false; + +private: + string dictionary_id; + //! Destroy before the executors, as adaptive caches reference their feedback state. + unique_ptr dictionary_cache; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 098058aee..851782c11 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -1636,10 +1636,72 @@ typedef struct { 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_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); + DUCKDB_V2_ERROR (*duckdb_v2_crypto_cipher_destroy)(duckdb_v2_crypto_cipher_handle *stream); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_cipher_finalize) + (duckdb_v2_crypto_cipher_handle stream, uint8_t *tag, idx_t tag_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_cipher_init) + (duckdb_v2_crypto_cipher_handle stream, const uint8_t *iv, idx_t iv_length, const uint8_t *aad, idx_t aad_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_cipher_update) + (duckdb_v2_crypto_cipher_handle stream, const uint8_t *in, idx_t in_length, uint8_t *out, idx_t out_capacity, + idx_t *out_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_hash) + (duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, const uint8_t *data, idx_t length, + uint8_t *digest, idx_t digest_capacity, idx_t *digest_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_hash_digest_size) + (DUCKDB_V2_CRYPTO_HASH_FUNCTION function, idx_t *size, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_hmac) + (duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, const uint8_t *key, idx_t key_length, + const uint8_t *data, idx_t length, uint8_t *mac, idx_t mac_capacity, idx_t *mac_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_create) + (duckdb_v2_factory_handle factory, duckdb_v2_crypto_provider_handle *provider, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_crypto_provider_destroy)(duckdb_v2_crypto_provider_handle *provider); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_cipher_create_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_create_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_cipher_destroy_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_destroy_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_cipher_finalize_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_finalize_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_cipher_init_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_init_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_cipher_update_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_update_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_hash_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_hash_callback_fn callback, + const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_hmac_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_hmac_callback_fn callback, + const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_random_callback) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_random_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_provider_set_user_data) + (duckdb_v2_crypto_provider_handle provider, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_random_bytes) + (duckdb_v2_instance_handle instance, uint8_t *data, idx_t length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_supports_hash) + (duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_crypto_supports_hmac) + (duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_extension_register_crypto_provider) + (duckdb_v2_extension_handle extension, duckdb_v2_crypto_provider_handle provider, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_extension_register_secret_function) (duckdb_v2_extension_handle extension, duckdb_v2_secret_function_handle function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_get_object_cache) (duckdb_v2_instance_handle instance, duckdb_v2_object_cache_handle *cache, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_instance_register_crypto_provider) + (duckdb_v2_instance_handle instance, duckdb_v2_crypto_provider_handle provider, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_object_cache_delete) (duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, const char *key, idx_t key_length, duckdb_v2_error_info_handle *err); @@ -1722,6 +1784,9 @@ typedef struct { const idx_t *option_names_lengths, const char *const *option_values, const idx_t *option_values_lengths, idx_t option_count, duckdb_v2_instance_init_callback_fn init, void *init_user_data, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); + 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); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -3817,12 +3882,89 @@ typedef struct { #define duckdb_v2_context_lookup_secret duckdb_ext_api.duckdb_v2_context_lookup_secret #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 +#define duckdb_v2_crypto_cipher_destroy duckdb_ext_api.duckdb_v2_crypto_cipher_destroy +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_cipher_finalize duckdb_ext_api.duckdb_v2_crypto_cipher_finalize +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_cipher_init duckdb_ext_api.duckdb_v2_crypto_cipher_init +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_cipher_update duckdb_ext_api.duckdb_v2_crypto_cipher_update +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_hash duckdb_ext_api.duckdb_v2_crypto_hash +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_hash_digest_size duckdb_ext_api.duckdb_v2_crypto_hash_digest_size +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_hmac duckdb_ext_api.duckdb_v2_crypto_hmac +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_create duckdb_ext_api.duckdb_v2_crypto_provider_create +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_destroy duckdb_ext_api.duckdb_v2_crypto_provider_destroy +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_set_cipher_create_callback \ + duckdb_ext_api.duckdb_v2_crypto_provider_set_cipher_create_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_set_cipher_destroy_callback \ + duckdb_ext_api.duckdb_v2_crypto_provider_set_cipher_destroy_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_set_cipher_finalize_callback \ + duckdb_ext_api.duckdb_v2_crypto_provider_set_cipher_finalize_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_set_cipher_init_callback \ + duckdb_ext_api.duckdb_v2_crypto_provider_set_cipher_init_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_set_cipher_update_callback \ + duckdb_ext_api.duckdb_v2_crypto_provider_set_cipher_update_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_set_hash_callback duckdb_ext_api.duckdb_v2_crypto_provider_set_hash_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_set_hmac_callback duckdb_ext_api.duckdb_v2_crypto_provider_set_hmac_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_set_random_callback duckdb_ext_api.duckdb_v2_crypto_provider_set_random_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_provider_set_user_data duckdb_ext_api.duckdb_v2_crypto_provider_set_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_random_bytes duckdb_ext_api.duckdb_v2_crypto_random_bytes +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_supports_hash duckdb_ext_api.duckdb_v2_crypto_supports_hash +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_crypto_supports_hmac duckdb_ext_api.duckdb_v2_crypto_supports_hmac +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_extension_register_crypto_provider duckdb_ext_api.duckdb_v2_extension_register_crypto_provider +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_extension_register_secret_function duckdb_ext_api.duckdb_v2_extension_register_secret_function #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_instance_get_object_cache duckdb_ext_api.duckdb_v2_instance_get_object_cache #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_instance_register_crypto_provider duckdb_ext_api.duckdb_v2_instance_register_crypto_provider +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_object_cache_delete duckdb_ext_api.duckdb_v2_object_cache_delete #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -3921,6 +4063,9 @@ typedef struct { #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_instance_open_shared duckdb_ext_api.duckdb_v2_instance_open_shared #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_connection_get_profiling_information duckdb_ext_api.duckdb_v2_connection_get_profiling_information +#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 0ee70cdf1..35e3fb21a 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -2033,6 +2033,603 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_progress_get(duckdb_v2_connect /* --- Struct definitions for connection --- */ +/* ============================================================================ + * MODULE: crypto + * ============================================================================ */ + +/* --- Enums for crypto --- */ + +//! A cipher, meaning an algorithm together with its mode of operation. New ciphers are new values. +typedef enum DUCKDB_V2_CRYPTO_CIPHER { + //! AES-GCM. 12-byte IV, optional additional authenticated data, 16-byte authentication tag. + DUCKDB_V2_CRYPTO_CIPHER_AES_GCM = 1, + + //! AES-CTR. 16-byte IV (initial counter block), no authentication tag. + DUCKDB_V2_CRYPTO_CIPHER_AES_CTR = 2, + DUCKDB_V2_CRYPTO_CIPHER_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_CRYPTO_CIPHER; + +//! The direction of a cipher stream. +typedef enum DUCKDB_V2_CRYPTO_MODE { + //! Encrypt plaintext into ciphertext. + DUCKDB_V2_CRYPTO_MODE_ENCRYPT = 0, + + //! Decrypt ciphertext into plaintext. + DUCKDB_V2_CRYPTO_MODE_DECRYPT = 1, + DUCKDB_V2_CRYPTO_MODE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_CRYPTO_MODE; + +//! A hash function, for hashing and HMAC. +typedef enum DUCKDB_V2_CRYPTO_HASH_FUNCTION { + //! MD5, 16-byte digest. Not collision resistant; for legacy formats only. + DUCKDB_V2_CRYPTO_HASH_MD5 = 0, + + //! SHA-1, 20-byte digest. Not collision resistant; for legacy formats only. + DUCKDB_V2_CRYPTO_HASH_SHA1 = 1, + + //! SHA-256, 32-byte digest. + DUCKDB_V2_CRYPTO_HASH_SHA256 = 2, + DUCKDB_V2_CRYPTO_HASH_FUNCTION_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_CRYPTO_HASH_FUNCTION; + +/* --- Struct forward declarations for crypto --- */ + +/* --- Types for crypto --- */ + +/*! + * An owned opaque handle to a streaming cipher (see `CRYPTO_CIPHER`). Created with `duckdb_v2_crypto_cipher_create()`, + * initialized with `duckdb_v2_crypto_cipher_init()`, fed with `duckdb_v2_crypto_cipher_update()`, completed with + * `duckdb_v2_crypto_cipher_finalize()`, and destroyed with `duckdb_v2_crypto_cipher_destroy()`. Not safe for concurrent + * use. + */ +typedef struct _duckdb_v2_crypto_cipher { + void *internal_ptr; +} * duckdb_v2_crypto_cipher_handle; + +/*! + * An owned opaque handle to a crypto provider being built. Created with `duckdb_v2_crypto_provider_create()`, + * configured with the setters, registered with `duckdb_v2_instance_register_crypto_provider()` or + * `duckdb_v2_extension_register_crypto_provider()`, and destroyed with `duckdb_v2_crypto_provider_destroy()`. + */ +typedef struct _duckdb_v2_crypto_provider { + void *internal_ptr; +} * duckdb_v2_crypto_provider_handle; + +/* --- Constants for crypto --- */ + +/* --- Function pointer typedefs for crypto --- */ + +typedef void (*duckdb_v2_crypto_provider_cipher_create_callback_fn)(void *user_data, DUCKDB_V2_CRYPTO_CIPHER cipher, + DUCKDB_V2_CRYPTO_MODE mode, const uint8_t *key, + idx_t key_length, void **stream, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_crypto_provider_cipher_init_callback_fn)(void *user_data, void *stream, const uint8_t *iv, + idx_t iv_length, const uint8_t *aad, idx_t aad_length, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_crypto_provider_cipher_update_callback_fn)(void *user_data, void *stream, const uint8_t *in, + idx_t in_length, uint8_t *out, idx_t out_capacity, + idx_t *out_length, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_crypto_provider_cipher_finalize_callback_fn)(void *user_data, void *stream, uint8_t *tag, + idx_t tag_length, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_crypto_provider_cipher_destroy_callback_fn)(void *user_data, void *stream); + +typedef void (*duckdb_v2_crypto_provider_hash_callback_fn)(void *user_data, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, + const uint8_t *in, idx_t in_length, uint8_t *out, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_crypto_provider_hmac_callback_fn)(void *user_data, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, + const uint8_t *key, idx_t key_length, const uint8_t *in, + idx_t in_length, uint8_t *out, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_crypto_provider_random_callback_fn)(void *user_data, uint8_t *out, idx_t length, + duckdb_v2_error_info_handle *err); + +/* --- Functions for crypto --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the size in bytes of the digest, and of the HMAC, of a hash function. + * + * history: + * - unstable: v2.0.0 + * + * @param function The hash function. + * @param size Receives the size 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_crypto_hash_digest_size(DUCKDB_V2_CRYPTO_HASH_FUNCTION function, idx_t *size, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves whether the instance's crypto provider supports hashing with the function. + * + * history: + * - unstable: v2.0.0 + * + * @param instance The instance whose provider to ask. + * @param function The hash function. + * @param supported Receives whether hashing is supported. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_supports_hash(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves whether the instance's crypto provider supports HMAC with the function. + * + * history: + * - unstable: v2.0.0 + * + * @param instance The instance whose provider to ask. + * @param function The hash function. + * @param supported Receives whether HMAC is supported. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_supports_hmac(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Hashes `data` with the instance's crypto provider. + * + * Fails if the provider does not support the function; see `duckdb_v2_crypto_supports_hash()`. + * + * history: + * - unstable: v2.0.0 + * + * @param instance The instance whose provider to use. + * @param function The hash function. + * @param data The bytes to hash. May be null if `length` is 0. + * @param length The number of bytes. + * @param digest Receives the digest. + * @param digest_capacity The capacity of `digest`, at least `duckdb_v2_crypto_hash_digest_size()`. + * @param digest_length Receives the number of digest bytes written. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_hash(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_HASH_FUNCTION function, const uint8_t *data, + idx_t length, uint8_t *digest, idx_t digest_capacity, + idx_t *digest_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Computes the HMAC of `data` under `key` with the instance's crypto provider. + * + * Fails if the provider does not support the function; see `duckdb_v2_crypto_supports_hmac()`. + * + * history: + * - unstable: v2.0.0 + * + * @param instance The instance whose provider to use. + * @param function The hash function. + * @param key The HMAC key. + * @param key_length The key length in bytes. + * @param data The bytes to authenticate. May be null if `length` is 0. + * @param length The number of bytes. + * @param mac Receives the MAC. + * @param mac_capacity The capacity of `mac`, at least `duckdb_v2_crypto_hash_digest_size()`. + * @param mac_length Receives the number of MAC bytes written. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_hmac(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_HASH_FUNCTION function, const uint8_t *key, + idx_t key_length, const uint8_t *data, idx_t length, uint8_t *mac, + idx_t mac_capacity, idx_t *mac_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Fills `data` with cryptographically secure random bytes from the instance's crypto provider, e.g. for IVs. + * + * Fails when the instance has no provider DuckDB considers secure for writing; see the module notes. + * + * history: + * - unstable: v2.0.0 + * + * @param instance The instance whose provider to use. + * @param data Receives the random bytes. + * @param length The number of bytes to 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_crypto_random_bytes(duckdb_v2_instance_handle instance, uint8_t *data, + idx_t length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a streaming cipher. + * + * The key is copied and wiped when the cipher is destroyed. Encrypting requires a provider DuckDB considers secure for + * writing; decrypting does not. The cipher must be initialized with `duckdb_v2_crypto_cipher_init()` before use. + * + * history: + * - unstable: v2.0.0 + * + * @param instance The instance whose provider to use. + * @param cipher The cipher. + * @param mode Whether to encrypt or decrypt. + * @param key The key. Borrowed and copied. + * @param key_length The key length in bytes: 16, 24 or 32. + * @param stream On success, receives the new cipher. 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_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); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Starts the stream with an IV and, for GCM, additional authenticated data. + * + * The IV length and AAD support depend on the cipher: AES-GCM takes a 12-byte IV and optional AAD, AES-CTR a 16-byte IV + * and no AAD. May be called once per cipher. + * + * history: + * - unstable: v2.0.0 + * + * @param stream The cipher. + * @param iv The IV. Borrowed. + * @param iv_length The IV length in bytes. + * @param aad The additional authenticated data, or null. Borrowed. + * @param aad_length The AAD length in bytes, 0 if 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_crypto_cipher_init(duckdb_v2_crypto_cipher_handle stream, const uint8_t *iv, + idx_t iv_length, const uint8_t *aad, idx_t aad_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Processes the next chunk of the stream. + * + * Once an update or finalize fails in the provider, the cipher rejects every further call and can only be destroyed. + * `out_capacity` must be at least `in_length`. `in` and `out` may be the same buffer. For decryption with GCM, the + * plaintext must not be trusted before `duckdb_v2_crypto_cipher_finalize()` succeeds. + * + * history: + * - unstable: v2.0.0 + * + * @param stream The cipher. + * @param in The input bytes. + * @param in_length The number of input bytes. + * @param out Receives the output bytes. + * @param out_capacity The capacity of `out` in bytes. + * @param out_length Receives the number of bytes written. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_update(duckdb_v2_crypto_cipher_handle stream, const uint8_t *in, + idx_t in_length, uint8_t *out, idx_t out_capacity, + idx_t *out_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Completes the stream. + * + * GCM encryption: writes the 16-byte authentication tag into `tag`. GCM decryption: verifies the 16-byte `tag`, failing + * with an input error when it does not match, after which the cipher can only be destroyed. CTR: `tag` must be null and + * `tag_length` 0. + * + * history: + * - unstable: v2.0.0 + * + * @param stream The cipher. + * @param tag The tag buffer (GCM), or null. + * @param tag_length The tag length in bytes - 16 for GCM, 0 for CTR. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_finalize(duckdb_v2_crypto_cipher_handle stream, uint8_t *tag, + idx_t tag_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Destroys the cipher, wiping its key. Null-safe; the handle is set to null on return. + * + * history: + * - unstable: v2.0.0 + * + * @param stream The cipher to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_destroy(duckdb_v2_crypto_cipher_handle *stream); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a new, empty crypto provider through a factory. + * + * The provider can only be registered on the instance the factory belongs to. The caller owns the handle and must + * destroy it with `duckdb_v2_crypto_provider_destroy()`, also after registration. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to create the provider through. + * @param provider On success, receives the new provider. 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_crypto_provider_create(duckdb_v2_factory_handle factory, + duckdb_v2_crypto_provider_handle *provider, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets user data handed to every callback of the provider, destroyed with the registered provider (or with the handle + * if never registered). + * + * history: + * - unstable: v2.0.0 + * + * @param provider The provider. + * @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_crypto_provider_set_user_data(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback that creates a cipher stream. + * + * The create, init, update and finalize callbacks are required before registration, and together must support every + * `CRYPTO_CIPHER` value: currently AES-GCM and AES-CTR, with 16-, 24- and 32-byte keys. + * + * history: + * - unstable: v2.0.0 + * + * @param provider The provider. + * @param callback The create 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_crypto_provider_set_cipher_create_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_create_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback that starts a cipher stream. + * + * The callback must accept 16-byte GCM IVs: encrypted databases in the legacy v0 format use them, unlike + * `duckdb_v2_crypto_cipher_init()`, which takes 12. + * + * history: + * - unstable: v2.0.0 + * + * @param provider The provider. + * @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 + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_init_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_init_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback that processes a chunk of a cipher stream. + * + * history: + * - unstable: v2.0.0 + * + * @param provider The provider. + * @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_crypto_provider_set_cipher_update_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_update_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback that completes a cipher stream. + * + * history: + * - unstable: v2.0.0 + * + * @param provider The provider. + * @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_crypto_provider_set_cipher_finalize_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_finalize_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the optional callback that releases a cipher stream. + * + * history: + * - unstable: v2.0.0 + * + * @param provider The provider. + * @param callback Optional. The destroy 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_crypto_provider_set_cipher_destroy_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_destroy_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the hash callback and the functions it supports. Optional: DuckDB's built-in implementation serves every + * function the callback does not declare. + * + * history: + * - unstable: v2.0.0 + * + * @param provider The provider. + * @param callback The callback. + * @param functions The functions the callback supports. Borrowed and copied. + * @param function_count The number of functions. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_hash_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_hash_callback_fn callback, + const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the HMAC callback and the functions it supports. Optional: DuckDB's built-in implementation serves every + * function the callback does not declare. + * + * history: + * - unstable: v2.0.0 + * + * @param provider The provider. + * @param callback The callback. + * @param functions The functions the callback supports. Borrowed and copied. + * @param function_count The number of functions. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_hmac_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_hmac_callback_fn callback, + const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the random bytes callback. Required before registration: DuckDB generates the IVs and salts of encrypted writes + * with it. + * + * history: + * - unstable: v2.0.0 + * + * @param provider The provider. + * @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_crypto_provider_set_random_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_random_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Registers the provider as the instance's crypto provider, used by encrypted databases, Parquet encryption and the + * primitives above. + * + * Requires the cipher and random bytes callbacks. Register before the instance uses its crypto provider; see the module + * notes. Fails when the instance already has a provider (e.g. httpfs is loaded) or when the provider was created + * through a factory of another instance. The `force_mbedtls_unsafe` setting still overrides it. The caller still owns + * the handle and must destroy it with `duckdb_v2_crypto_provider_destroy()`. + * + * history: + * - unstable: v2.0.0 + * + * @param instance The instance to register on. + * @param provider The provider 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_crypto_provider(duckdb_v2_instance_handle instance, + duckdb_v2_crypto_provider_handle provider, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Registers the provider on the loading extension's instance. Use this from the extension's load callback. Follows the + * rules of `duckdb_v2_instance_register_crypto_provider()`. + * + * history: + * - unstable: v2.0.0 + * + * @param extension The loading extension. + * @param provider The provider 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_crypto_provider(duckdb_v2_extension_handle extension, + duckdb_v2_crypto_provider_handle provider, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Destroys the provider handle. Null-safe; the handle is set to null on return. Does not affect a registered provider. + * + * history: + * - unstable: v2.0.0 + * + * @param provider The provider to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_destroy(duckdb_v2_crypto_provider_handle *provider); +#endif + +/* --- Struct definitions for crypto --- */ + /* ============================================================================ * MODULE: custom type * ============================================================================ */ @@ -4834,7 +5431,8 @@ typedef struct _duckdb_v2_query_metrics_node { #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Takes a snapshot of the metrics of the last query the connection finished. + * Takes a snapshot of the metrics of the last query the connection profiled, which is not necessarily the last query it + * ran: see `duckdb_v2_connection_get_profiling_information()`. * * The snapshot is owned by the caller and does not change afterwards. It holds the metrics DuckDB's profiling * configuration gathered: without profiling enabled, the root node carries no metrics and has no children. A snapshot @@ -4879,6 +5477,49 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_enable_profiling(duckdb_v2_con duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Renders the profile of the last query the connection profiled. + * + * That is not necessarily the last query the connection ran: the profiler keeps the last profile while profiling is + * disabled. After profiling is enabled again, and until the next query finishes, the profile is still that of the last + * query run while profiling was enabled. + * + * The same profile `duckdb_v2_connection_get_query_metrics()` takes a snapshot of, as the text DuckDB's profiler prints + * for it: the query, its metrics and its operator tree. The text is delivered through `sink` in a single call. + * + * `format` names the profiler format: `json`, `text`, `query_tree`, `query_tree_optimizer`, `html`, `graphviz`, `yaml`, + * `mermaid` or `no_output`, which renders nothing. An empty `format` selects the connection's configured format (the + * `enable_profiling` option), or a query tree when that is `no_output`. An unknown format fails with + * `ERROR_INPUT_INVALID`. + * + * Without profiling enabled there is no profile: the text is the profiler's own note that profiling is disabled. + * + * Fails with `ERROR_RESOURCE_IN_USE` while a query is running on the connection, i.e. while a result of it has not yet + * been drained or destroyed. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection to render the profile of. + * @param format The profiler format name. Empty selects the configured format, or a query tree when that is + * `no_output`. + * @param format_length The length of `format` in bytes. `format` need not be null-terminated and may be NULL only when + * this is 0. + * @param sink Receives the rendered profile 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 + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API 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); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Borrows the root node of the snapshot, which describes the query as a whole. Its children, if any, describe the diff --git a/src/duckdb/src/main/capi/v2/capi_v2_crypto.cpp b/src/duckdb/src/main/capi/v2/capi_v2_crypto.cpp new file mode 100644 index 000000000..e1f6c01f2 --- /dev/null +++ b/src/duckdb/src/main/capi/v2/capi_v2_crypto.cpp @@ -0,0 +1,671 @@ +#include "duckdb/main/capi_v2/capi_v2_internal.hpp" + +#include "duckdb/common/encryption_state.hpp" +#include "duckdb/common/mutex.hpp" +#include "duckdb/main/config.hpp" + +namespace duckdb::capiv2 { + +//---------------------------------------------------------------------------------------------------------------------- +// Provider callbacks +//---------------------------------------------------------------------------------------------------------------------- +//! Runs a provider callback, rethrowing the error it reports as the matching exception. +template +static void InvokeCallback(FUNC &&func) { + CV2ErrorInfo info; + auto handle = Convert(&info); + func(&handle); + if (info.HasError()) { + info.ThrowAsException(); + } +} + +static uint32_t HashFunctionBit(CryptoHashFunction function) { + return 1U << static_cast(function); +} + +static CryptoHashFunction ConvertHashFunction(DUCKDB_V2_CRYPTO_HASH_FUNCTION function) { + switch (function) { + case DUCKDB_V2_CRYPTO_HASH_MD5: + return CryptoHashFunction::MD5; + case DUCKDB_V2_CRYPTO_HASH_SHA1: + return CryptoHashFunction::SHA1; + case DUCKDB_V2_CRYPTO_HASH_SHA256: + return CryptoHashFunction::SHA256; + default: + throw InvalidInputException("Unknown hash function"); + } +} + +struct CV2CryptoCallbacks { + duckdb_v2_crypto_provider_cipher_create_callback_fn cipher_create = nullptr; + duckdb_v2_crypto_provider_cipher_init_callback_fn cipher_init = nullptr; + duckdb_v2_crypto_provider_cipher_update_callback_fn cipher_update = nullptr; + duckdb_v2_crypto_provider_cipher_finalize_callback_fn cipher_finalize = nullptr; + duckdb_v2_crypto_provider_cipher_destroy_callback_fn cipher_destroy = nullptr; + duckdb_v2_crypto_provider_hash_callback_fn hash = nullptr; + duckdb_v2_crypto_provider_hmac_callback_fn hmac = nullptr; + //! Bit masks of the CryptoHashFunction values the callbacks serve + uint32_t hash_functions = 0; + uint32_t hmac_functions = 0; + duckdb_v2_crypto_provider_random_callback_fn random = nullptr; +}; + +//! The cipher stream of a provider: created on initialization, once key, direction and IV are known +class CV2ProviderEncryptionState final : public EncryptionState { +public: + CV2ProviderEncryptionState(unique_ptr metadata, const CV2CryptoCallbacks &callbacks, + shared_ptr user_data) + : EncryptionState(std::move(metadata)), callbacks(callbacks), user_data(std::move(user_data)) { + } + + ~CV2ProviderEncryptionState() override { + if (stream && callbacks.cipher_destroy) { + callbacks.cipher_destroy(GetUserData(), stream); + } + } + + void InitializeEncryption(EncryptionNonce &nonce, const_data_ptr_t key, const_data_ptr_t aad, + idx_t aad_len) override { + Initialize(DUCKDB_V2_CRYPTO_MODE_ENCRYPT, nonce, key, aad, aad_len); + } + + void InitializeDecryption(EncryptionNonce &nonce, const_data_ptr_t key, const_data_ptr_t aad, + idx_t aad_len) override { + Initialize(DUCKDB_V2_CRYPTO_MODE_DECRYPT, nonce, key, aad, aad_len); + } + + size_t Process(const_data_ptr_t in, idx_t in_len, data_ptr_t out, idx_t out_len) override { + CheckInitialized(); + idx_t written = 0; + InvokeCallback([&](duckdb_v2_error_info_handle *err) { + callbacks.cipher_update(GetUserData(), stream, in, in_len, out, out_len, &written, err); + }); + return written; + } + + size_t Finalize(data_ptr_t out, idx_t out_len, data_ptr_t tag, idx_t tag_len) override { + CheckInitialized(); + auto is_gcm = GetCipher() == EncryptionTypes::GCM; + InvokeCallback([&](duckdb_v2_error_info_handle *err) { + callbacks.cipher_finalize(GetUserData(), stream, is_gcm ? tag : nullptr, is_gcm ? tag_len : 0, err); + }); + return 0; + } + + void GenerateRandomData(data_ptr_t data, idx_t len) override { + InvokeCallback([&](duckdb_v2_error_info_handle *err) { callbacks.random(GetUserData(), data, len, err); }); + } + +private: + void *GetUserData() const { + return user_data ? user_data->GetData() : nullptr; + } + + void CheckInitialized() const { + if (!stream) { + throw InvalidInputException("The cipher stream has not been initialized"); + } + } + + void Initialize(DUCKDB_V2_CRYPTO_MODE mode, EncryptionNonce &nonce, const_data_ptr_t key, const_data_ptr_t aad, + idx_t aad_len) { + if (stream) { + throw InvalidInputException("The cipher stream has already been initialized"); + } + auto cipher = static_cast(GetCipher()); + InvokeCallback([&](duckdb_v2_error_info_handle *err) { + callbacks.cipher_create(GetUserData(), cipher, mode, key, metadata->GetKeyLen(), &stream, err); + }); + InvokeCallback([&](duckdb_v2_error_info_handle *err) { + callbacks.cipher_init(GetUserData(), stream, nonce.data(), nonce.total_size(), aad, aad_len, err); + }); + } + +private: + CV2CryptoCallbacks callbacks; + shared_ptr user_data; + void *stream = nullptr; +}; + +//! The crypto provider supplied through the C API. Hashing and HMAC fall back to the built-in provider. +class CV2EncryptionUtil final : public EncryptionUtil { +public: + CV2EncryptionUtil(const CV2CryptoCallbacks &callbacks, shared_ptr user_data, + shared_ptr fallback) + : callbacks(callbacks), user_data(std::move(user_data)), fallback(std::move(fallback)) { + } + + shared_ptr CreateEncryptionState(unique_ptr metadata) const override { + return make_shared_ptr(std::move(metadata), callbacks, user_data); + } + + unique_ptr CreateHashState(CryptoHashFunction function) const override { + if (!ServesHash(function)) { + return fallback->CreateHashState(function); + } + return EncryptionUtil::CreateHashState(function); + } + + void Hash(CryptoHashFunction function, const_data_ptr_t input, idx_t input_len, data_ptr_t output) const override { + if (!ServesHash(function)) { + fallback->Hash(function, input, input_len, output); + return; + } + auto c_function = static_cast(function); + InvokeCallback([&](duckdb_v2_error_info_handle *err) { + callbacks.hash(GetUserData(), c_function, input, input_len, output, err); + }); + } + + void Hmac(CryptoHashFunction function, const_data_ptr_t key, idx_t key_len, const_data_ptr_t input, idx_t input_len, + data_ptr_t output) const override { + if (!callbacks.hmac || !(callbacks.hmac_functions & HashFunctionBit(function))) { + fallback->Hmac(function, key, key_len, input, input_len, output); + return; + } + auto c_function = static_cast(function); + InvokeCallback([&](duckdb_v2_error_info_handle *err) { + callbacks.hmac(GetUserData(), c_function, key, key_len, input, input_len, output, err); + }); + } + + bool SupportsHash(CryptoHashFunction function) const override { + return ServesHash(function) || fallback->SupportsHash(function); + } + + bool SupportsHmac(CryptoHashFunction function) const override { + return (callbacks.hmac && (callbacks.hmac_functions & HashFunctionBit(function))) || + fallback->SupportsHmac(function); + } + +private: + void *GetUserData() const { + return user_data ? user_data->GetData() : nullptr; + } + + bool ServesHash(CryptoHashFunction function) const { + return callbacks.hash && (callbacks.hash_functions & HashFunctionBit(function)); + } + +private: + CV2CryptoCallbacks callbacks; + shared_ptr user_data; + shared_ptr fallback; +}; + +class CV2CryptoProvider { +public: + explicit CV2CryptoProvider(DatabaseInstance &db) : db(db) { + } + + void Register(DatabaseInstance &target) { + CheckRegistrationTarget(db, target, "crypto provider"); + if (!callbacks.cipher_create || !callbacks.cipher_init || !callbacks.cipher_update || + !callbacks.cipher_finalize) { + throw InvalidInputException("The cipher callbacks must be set for the crypto provider."); + } + if (!callbacks.random) { + throw InvalidInputException("The random callback must be set for the crypto provider."); + } + static mutex registration_lock; + lock_guard guard(registration_lock); + auto &config = DBConfig::GetConfig(target); + if (config.encryption_util) { + throw InvalidInputException("A crypto provider is already registered on this database."); + } + config.encryption_util = make_shared_ptr(callbacks, user_data, target.GetMbedTLSUtil(false)); + } + +public: + //! The database it was created for: the only one it can be registered on. + DatabaseInstance &db; + CV2CryptoCallbacks callbacks; + shared_ptr user_data = nullptr; +}; + +static auto Convert(duckdb_v2_crypto_provider_handle provider) -> CV2CryptoProvider * { + return reinterpret_cast(provider); +} +static auto Convert(CV2CryptoProvider *provider) -> duckdb_v2_crypto_provider_handle { + return reinterpret_cast(provider); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Primitives +//---------------------------------------------------------------------------------------------------------------------- +//! A streaming cipher on the instance's crypto provider +class CV2Cipher { +public: + CV2Cipher(DatabaseInstance &db, DUCKDB_V2_CRYPTO_CIPHER cipher_p, DUCKDB_V2_CRYPTO_MODE mode_p, + const uint8_t *key_p, idx_t key_length) + : mode(mode_p) { + switch (cipher_p) { + case DUCKDB_V2_CRYPTO_CIPHER_AES_GCM: + cipher = EncryptionTypes::GCM; + break; + case DUCKDB_V2_CRYPTO_CIPHER_AES_CTR: + cipher = EncryptionTypes::CTR; + break; + default: + throw InvalidInputException("Unknown cipher"); + } + if (mode != DUCKDB_V2_CRYPTO_MODE_ENCRYPT && mode != DUCKDB_V2_CRYPTO_MODE_DECRYPT) { + throw InvalidInputException("Unknown cipher mode"); + } + if (key_length != 16 && key_length != 24 && key_length != 32) { + throw InvalidInputException("AES keys must be 16, 24 or 32 bytes, got %llu", + static_cast(key_length)); + } + // writing needs a secure provider, reading falls back to the built-in one + auto util = db.GetEncryptionUtil(mode == DUCKDB_V2_CRYPTO_MODE_DECRYPT); + state = util->CreateEncryptionState( + make_uniq(cipher, key_length, EncryptionTypes::EncryptionVersion::V0_1)); + key.assign(reinterpret_cast(key_p), key_length); + } + + ~CV2Cipher() { + // volatile writes so the wipe is not optimized away + volatile char *volatile_key = key.empty() ? nullptr : &key[0]; + for (idx_t i = 0; i < key.size(); i++) { + volatile_key[i] = 0; + } + } + + void Init(const uint8_t *iv, idx_t iv_length, const uint8_t *aad, idx_t aad_length) { + CheckNotFailed(); + if (initialized) { + throw InvalidInputException("The cipher has already been initialized"); + } + auto expected_iv_length = cipher == EncryptionTypes::GCM ? 12 : 16; + if (iv_length != expected_iv_length) { + throw InvalidInputException("The IV must be %llu bytes for %s, got %llu", + static_cast(expected_iv_length), + EncryptionTypes::CipherToString(cipher), static_cast(iv_length)); + } + if (aad_length > 0 && (cipher != EncryptionTypes::GCM || !aad)) { + throw InvalidInputException("Additional authenticated data is only valid for GCM"); + } + EncryptionNonce nonce(cipher, EncryptionTypes::EncryptionVersion::V0_1); + memcpy(nonce.data(), iv, iv_length); + auto key_ptr = const_data_ptr_cast(key.data()); + RunBackend([&]() { + if (mode == DUCKDB_V2_CRYPTO_MODE_ENCRYPT) { + state->InitializeEncryption(nonce, key_ptr, aad, aad_length); + } else { + state->InitializeDecryption(nonce, key_ptr, aad, aad_length); + } + }); + initialized = true; + } + + idx_t Update(const uint8_t *in, idx_t in_length, uint8_t *out, idx_t out_capacity) { + CheckActive(); + if (out_capacity < in_length) { + throw Exception(ExceptionType::OBJECT_SIZE, "out_capacity must be at least in_length"); + } + idx_t written = 0; + RunBackend([&]() { written = state->Process(in, in_length, out, out_capacity); }); + return written; + } + + void Finalize(uint8_t *tag, idx_t tag_length) { + CheckActive(); + auto expected_tag_length = cipher == EncryptionTypes::GCM ? 16 : 0; + if (tag_length != expected_tag_length || (tag_length > 0 && !tag)) { + throw InvalidInputException("The tag must be %llu bytes for %s", static_cast(expected_tag_length), + EncryptionTypes::CipherToString(cipher)); + } + // ciphers may flush a final block, which for these stream modes is always empty + data_t scratch[32]; + RunBackend([&]() { state->Finalize(scratch, sizeof(scratch), tag, tag_length); }); + finalized = true; + } + +private: + //! Runs a backend call: once one fails, the cipher rejects every further call + template + void RunBackend(FUNC &&func) { + try { + func(); + } catch (...) { + failed = true; + throw; + } + } + + void CheckNotFailed() const { + if (failed) { + throw InvalidInputException("The cipher failed and can only be destroyed"); + } + } + + void CheckActive() const { + CheckNotFailed(); + if (!initialized) { + throw InvalidInputException("The cipher has not been initialized"); + } + if (finalized) { + throw InvalidInputException("The cipher has already been finalized"); + } + } + +private: + EncryptionTypes::CipherType cipher; + DUCKDB_V2_CRYPTO_MODE mode; + string key; + shared_ptr state; + bool initialized = false; + bool finalized = false; + bool failed = false; +}; + +static auto Convert(duckdb_v2_crypto_cipher_handle stream) -> CV2Cipher * { + return reinterpret_cast(stream); +} +static auto Convert(CV2Cipher *stream) -> duckdb_v2_crypto_cipher_handle { + return reinterpret_cast(stream); +} + +//! Providers such as OpenSSL reject null pointers even for empty buffers +static const uint8_t *NonNullBuffer(const uint8_t *buffer) { + static const uint8_t EMPTY = 0; + return buffer ? buffer : &EMPTY; +} + +static DatabaseInstance &GetInstance(duckdb_v2_instance_handle instance) { + return *Convert(instance)->GetDatabase().instance; +} + +} // namespace duckdb::capiv2 + +//---------------------------------------------------------------------------------------------------------------------- +// Public Functions +//---------------------------------------------------------------------------------------------------------------------- + +using namespace duckdb::capiv2; + +DUCKDB_V2_ERROR duckdb_v2_crypto_hash_digest_size(DUCKDB_V2_CRYPTO_HASH_FUNCTION function, idx_t *size, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(size); + return WithErrorHandler(err, [&]() { *size = duckdb::CryptoHash::GetDigestSize(ConvertHashFunction(function)); }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_supports_hash(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(instance); + DUCKDB_CHECK_ARG(supported); + return WithErrorHandler(err, [&]() { + *supported = GetInstance(instance).GetEncryptionUtil(true)->SupportsHash(ConvertHashFunction(function)); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_supports_hmac(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(instance); + DUCKDB_CHECK_ARG(supported); + return WithErrorHandler(err, [&]() { + *supported = GetInstance(instance).GetEncryptionUtil(true)->SupportsHmac(ConvertHashFunction(function)); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_hash(duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, + const uint8_t *data, idx_t length, uint8_t *digest, idx_t digest_capacity, + idx_t *digest_length, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(instance); + DUCKDB_CHECK_ARG(digest); + DUCKDB_CHECK_ARG(digest_length); + if (length > 0) { + DUCKDB_CHECK_ARG(data); + } + *digest_length = 0; + return WithErrorHandler(err, [&]() { + auto hash_function = ConvertHashFunction(function); + auto size = duckdb::CryptoHash::GetDigestSize(hash_function); + if (digest_capacity < size) { + throw duckdb::Exception(duckdb::ExceptionType::OBJECT_SIZE, "digest_capacity is smaller than the digest"); + } + auto util = GetInstance(instance).GetEncryptionUtil(true); + if (!util->SupportsHash(hash_function)) { + throw duckdb::NotImplementedException("The crypto provider does not support this hash function"); + } + util->Hash(hash_function, NonNullBuffer(data), length, digest); + *digest_length = size; + }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_hmac(duckdb_v2_instance_handle instance, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, + const uint8_t *key, idx_t key_length, const uint8_t *data, idx_t length, + uint8_t *mac, idx_t mac_capacity, idx_t *mac_length, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(instance); + DUCKDB_CHECK_ARG(mac); + DUCKDB_CHECK_ARG(mac_length); + if (key_length > 0) { + DUCKDB_CHECK_ARG(key); + } + if (length > 0) { + DUCKDB_CHECK_ARG(data); + } + *mac_length = 0; + return WithErrorHandler(err, [&]() { + auto hash_function = ConvertHashFunction(function); + auto size = duckdb::CryptoHash::GetDigestSize(hash_function); + if (mac_capacity < size) { + throw duckdb::Exception(duckdb::ExceptionType::OBJECT_SIZE, "mac_capacity is smaller than the MAC"); + } + auto util = GetInstance(instance).GetEncryptionUtil(true); + if (!util->SupportsHmac(hash_function)) { + throw duckdb::NotImplementedException("The crypto provider does not support HMAC with this hash function"); + } + util->Hmac(hash_function, NonNullBuffer(key), key_length, NonNullBuffer(data), length, mac); + *mac_length = size; + }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_random_bytes(duckdb_v2_instance_handle instance, uint8_t *data, idx_t length, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(instance); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { + auto util = GetInstance(instance).GetEncryptionUtil(false); + auto state = util->CreateEncryptionState(duckdb::make_uniq( + duckdb::EncryptionTypes::GCM, 16, duckdb::EncryptionTypes::EncryptionVersion::V0_1)); + state->GenerateRandomData(data, length); + }); +} + +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) { + DUCKDB_CHECK_ARG(instance); + DUCKDB_CHECK_ARG(key); + DUCKDB_CHECK_ARG(stream); + *stream = nullptr; + return WithErrorHandler(err, [&]() { + auto result = duckdb::make_uniq(GetInstance(instance), cipher, mode, key, key_length); + *stream = Convert(result.release()); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_init(duckdb_v2_crypto_cipher_handle stream, const uint8_t *iv, idx_t iv_length, + const uint8_t *aad, idx_t aad_length, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(stream); + DUCKDB_CHECK_ARG(iv); + return WithErrorHandler(err, [&]() { Convert(stream)->Init(iv, iv_length, aad, aad_length); }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_update(duckdb_v2_crypto_cipher_handle stream, const uint8_t *in, + idx_t in_length, uint8_t *out, idx_t out_capacity, idx_t *out_length, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(stream); + DUCKDB_CHECK_ARG(out_length); + if (in_length > 0) { + DUCKDB_CHECK_ARG(in); + DUCKDB_CHECK_ARG(out); + } + *out_length = 0; + return WithErrorHandler(err, [&]() { *out_length = Convert(stream)->Update(in, in_length, out, out_capacity); }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_finalize(duckdb_v2_crypto_cipher_handle stream, uint8_t *tag, idx_t tag_length, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(stream); + return WithErrorHandler(err, [&]() { Convert(stream)->Finalize(tag, tag_length); }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_destroy(duckdb_v2_crypto_cipher_handle *stream) { + return WithErrorHandler(nullptr, [&]() { + if (!stream) { + return; + } + if (*stream) { + delete Convert(*stream); + *stream = nullptr; + } + }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_provider_create(duckdb_v2_factory_handle factory, + duckdb_v2_crypto_provider_handle *provider, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(factory); + DUCKDB_CHECK_ARG(provider); + *provider = nullptr; + return WithErrorHandler(err, [&]() { + auto result = duckdb::make_uniq(Convert(factory)->GetDatabase()); + *provider = Convert(result.release()); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_user_data(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(provider); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { + Convert(provider)->user_data = duckdb::make_shared_ptr(data->ptr, data->destroy, data->equals); + }); +} + +DUCKDB_V2_ERROR +duckdb_v2_crypto_provider_set_cipher_create_callback(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_crypto_provider_cipher_create_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(provider); + DUCKDB_CHECK_ARG(callback); + return WithErrorHandler(err, [&]() { Convert(provider)->callbacks.cipher_create = callback; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_crypto_provider_set_cipher_init_callback(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_crypto_provider_cipher_init_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(provider); + DUCKDB_CHECK_ARG(callback); + return WithErrorHandler(err, [&]() { Convert(provider)->callbacks.cipher_init = callback; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_crypto_provider_set_cipher_update_callback(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_crypto_provider_cipher_update_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(provider); + DUCKDB_CHECK_ARG(callback); + return WithErrorHandler(err, [&]() { Convert(provider)->callbacks.cipher_update = callback; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_crypto_provider_set_cipher_finalize_callback(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_crypto_provider_cipher_finalize_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(provider); + DUCKDB_CHECK_ARG(callback); + return WithErrorHandler(err, [&]() { Convert(provider)->callbacks.cipher_finalize = callback; }); +} + +DUCKDB_V2_ERROR +duckdb_v2_crypto_provider_set_cipher_destroy_callback(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_crypto_provider_cipher_destroy_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(provider); + return WithErrorHandler(err, [&]() { Convert(provider)->callbacks.cipher_destroy = callback; }); +} + +static uint32_t ToHashFunctionMask(const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count) { + uint32_t mask = 0; + for (idx_t i = 0; i < function_count; i++) { + mask |= HashFunctionBit(ConvertHashFunction(functions[i])); + } + return mask; +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_hash_callback(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_crypto_provider_hash_callback_fn callback, + const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, + idx_t function_count, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(provider); + if (function_count > 0) { + DUCKDB_CHECK_ARG(functions); + } + return WithErrorHandler(err, [&]() { + auto mask = ToHashFunctionMask(functions, function_count); + auto &callbacks = Convert(provider)->callbacks; + callbacks.hash = callback; + callbacks.hash_functions = callback ? mask : 0; + }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_hmac_callback(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_crypto_provider_hmac_callback_fn callback, + const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, + idx_t function_count, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(provider); + if (function_count > 0) { + DUCKDB_CHECK_ARG(functions); + } + return WithErrorHandler(err, [&]() { + auto mask = ToHashFunctionMask(functions, function_count); + auto &callbacks = Convert(provider)->callbacks; + callbacks.hmac = callback; + callbacks.hmac_functions = callback ? mask : 0; + }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_random_callback(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_crypto_provider_random_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(provider); + return WithErrorHandler(err, [&]() { Convert(provider)->callbacks.random = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_instance_register_crypto_provider(duckdb_v2_instance_handle instance, + duckdb_v2_crypto_provider_handle provider, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(instance); + DUCKDB_CHECK_ARG(provider); + return WithErrorHandler(err, [&]() { Convert(provider)->Register(GetInstance(instance)); }); +} + +DUCKDB_V2_ERROR duckdb_v2_extension_register_crypto_provider(duckdb_v2_extension_handle extension, + duckdb_v2_crypto_provider_handle provider, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(extension); + DUCKDB_CHECK_ARG(provider); + return WithErrorHandler( + err, [&]() { Convert(provider)->Register(GetExtensionLoader(extension).GetDatabaseInstance()); }); +} + +DUCKDB_V2_ERROR duckdb_v2_crypto_provider_destroy(duckdb_v2_crypto_provider_handle *provider) { + return WithErrorHandler(nullptr, [&]() { + if (!provider) { + return; + } + if (*provider) { + delete Convert(*provider); + *provider = nullptr; + } + }); +} diff --git a/src/duckdb/src/main/capi/v2/capi_v2_query_metrics.cpp b/src/duckdb/src/main/capi/v2/capi_v2_query_metrics.cpp index d8a529a2d..3e63e9d5b 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_query_metrics.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_query_metrics.cpp @@ -111,6 +111,22 @@ DUCKDB_V2_ERROR duckdb_v2_connection_get_query_metrics(duckdb_v2_connection_hand }); } +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_CHECK_ARG(conn); + DUCKDB_CHECK_ARG(sink); + DUCKDB_CHECK_STR_ARG(format, format_length); + return WithErrorHandler(err, [&]() { + auto &connection = *Convert(conn); + connection.context->VerifyNoOpenResult(); + std::string format_name(Convert(format, format_length)); + auto print_format = + format_name.empty() ? duckdb::ProfilerPrintFormat::Default() : duckdb::ProfilerPrintFormat(format_name); + InvokeTextSink(sink, connection.GetProfilingInformation(print_format), user_data); + }); +} + DUCKDB_V2_ERROR duckdb_v2_connection_enable_profiling(duckdb_v2_connection_handle conn, bool enabled, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(conn); diff --git a/src/duckdb/src/main/client_context.cpp b/src/duckdb/src/main/client_context.cpp index 5e3c1343d..2b432af7b 100644 --- a/src/duckdb/src/main/client_context.cpp +++ b/src/duckdb/src/main/client_context.cpp @@ -10,7 +10,6 @@ #include "duckdb/common/serializer/buffered_file_writer.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/common/types/uuid.hpp" -#include "duckdb/execution/column_binding_resolver.hpp" #include "duckdb/execution/physical_plan_generator.hpp" #include "duckdb/main/appender.hpp" #include "duckdb/main/attached_database.hpp" @@ -26,7 +25,6 @@ #include "duckdb/main/prepared_statement_data.hpp" #include "duckdb/main/query_profiler.hpp" #include "duckdb/main/query_result.hpp" -#include "duckdb/optimizer/optimizer.hpp" #include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/parser/expression/star_expression.hpp" #include "duckdb/parser/parsed_data/create_function_info.hpp" @@ -39,7 +37,6 @@ #include "duckdb/parser/statement/prepare_statement.hpp" #include "duckdb/parser/statement/select_statement.hpp" #include "duckdb/planner/binder.hpp" -#include "duckdb/planner/logical_plan_verifier.hpp" #include "duckdb/planner/planner.hpp" #include "duckdb/planner/statement_preprocessor.hpp" #include "duckdb/storage/data_table.hpp" @@ -506,36 +503,6 @@ vector> ClientContext::ParseStatementsInternal(ClientCo } } -unique_ptr ClientContext::ExtractPlan(const string &query) { - auto lock = LockContext(); - - auto statements = ParseStatementsInternal(*lock, query, false); - if (statements.size() != 1) { - throw InvalidInputException("ExtractPlan can only prepare a single statement"); - } - statements[0] = ExpandSingleStatementInternal(*lock, std::move(statements[0]), - "ExtractPlan can only prepare a single statement"); - - unique_ptr plan; - RunFunctionInTransactionInternal(*lock, [&]() { - Planner planner(*this); - planner.CreatePlan(std::move(statements[0])); - D_ASSERT(planner.plan); - - plan = std::move(planner.plan); - - Optimizer optimizer(*planner.binder, *this); - plan = optimizer.Optimize(std::move(plan)); - - LogicalPlanVerifier::Verify(*this, *plan); - // the resolver checks the column references against the operator types, which the optimizer leaves stale - plan->ResolveOperatorTypes(); - ColumnBindingResolver resolver; - resolver.VisitOperator(*plan); - }); - return plan; -} - //! Snapshot the metadata that the PreparedStatement handle exposes to the user static PreparedStatementInfo GetPreparedStatementInfo(PreparedStatementData &data) { PreparedStatementInfo info; diff --git a/src/duckdb/src/main/connection.cpp b/src/duckdb/src/main/connection.cpp index b045a6bd1..77b949a2e 100644 --- a/src/duckdb/src/main/connection.cpp +++ b/src/duckdb/src/main/connection.cpp @@ -191,10 +191,6 @@ vector> Connection::ExtractStatements(const string &que return result; } -unique_ptr Connection::ExtractPlan(const string &query) { - return context->ExtractPlan(query); -} - void Connection::Append(TableDescription &description, ColumnDataCollection &collection) { context->Append(description, collection); } diff --git a/src/duckdb/src/main/prepared_statement_data.cpp b/src/duckdb/src/main/prepared_statement_data.cpp index c7d2c9808..13a0e9b03 100644 --- a/src/duckdb/src/main/prepared_statement_data.cpp +++ b/src/duckdb/src/main/prepared_statement_data.cpp @@ -42,15 +42,19 @@ bool CheckCatalogIdentity(ClientContext &context, const Identifier &catalog_name return StatementProperties::CatalogIdentity {current_catalog_oid, current_catalog_version} == catalog_identity; } -static BoundParameterData GetParameterValue(ClientContext &context, const identifier_map_t &values, - const Identifier &identifier, bool allow_user_variables) { +//! Returns the value of the parameter, which is stored in "storage" if it comes from a user variable +static const BoundParameterData &GetParameterValue(ClientContext &context, + const identifier_map_t &values, + const Identifier &identifier, bool allow_user_variables, + BoundParameterData &storage) { auto lookup = values.find(identifier); if (lookup != values.end()) { return lookup->second; } Value variable_value; if (allow_user_variables && ClientConfig::GetConfig(context).GetUserVariable(identifier, variable_value)) { - return BoundParameterData(std::move(variable_value)); + storage = BoundParameterData(std::move(variable_value)); + return storage; } throw BinderException("Could not find parameter with identifier %s", identifier); } @@ -67,16 +71,20 @@ static bool HasNamedParameters(const PreparedStatementData &data) { return data.unbound_statement && !data.unbound_statement->named_param_map.empty(); } -static identifier_map_t GetExpectedParameters(const PreparedStatementData &data) { +//! Returns the expected parameters, which are stored in "storage" if they have to be computed +static const identifier_map_t &GetExpectedParameters(const PreparedStatementData &data, + identifier_map_t &storage) { if (HasNamedParameters(data)) { return data.unbound_statement->named_param_map; } - return GetExpectedParameters(data.value_map); + storage = GetExpectedParameters(data.value_map); + return storage; } void PreparedStatementData::PopulateMissingParameterValues(ClientContext &context, identifier_map_t &values) const { - const auto expected_parameters = GetExpectedParameters(*this); + identifier_map_t expected_storage; + const auto &expected_parameters = GetExpectedParameters(*this, expected_storage); const bool allow_user_variables = HasNamedParameters(*this); auto verification_context = allow_user_variables ? &context : nullptr; PreparedStatement::VerifyParameters(values, expected_parameters, verification_context); @@ -100,10 +108,8 @@ bool PreparedStatementData::RequireRebind(ClientContext &context, if (!unbound_statement) { throw InternalException("Prepared statement without unbound statement"); } - const auto expected_parameters = GetExpectedParameters(*this); + // the values were verified by PopulateMissingParameterValues const bool allow_user_variables = HasNamedParameters(*this); - auto verification_context = allow_user_variables ? &context : nullptr; - PreparedStatement::VerifyParameters(parameter_values, expected_parameters, verification_context); if (properties.always_require_rebind) { // this statement must always be re-bound return true; @@ -112,11 +118,13 @@ bool PreparedStatementData::RequireRebind(ClientContext &context, // parameters not yet bound: query always requires a rebind return true; } + BoundParameterData variable_storage; for (auto &it : value_map) { auto &identifier = it.first; const bool can_read_user_variable = allow_user_variables && PreparedStatement::AllowsUserVariableFallback(identifier); - auto parameter_value = GetParameterValue(context, parameter_values, identifier, can_read_user_variable); + auto ¶meter_value = + GetParameterValue(context, parameter_values, identifier, can_read_user_variable, variable_storage); if (parameter_value.GetValue().type() != it.second->return_type) { return true; } @@ -139,7 +147,8 @@ void PreparedStatementData::Bind(ClientContext &context, const identifier_map_t< // set parameters D_ASSERT(!unbound_statement || unbound_statement->named_param_map.size() == properties.parameter_count); if (unbound_statement || !value_map.empty()) { - const auto expected_parameters = GetExpectedParameters(*this); + identifier_map_t expected_storage; + const auto &expected_parameters = GetExpectedParameters(*this, expected_storage); const bool allow_user_variables = HasNamedParameters(*this); auto verification_context = allow_user_variables ? &context : nullptr; PreparedStatement::VerifyParameters(values, expected_parameters, verification_context); @@ -149,11 +158,12 @@ void PreparedStatementData::Bind(ClientContext &context, const identifier_map_t< // bind the required values const bool allow_user_variables = HasNamedParameters(*this); + BoundParameterData variable_storage; for (auto &it : value_map) { const string &identifier = it.first.GetIdentifierName(); const bool can_read_user_variable = allow_user_variables && PreparedStatement::AllowsUserVariableFallback(it.first); - auto parameter_value = GetParameterValue(context, values, it.first, can_read_user_variable); + auto ¶meter_value = GetParameterValue(context, values, it.first, can_read_user_variable, variable_storage); D_ASSERT(it.second); const auto &value = parameter_value.GetValue(); auto cast_value = value.TryCastAs(context, it.second->return_type); diff --git a/src/duckdb/src/optimizer/distinctness.cpp b/src/duckdb/src/optimizer/distinctness.cpp index cfaa50c69..c58e32a3a 100644 --- a/src/duckdb/src/optimizer/distinctness.cpp +++ b/src/duckdb/src/optimizer/distinctness.cpp @@ -311,6 +311,12 @@ vector Distinctness::ComputeUniqueSets(LogicalOperator &op break; } return ComputeJoinUniqueSets(op.Cast()); + case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: + if (propagation != DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS) { + break; + } + // the output of a materialized CTE is the output of the query that reads it (the second child) + return GetUniqueSets(*op.children[1]); default: break; } diff --git a/src/duckdb/src/optimizer/expression_rewriter.cpp b/src/duckdb/src/optimizer/expression_rewriter.cpp index 1e24c9f90..d343f2504 100644 --- a/src/duckdb/src/optimizer/expression_rewriter.cpp +++ b/src/duckdb/src/optimizer/expression_rewriter.cpp @@ -160,6 +160,12 @@ unique_ptr ExpressionRewriter::ConstantOrNull(ClientContext &context unique_ptr ExpressionRewriter::ConstantOrNull(ClientContext &context, vector> children, Value value) { + for (auto &child : children) { + if (child->GetReturnType().id() == LogicalTypeId::SQLNULL) { + // an untyped NULL child folds the call before its types are resolved: keep the type of the constant + return make_uniq(Value(value.type())); + } + } children.insert(children.begin(), make_uniq(std::move(value))); // constant_or_null has the type of the leading constant, also when a typed NULL child folds the call return BindBuiltinScalarExpression(context, ConstantOrNullFun::Name, std::move(children)); diff --git a/src/duckdb/src/optimizer/join_elimination.cpp b/src/duckdb/src/optimizer/join_elimination.cpp index 7177114b4..9be6f09c6 100644 --- a/src/duckdb/src/optimizer/join_elimination.cpp +++ b/src/duckdb/src/optimizer/join_elimination.cpp @@ -112,8 +112,7 @@ void JoinElimination::OptimizeChild(LogicalOperator &op, idx_t child_idx, JoinEl void JoinElimination::OptimizeJoin(unique_ptr &op) { while (true) { auto &join = *op; - // the pipelines of the two sides inherit the references of the operators above; whatever they find below (table - // filters) stays theirs + // the pipelines of the two sides inherit the references of the operators above auto left_child = CreateChildren(); auto right_child = CreateChildren(); // the joins below must keep the columns this join's conditions read @@ -147,7 +146,7 @@ void JoinElimination::OptimizeJoin(unique_ptr &op) { OptimizeJoinChild(join, 0, *left_child); OptimizeJoinChild(join, 1, *right_child); removed_joins += left_child->removed_joins + right_child->removed_joins; - if (!TryEliminateJoin(op, *left_child, *right_child)) { + if (!TryEliminateJoin(op)) { return; } removed_joins++; @@ -201,10 +200,6 @@ void JoinElimination::OptimizeOperator(unique_ptr &op_ptr, bool break; } - if (op.type == LogicalOperatorType::LOGICAL_GET && op.Cast().table_filters.HasFilters()) { - pipe_info.has_filter = true; - } - if (op.children.size() == 1) { OptimizeChild(op, 0, *this, true); return; @@ -227,8 +222,7 @@ bool JoinElimination::RemovedJoin() const { return removed_joins > 0; } -bool JoinElimination::TryEliminateJoin(unique_ptr &op, JoinElimination &left_child, - JoinElimination &right_child) { +bool JoinElimination::TryEliminateJoin(unique_ptr &op) { auto &join = op->Cast(); idx_t inner_idx = 1; idx_t outer_idx = 0; @@ -243,7 +237,6 @@ bool JoinElimination::TryEliminateJoin(unique_ptr &op, JoinElim default: return false; } - auto &inner_child = inner_idx == 0 ? left_child : right_child; auto &outer_projection_map = outer_idx == 0 ? join.left_projection_map : join.right_projection_map; if (join.filter_pushdown) { return false; @@ -268,9 +261,10 @@ bool JoinElimination::TryEliminateJoin(unique_ptr &op, JoinElim // its outer rows, whatever the inner side holds (a SINGLE join raises an error on a second match, so it is // left to the proof below) is_removable = true; - } else if (!inner_child.pipe_info.has_filter) { + } else { // b) the inner side is distinct on the columns its equality conditions compare: every outer row finds at - // most one match, so the join returns exactly its outer rows. The other conditions only filter the matches. + // most one match, so the join returns exactly its outer rows. The other conditions only filter the matches, + // and so does a filter on the inner side, pushed into a scan or not: it only removes inner rows. // The plan below this join is not rewritten any more, so the unique sets are inferred on a stable plan column_binding_set_t inner_keys; Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS); diff --git a/src/duckdb/src/optimizer/join_order/dphyp_enumerator.cpp b/src/duckdb/src/optimizer/join_order/dphyp_enumerator.cpp new file mode 100644 index 000000000..402ac352f --- /dev/null +++ b/src/duckdb/src/optimizer/join_order/dphyp_enumerator.cpp @@ -0,0 +1,294 @@ +#include "duckdb/optimizer/join_order/dphyp_enumerator.hpp" + +#include "duckdb/optimizer/join_order/query_graph_manager.hpp" + +#include +#include +#include + +namespace duckdb { + +DPHypEnumerator::DPHypEnumerator(QueryGraphManager &graph, const QueryGraphEdges &edges, + JoinOrderCandidateEvaluator &evaluator, JoinOrderPlanMap plans) + : query_graph_manager(graph), query_graph(edges), evaluator(evaluator), plans(std::move(plans)) { +} + +const JoinOrderPlanMap &DPHypEnumerator::GetPlans() const { + return plans; +} + +JoinOrderPlanMap DPHypEnumerator::TakePlans() { + return std::move(plans); +} + +void DPHypEnumerator::ResetAfterGraphChange() { + pairs = 0; + neighbor_set_cache.clear(); +} + +static vector> AddSuperSets(const vector> ¤t, + const vector &all_neighbors) { + vector> ret; + + for (const auto &neighbor_set : current) { + auto max_val = std::max_element(neighbor_set.begin(), neighbor_set.end()); + for (const auto &neighbor : all_neighbors) { + if (*max_val >= neighbor) { + continue; + } + if (neighbor_set.count(neighbor) == 0) { + unordered_set new_set; + for (auto &n : neighbor_set) { + new_set.insert(n); + } + new_set.insert(neighbor); + ret.push_back(new_set); + } + } + } + + return ret; +} + +//! Update the exclusion set with all entries in the subgraph +static void UpdateExclusionSet(optional_ptr node, unordered_set &exclusion_set) { + for (idx_t i = 0; i < node->count; i++) { + exclusion_set.insert(node->relations[i]); + } +} + +// works by first creating all sets with cardinality 1 +// then iterates over each previously created group of subsets and will only add a neighbor if the neighbor +// is greater than all relations in the set. +static vector> GetAllNeighborSets(vector neighbors) { + vector> ret; + sort(neighbors.begin(), neighbors.end()); + vector> added; + for (auto &neighbor : neighbors) { + added.push_back(unordered_set({neighbor})); + ret.push_back(unordered_set({neighbor})); + } + do { + added = AddSuperSets(added, neighbors); + for (auto &d : added) { + ret.push_back(d); + } + } while (!added.empty()); +#if DEBUG + // drive by test to make sure we have an accurate amount of + // subsets, and that each neighbor is in a correct amount + // of those subsets. + D_ASSERT(ret.size() == static_cast(std::pow(2, neighbors.size())) - 1); + for (auto &n : neighbors) { + idx_t count = 0; + for (auto &set : ret) { + if (set.count(n) >= 1) { + count += 1; + } + } + D_ASSERT(count == static_cast(std::pow(2, neighbors.size() - 1))); + } +#endif + return ret; +} + +static idx_t GetNeighborSetCacheKey(const vector &neighbors) { + idx_t key = 0; + for (auto &neighbor : neighbors) { + D_ASSERT(neighbor.index < sizeof(idx_t) * 8); + key |= idx_t(1) << neighbor.index; + } + return key; +} + +const vector> &DPHypEnumerator::GetAllNeighborRelationSets(vector neighbors) { + auto key = GetNeighborSetCacheKey(neighbors); + auto entry = neighbor_set_cache.find(key); + if (entry != neighbor_set_cache.end()) { + return entry->second; + } + + auto all_subset = GetAllNeighborSets(std::move(neighbors)); + vector> relation_sets; + relation_sets.reserve(all_subset.size()); + for (const auto &rel_set : all_subset) { + relation_sets.push_back(query_graph_manager.set_manager.GetJoinRelation(rel_set)); + } + auto inserted = neighbor_set_cache.insert(make_pair(key, std::move(relation_sets))); + return inserted.first->second; +} + +bool DPHypEnumerator::TryEmitPair(JoinRelationSet &left, JoinRelationSet &right, + const vector> &info) { + pairs++; + // If a full plan is created, it's possible a node in the plan gets updated. When this happens, make sure you keep + // emitting pairs until you emit another final plan. Another final plan is guaranteed to be produced because of + // our symmetry guarantees. + if (pairs >= 10000) { + // when the amount of pairs gets too large we exit the dynamic programming and resort to a greedy algorithm + // FIXME: simple heuristic currently + // at 10K pairs stop searching exactly and switch to heuristic + return false; + } + evaluator.EmitPair(plans, left, right, info); + return true; +} + +bool DPHypEnumerator::EmitCSG(JoinRelationSet &node) { + if (node.count == query_graph_manager.relation_manager.NumRelations()) { + return true; + } + // create the exclusion set as everything inside the subgraph AND anything with members BELOW it + unordered_set exclusion_set; + for (idx_t i = 0; i < node.relations[0].index; i++) { + exclusion_set.emplace(i); + } + UpdateExclusionSet(&node, exclusion_set); + // find the neighbors given this exclusion set + auto neighbors = query_graph.GetNeighbors(node, exclusion_set); + if (neighbors.empty()) { + return true; + } + + //! Neighbors should be reversed when iterating over them. + std::sort(neighbors.begin(), neighbors.end(), std::greater()); + for (idx_t i = 0; i < neighbors.size() - 1; i++) { + D_ASSERT(neighbors[i] > neighbors[i + 1]); + } + + // Dphyp paper missing this. + // Because we are traversing in reverse order, we need to add neighbors whose number is smaller than the current + // node to exclusion_set + // This avoids duplicated enumeration + unordered_set new_exclusion_set = exclusion_set; + for (idx_t i = 0; i < neighbors.size(); ++i) { + D_ASSERT(new_exclusion_set.find(neighbors[i]) == new_exclusion_set.end()); + new_exclusion_set.insert(neighbors[i]); + } + + for (auto neighbor : neighbors) { + // since the GetNeighbors only returns the smallest element in a list, the entry might not be connected to + // (only!) this neighbor, hence we have to do a connectedness check before we can emit it + auto &neighbor_relation = query_graph_manager.set_manager.GetJoinRelation(neighbor); + auto &connections = evaluator.GetConnections(node, neighbor_relation); + if (!connections.empty()) { + if (!TryEmitPair(node, neighbor_relation, connections)) { + return false; + } + } + + if (!EnumerateCmpRecursive(node, neighbor_relation, new_exclusion_set)) { + return false; + } + + new_exclusion_set.erase(neighbor); + } + return true; +} + +bool DPHypEnumerator::EnumerateCmpRecursive(JoinRelationSet &left, JoinRelationSet &right, + unordered_set &exclusion_set) { + // get the neighbors of the second relation under the exclusion set + auto neighbors = query_graph.GetNeighbors(right, exclusion_set); + if (neighbors.empty()) { + return true; + } + + auto &all_subset = GetAllNeighborRelationSets(neighbors); + vector> union_sets; + union_sets.reserve(all_subset.size()); + for (auto &neighbor : all_subset) { + // emit the combinations of this node and its neighbors + auto &combined_set = query_graph_manager.set_manager.Union(right, neighbor.get()); + // If combined_set.count == right.count, This means we found a neighbor that has been present before + // This means we didn't set exclusion_set correctly. + D_ASSERT(combined_set.count > right.count); + if (plans.find(combined_set) != plans.end()) { + auto &connections = evaluator.GetConnections(left, combined_set); + if (!connections.empty()) { + if (!TryEmitPair(left, combined_set, connections)) { + return false; + } + } + } + union_sets.push_back(combined_set); + } + + unordered_set new_exclusion_set = exclusion_set; + for (const auto &neighbor : neighbors) { + new_exclusion_set.insert(neighbor); + } + + // recursively enumerate the sets + for (idx_t i = 0; i < union_sets.size(); i++) { + // updated the set of excluded entries with this neighbor + if (!EnumerateCmpRecursive(left, union_sets[i], new_exclusion_set)) { + return false; + } + } + return true; +} + +bool DPHypEnumerator::EnumerateCSGRecursive(JoinRelationSet &node, unordered_set &exclusion_set) { + // find neighbors of S under the exclusion set + auto neighbors = query_graph.GetNeighbors(node, exclusion_set); + if (neighbors.empty()) { + return true; + } + + auto &all_subset = GetAllNeighborRelationSets(neighbors); + vector> union_sets; + union_sets.reserve(all_subset.size()); + for (auto &neighbor : all_subset) { + // emit the combinations of this node and its neighbors + auto &new_set = query_graph_manager.set_manager.Union(node, neighbor.get()); + D_ASSERT(new_set.count > node.count); + if (plans.find(new_set) != plans.end()) { + if (!EmitCSG(new_set)) { + return false; + } + } + union_sets.push_back(new_set); + } + + unordered_set new_exclusion_set = exclusion_set; + for (const auto &neighbor : neighbors) { + new_exclusion_set.insert(neighbor); + } + + // recursively enumerate the sets + for (idx_t i = 0; i < union_sets.size(); i++) { + // updated the set of excluded entries with this neighbor + if (!EnumerateCSGRecursive(union_sets[i], new_exclusion_set)) { + return false; + } + } + return true; +} + +// "Dynamic Programming Strikes Back" by Guido Moerkotte and Thomas Neumann. +// https://db.in.tum.de/teaching/ws1415/queryopt/chapter3.pdf?lang=de +bool DPHypEnumerator::Solve() { + // now we perform the actual dynamic programming to compute the final result + // we enumerate over all the possible pairs in the neighborhood + for (idx_t i = query_graph_manager.relation_manager.NumRelations(); i > 0; i--) { + // for every node in the set, we consider it as the start node once + auto &start_node = query_graph_manager.set_manager.GetJoinRelation(RelationIndex(i - 1)); + // emit the start node + if (!EmitCSG(start_node)) { + return false; + } + // initialize the set of exclusion_set as all the nodes with a number below this + unordered_set exclusion_set; + for (idx_t j = 0; j < i; j++) { + exclusion_set.emplace(j); + } + // then we recursively search for neighbors that do not belong to the banned entries + if (!EnumerateCSGRecursive(start_node, exclusion_set)) { + return false; + } + } + return true; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/greedy_join_enumerator.cpp b/src/duckdb/src/optimizer/join_order/greedy_join_enumerator.cpp new file mode 100644 index 000000000..11c80d036 --- /dev/null +++ b/src/duckdb/src/optimizer/join_order/greedy_join_enumerator.cpp @@ -0,0 +1,135 @@ +#include "duckdb/optimizer/join_order/greedy_join_enumerator.hpp" + +#include "duckdb/optimizer/join_order/query_graph_manager.hpp" + +namespace duckdb { + +GreedyJoinEnumerator::GreedyJoinEnumerator(QueryGraphManager &graph, JoinOrderCandidateEvaluator &evaluator) + : query_graph_manager(graph), evaluator(evaluator) { +} + +bool GreedyJoinEnumerator::Solve(JoinOrderPlanMap &plans) { + // at this point, we exited the dynamic programming but did not compute the final join order because it took too + // long instead, we use a greedy heuristic to obtain a join ordering now we use Greedy Operator Ordering to + // construct the result tree first we start out with all the base relations (the to-be-joined relations) + vector> join_relations; // T in the paper + for (idx_t i = 0; i < query_graph_manager.relation_manager.NumRelations(); i++) { + join_relations.push_back(query_graph_manager.set_manager.GetJoinRelation(RelationIndex(i))); + } + + // in every step of the algorithm, we greedily pick the join between the to-be-joined relations that has the + // smallest cost. Pair costs are deterministic while the query graph is unchanged, so we evaluate each pair once + // and keep the viable candidates in a list, instead of re-emitting every pair in every step + struct GreedyCandidate { + optional_ptr left; + optional_ptr right; + JoinPlanCost cost; + }; + vector candidates; + auto EmitOrientation = [&](JoinRelationSet &left, JoinRelationSet &right) -> optional_ptr { + auto &connection = evaluator.GetConnections(left, right); + if (connection.empty()) { + return nullptr; + } + return evaluator.EmitPair(plans, left, right, connection); + }; + auto EmitCandidate = [&](JoinRelationSet &left, JoinRelationSet &right) { + // non-commutative joins (e.g. LEFT, SEMI, ANTI) are only valid in one orientation + auto node = EmitOrientation(left, right); + if (!node) { + node = EmitOrientation(right, left); + } + if (node) { + candidates.push_back({&left, &right, evaluator.GetPlanCost(*node)}); + } + }; + auto InitializeCandidates = [&]() { + candidates.clear(); + for (idx_t i = 0; i < join_relations.size(); i++) { + for (idx_t j = i + 1; j < join_relations.size(); j++) { + EmitCandidate(join_relations[i], join_relations[j]); + } + } + }; + InitializeCandidates(); + + while (join_relations.size() > 1) { + optional_ptr best_left; + optional_ptr best_right; + JoinPlanCost best_cost {NumericLimits::Maximum(), NumericLimits::Maximum()}; + for (auto &candidate : candidates) { + if (!best_left || candidate.cost < best_cost) { + best_cost = candidate.cost; + best_left = candidate.left; + best_right = candidate.right; + } + } + if (!best_left) { + if (evaluator.ActivateRequiredCrossProducts()) { + // the query graph gained edges, which invalidates the evaluated candidates + InitializeCandidates(); + continue; + } + // Optimizer-introduced cross products are valid only inside an inner-join companion set (Section 6.2). + for (idx_t i = 0; i < join_relations.size(); i++) { + auto &left = join_relations[i].get(); + for (idx_t j = i + 1; j < join_relations.size(); j++) { + auto &right = join_relations[j].get(); + if (!query_graph_manager.CanCreateCrossProduct(left, right)) { + continue; + } + auto left_plan = plans.find(left); + auto right_plan = plans.find(right); + D_ASSERT(left_plan != plans.end() && right_plan != plans.end()); + auto left_cost = evaluator.GetPlanCost(*left_plan->second); + auto right_cost = evaluator.GetPlanCost(*right_plan->second); + JoinPlanCost cost {left_cost.work + right_cost.work, + MaxValue(left_cost.memory_excess, right_cost.memory_excess)}; + if (!best_left || cost < best_cost) { + best_cost = cost; + best_left = left; + best_right = right; + } + } + } + if (!best_left) { + return false; + } + // create a cross product edge (i.e. edge with empty filter) between these two sets in the query graph + auto &connections = evaluator.CreateCrossProduct(*best_left, *best_right); + // the new edge only connects this pair, which is merged below, so the other candidates remain valid + // now emit the pair and continue with the algorithm + D_ASSERT(!connections.empty()); + + auto cross_product = evaluator.EmitPair(plans, *best_left, *best_right, connections); + if (!cross_product) { + return false; + } + } + // now update the to-be-checked pairs: remove left and right, and add the combination + auto &new_set = query_graph_manager.set_manager.Union(*best_left, *best_right); + for (idx_t i = join_relations.size(); i > 0; i--) { + auto &relation = join_relations[i - 1].get(); + if (&relation == best_left.get() || &relation == best_right.get()) { + join_relations.erase(join_relations.begin() + NumericCast(i - 1)); + } + } + idx_t kept_candidates = 0; + for (idx_t candidate_idx = 0; candidate_idx < candidates.size(); candidate_idx++) { + auto &candidate = candidates[candidate_idx]; + if (candidate.left == best_left || candidate.left == best_right || candidate.right == best_left || + candidate.right == best_right) { + continue; + } + candidates[kept_candidates++] = candidate; + } + candidates.resize(kept_candidates); + for (auto &relation : join_relations) { + EmitCandidate(relation, new_set); + } + join_relations.push_back(new_set); + } + return true; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/join_order_candidate.cpp b/src/duckdb/src/optimizer/join_order/join_order_candidate.cpp new file mode 100644 index 000000000..e374e88d3 --- /dev/null +++ b/src/duckdb/src/optimizer/join_order/join_order_candidate.cpp @@ -0,0 +1,225 @@ +#include "duckdb/optimizer/join_order/join_order_candidate.hpp" + +#include "duckdb/optimizer/join_order/query_graph_manager.hpp" + +namespace duckdb { + +JoinOrderCandidateEvaluator::JoinOrderCandidateEvaluator(QueryGraphManager &graph, CostModel &cost_model, + const QueryGraphEdges &edges) + : query_graph_manager(graph), cost_model(cost_model), query_graph(edges) { +} + +JoinPlanCost JoinOrderCandidateEvaluator::GetPlanCost(const DPJoinNode &node) const { + return cost_model.GetCost(node); +} + +const vector> &JoinOrderCandidateEvaluator::GetConnections(JoinRelationSet &left, + JoinRelationSet &right) { + auto &left_cache = connection_cache[left]; + auto entry = left_cache.find(right); + if (entry != left_cache.end()) { + return entry->second; + } + auto connections = query_graph.GetConnections(left, right); + auto inserted = left_cache.insert(make_pair(reference(right), std::move(connections))); + return inserted.first->second; +} + +static bool EnablesJoinKey(const JoinPredicateModel &predicates, JoinRelationSet &set, JoinRelationSet &left, + JoinRelationSet &right) { + auto needs_both_inputs = [&](optional_ptr key) { + return key && JoinRelationSet::Intersects(left, *key) && JoinRelationSet::Intersects(right, *key); + }; + for (auto &predicate_ref : predicates.GetGraphPredicates()) { + auto &predicate = predicate_ref.get(); + if (!JoinRelationSet::IsSubset(set, predicate.GetSet()) && + (needs_both_inputs(predicate.GetLeftSetOptional()) || needs_both_inputs(predicate.GetRightSetOptional()))) { + return true; + } + } + return false; +} + +unique_ptr +JoinOrderCandidateEvaluator::CreateJoinTree(JoinRelationSet &set, + const vector> &possible_connections, + DPJoinNode &left, DPJoinNode &right) { + // FIXME: should consider different join algorithms, should we pick a join algorithm here as well? (probably) + vector> applicable_connections; + struct JoinCandidate { + optional_ptr join_operator; + vector> predicates; + bool generated_cross_product = false; + idx_t priority = 0; + }; + vector candidates; + for (auto &connection_ref : possible_connections) { + auto &connection = connection_ref.get(); + if (!query_graph_manager.IsConnectionApplicable(connection, left.set, right.set)) { + continue; + } + applicable_connections.push_back(connection); + optional_ptr candidate; + for (auto &entry : candidates) { + if (entry.join_operator == connection.join_operator && + entry.generated_cross_product == connection.generated_cross_product) { + candidate = entry; + break; + } + } + if (!candidate) { + candidates.emplace_back(); + candidate = candidates.back(); + candidate->join_operator = connection.join_operator; + candidate->generated_cross_product = connection.generated_cross_product; + } + candidate->predicates.insert(candidate->predicates.end(), connection.predicates.begin(), + connection.predicates.end()); + idx_t priority = 0; + if (!connection.predicates.empty()) { + priority = 3; + } else if (connection.join_operator) { + priority = 2; + } else if (connection.generated_cross_product) { + priority = 1; + } + candidate->priority = MaxValue(candidate->priority, priority); + } + if (applicable_connections.empty()) { + return nullptr; + } + optional_ptr best_candidate; + for (auto &candidate : candidates) { + if (!query_graph_manager.IsJoinOrderCandidate(candidate.join_operator, candidate.generated_cross_product, + left.set, right.set)) { + continue; + } + if (!best_candidate || candidate.priority > best_candidate->priority) { + best_candidate = candidate; + } + } + if (!best_candidate) { + return nullptr; + } + auto cardinality = cost_model.GetCardinalityEstimator().EstimateCardinality(set); + // Avoid large expanding independent builds unless the inputs contribute to the same join key. + if (recursive_frontier_estimate > 0 && !left.recursive_properties.depends_on_recursive_input && + !right.recursive_properties.depends_on_recursive_input) { + auto output = cardinality.GetDouble(); + if (output > left.cardinality.GetDouble() && output > right.cardinality.GetDouble() && + output > recursive_frontier_estimate && + !EnablesJoinKey(query_graph_manager.GetPredicateModel(), set, left.set, right.set)) { + return nullptr; + } + } + auto cost = cost_model.ComputeCost(left, right, best_candidate->join_operator, cardinality.GetDouble()); + 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; + cost_model.UpdateBuildMemory(*result, left, right); + return result; +} + +optional_ptr JoinOrderCandidateEvaluator::EmitPair(JoinOrderPlanMap &plans, JoinRelationSet &left, + JoinRelationSet &right, + const vector> &info) { + auto &set = query_graph_manager.set_manager.Union(left, right); + // get the left and right join plans + auto left_plan = plans.find(left); + auto right_plan = plans.find(right); + if (left_plan == plans.end() || right_plan == plans.end()) { + throw InternalException("No left or right plan: internal error in join order optimizer"); + } + // create the join tree based on combining the two plans + return ConsiderJoinTree(plans, CreateJoinTree(set, info, *left_plan->second, *right_plan->second)); +} + +optional_ptr JoinOrderCandidateEvaluator::ConsiderJoinTree(JoinOrderPlanMap &plans, + unique_ptr new_plan) { + if (!new_plan) { + return nullptr; + } + auto &new_set = new_plan->set; + // check if this plan is the optimal plan we found for this set of relations + auto entry = plans.find(new_set); + auto new_cost = GetPlanCost(*new_plan); + JoinPlanCost old_cost {NumericLimits::Maximum(), NumericLimits::Maximum()}; + if (entry != plans.end()) { + old_cost = GetPlanCost(*entry->second); + } + if (entry == plans.end() || new_cost < old_cost) { + // the new plan costs less than the old plan. Update our DP table. + plans[new_set] = std::move(new_plan); + return plans[new_set].get(); + } + // Tiebreaker for equal-cost plans: needed for LEFT JOINs, + // because all orderings preserve the LHS cardinality and always tie. + // This tiebreaker causes less joins to be flipped from LEFT to RIGHT + // later by the BuildProbeSideOptimizer, and we strongly prefer LEFT + if (new_cost == old_cost) { + auto new_right_cardinality = plans.at(new_plan->right_set)->cardinality; + auto existing_right = plans.find(entry->second->right_set); + if (existing_right != plans.end()) { + auto old_right_cardinality = existing_right->second->cardinality; + if (new_right_cardinality > old_right_cardinality) { + plans[new_set] = std::move(new_plan); + return plans[new_set].get(); + } + } + } + // Create join node from the plan currently in the DP table. + return entry->second.get(); +} + +void JoinOrderCandidateEvaluator::InitLeafPlans(JoinOrderPlanMap &plans) { + auto relation_stats = query_graph_manager.relation_manager.GetRelationStats(); + auto &estimator = cost_model.GetCardinalityEstimator(); + estimator.Initialize(relation_stats, query_graph_manager.GetJoinOperators(), + query_graph_manager.relation_manager.GetColumnSources()); + for (idx_t i = 0; i < relation_stats.size(); i++) { + auto &relation_set = query_graph_manager.set_manager.GetJoinRelation(RelationIndex(i)); + auto join_node = make_uniq(relation_set); + join_node->cost = 0; + join_node->cardinality = estimator.EstimateCardinality(relation_set); + if (query_graph_manager.relation_manager.HasRecursiveRelations()) { + auto &relation = query_graph_manager.relation_manager.GetRelation(RelationIndex(i)); + relation.op.ResolveOperatorTypes(); + join_node->recursive_properties = relation.recursive_properties; + if (join_node->recursive_properties.depends_on_recursive_input) { + recursive_frontier_estimate = MaxValue(recursive_frontier_estimate, join_node->cardinality.GetDouble()); + } + } + plans[relation_set] = std::move(join_node); + } +} + +void JoinOrderCandidateEvaluator::InitInputPlan(JoinOrderPlanMap &plans) { + for (auto &op : query_graph_manager.GetJoinOperators()) { + auto &left = op->left_relations.get(); + auto &right = op->right_relations.get(); + if (plans.find(left) == plans.end() || plans.find(right) == plans.end()) { + continue; + } + auto &connections = GetConnections(left, right); + if (!connections.empty()) { + EmitPair(plans, left, right, connections); + } + } +} + +bool JoinOrderCandidateEvaluator::ActivateRequiredCrossProducts() { + if (!query_graph_manager.ActivateRequiredCrossProducts()) { + return false; + } + connection_cache.clear(); + return true; +} + +const vector> &JoinOrderCandidateEvaluator::CreateCrossProduct(JoinRelationSet &left, + JoinRelationSet &right) { + query_graph_manager.CreateQueryGraphCrossProduct(left, right); + connection_cache.clear(); + return GetConnections(left, right); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp b/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp index a1ccc205e..b1eb41535 100644 --- a/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp +++ b/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp @@ -1,595 +1,40 @@ #include "duckdb/optimizer/join_order/plan_enumerator.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/optimizer/join_order/join_node.hpp" -#include "duckdb/optimizer/join_order/query_graph_manager.hpp" #include "duckdb/main/settings.hpp" - -#include +#include "duckdb/optimizer/join_order/dphyp_enumerator.hpp" +#include "duckdb/optimizer/join_order/greedy_join_enumerator.hpp" +#include "duckdb/optimizer/join_order/query_graph_manager.hpp" namespace duckdb { -PlanEnumerator::PlanEnumerator(QueryGraphManager &query_graph_manager, CostModel &cost_model, - const QueryGraphEdges &query_graph) - : query_graph(query_graph), query_graph_manager(query_graph_manager), cost_model(cost_model) { -} - -static vector> AddSuperSets(const vector> ¤t, - const vector &all_neighbors) { - vector> ret; - - for (const auto &neighbor_set : current) { - auto max_val = std::max_element(neighbor_set.begin(), neighbor_set.end()); - for (const auto &neighbor : all_neighbors) { - if (*max_val >= neighbor) { - continue; - } - if (neighbor_set.count(neighbor) == 0) { - unordered_set new_set; - for (auto &n : neighbor_set) { - new_set.insert(n); - } - new_set.insert(neighbor); - ret.push_back(new_set); - } - } - } - - return ret; -} - -//! Update the exclusion set with all entries in the subgraph -static void UpdateExclusionSet(optional_ptr node, unordered_set &exclusion_set) { - for (idx_t i = 0; i < node->count; i++) { - exclusion_set.insert(node->relations[i]); - } -} - -// works by first creating all sets with cardinality 1 -// then iterates over each previously created group of subsets and will only add a neighbor if the neighbor -// is greater than all relations in the set. -static vector> GetAllNeighborSets(vector neighbors) { - vector> ret; - sort(neighbors.begin(), neighbors.end()); - vector> added; - for (auto &neighbor : neighbors) { - added.push_back(unordered_set({neighbor})); - ret.push_back(unordered_set({neighbor})); - } - do { - added = AddSuperSets(added, neighbors); - for (auto &d : added) { - ret.push_back(d); - } - } while (!added.empty()); -#if DEBUG - // drive by test to make sure we have an accurate amount of - // subsets, and that each neighbor is in a correct amount - // of those subsets. - D_ASSERT(ret.size() == static_cast(std::pow(2, neighbors.size())) - 1); - for (auto &n : neighbors) { - idx_t count = 0; - for (auto &set : ret) { - if (set.count(n) >= 1) { - count += 1; - } - } - D_ASSERT(count == static_cast(std::pow(2, neighbors.size() - 1))); - } -#endif - return ret; +PlanEnumerator::PlanEnumerator(QueryGraphManager &graph, CostModel &cost_model, const QueryGraphEdges &edges) + : query_graph_manager(graph), query_graph(edges), candidate_evaluator(graph, cost_model, edges) { } -const reference_map_t> &PlanEnumerator::GetPlans() const { +const JoinOrderPlanMap &PlanEnumerator::GetPlans() const { return plans; } -const vector> &PlanEnumerator::GetConnections(JoinRelationSet &left, JoinRelationSet &right) { - auto &left_cache = connection_cache[left]; - auto entry = left_cache.find(right); - if (entry != left_cache.end()) { - return entry->second; - } - auto connections = query_graph.GetConnections(left, right); - auto inserted = left_cache.insert(make_pair(reference(right), std::move(connections))); - return inserted.first->second; -} - -static idx_t GetNeighborSetCacheKey(const vector &neighbors) { - idx_t key = 0; - for (auto &neighbor : neighbors) { - D_ASSERT(neighbor.index < sizeof(idx_t) * 8); - key |= idx_t(1) << neighbor.index; - } - return key; -} - -const vector> &PlanEnumerator::GetAllNeighborRelationSets(vector neighbors) { - auto key = GetNeighborSetCacheKey(neighbors); - auto entry = neighbor_set_cache.find(key); - if (entry != neighbor_set_cache.end()) { - return entry->second; - } - - auto all_subset = GetAllNeighborSets(std::move(neighbors)); - vector> relation_sets; - relation_sets.reserve(all_subset.size()); - for (const auto &rel_set : all_subset) { - relation_sets.push_back(query_graph_manager.set_manager.GetJoinRelation(rel_set)); - } - auto inserted = neighbor_set_cache.insert(make_pair(key, std::move(relation_sets))); - return inserted.first->second; -} - -static bool EnablesJoinKey(const JoinPredicateModel &predicates, JoinRelationSet &set, JoinRelationSet &left, - JoinRelationSet &right) { - auto needs_both_inputs = [&](optional_ptr key) { - return key && JoinRelationSet::Intersects(left, *key) && JoinRelationSet::Intersects(right, *key); - }; - for (auto &predicate_ref : predicates.GetGraphPredicates()) { - auto &predicate = predicate_ref.get(); - if (!JoinRelationSet::IsSubset(set, predicate.GetSet()) && - (needs_both_inputs(predicate.GetLeftSetOptional()) || needs_both_inputs(predicate.GetRightSetOptional()))) { - return true; - } - } - return false; -} - -//! Create a new JoinTree node by joining together two previous JoinTree nodes -unique_ptr PlanEnumerator::CreateJoinTree(JoinRelationSet &set, - const vector> &possible_connections, - DPJoinNode &left, DPJoinNode &right) { - // FIXME: should consider different join algorithms, should we pick a join algorithm here as well? (probably) - vector> applicable_connections; - struct JoinCandidate { - optional_ptr join_operator; - vector> predicates; - bool generated_cross_product = false; - idx_t priority = 0; - }; - vector candidates; - for (auto &connection_ref : possible_connections) { - auto &connection = connection_ref.get(); - if (!query_graph_manager.IsConnectionApplicable(connection, left.set, right.set)) { - continue; - } - applicable_connections.push_back(connection); - optional_ptr candidate; - for (auto &entry : candidates) { - if (entry.join_operator == connection.join_operator && - entry.generated_cross_product == connection.generated_cross_product) { - candidate = entry; - break; - } - } - if (!candidate) { - candidates.emplace_back(); - candidate = candidates.back(); - candidate->join_operator = connection.join_operator; - candidate->generated_cross_product = connection.generated_cross_product; - } - candidate->predicates.insert(candidate->predicates.end(), connection.predicates.begin(), - connection.predicates.end()); - idx_t priority = 0; - if (!connection.predicates.empty()) { - priority = 3; - } else if (connection.join_operator) { - priority = 2; - } else if (connection.generated_cross_product) { - priority = 1; - } - candidate->priority = MaxValue(candidate->priority, priority); - } - if (applicable_connections.empty()) { - return nullptr; - } - optional_ptr best_candidate; - for (auto &candidate : candidates) { - if (!query_graph_manager.IsJoinOrderCandidate(candidate.join_operator, candidate.generated_cross_product, - left.set, right.set)) { - continue; - } - if (!best_candidate || candidate.priority > best_candidate->priority) { - best_candidate = candidate; - } - } - if (!best_candidate) { - return nullptr; - } - auto cardinality = cost_model.GetCardinalityEstimator().EstimateCardinality(set); - // Avoid large expanding independent builds unless the inputs contribute to the same join key. - if (recursive_frontier_estimate > 0 && !left.recursive_properties.depends_on_recursive_input && - !right.recursive_properties.depends_on_recursive_input) { - auto output = cardinality.GetDouble(); - if (output > left.cardinality.GetDouble() && output > right.cardinality.GetDouble() && - output > recursive_frontier_estimate && - !EnablesJoinKey(query_graph_manager.GetPredicateModel(), set, left.set, right.set)) { - return nullptr; - } - } - auto cost = cost_model.ComputeCost(left, right, best_candidate->join_operator, cardinality.GetDouble()); - 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; - cost_model.UpdateBuildMemory(*result, left, right); - return result; -} - -optional_ptr PlanEnumerator::EmitPair(JoinRelationSet &left, JoinRelationSet &right, - const vector> &info) { - // get the left and right join plans - auto left_plan = plans.find(left); - auto right_plan = plans.find(right); - if (left_plan == plans.end() || right_plan == plans.end()) { - throw InternalException("No left or right plan: internal error in join order optimizer"); - } - auto &new_set = query_graph_manager.set_manager.Union(left, right); - // create the join tree based on combining the two plans - auto new_plan = CreateJoinTree(new_set, info, *left_plan->second, *right_plan->second); - if (!new_plan) { - return nullptr; - } - // check if this plan is the optimal plan we found for this set of relations - auto entry = plans.find(new_set); - auto new_cost = cost_model.GetCost(*new_plan); - JoinPlanCost old_cost {NumericLimits::Maximum(), NumericLimits::Maximum()}; - if (entry != plans.end()) { - old_cost = cost_model.GetCost(*entry->second); - } - if (entry == plans.end() || new_cost < old_cost) { - // the new plan costs less than the old plan. Update our DP table. - plans[new_set] = std::move(new_plan); - return plans[new_set].get(); - } - // Tiebreaker for equal-cost plans: needed for LEFT JOINs, - // because all orderings preserve the LHS cardinality and always tie. - // This tiebreaker causes less joins to be flipped from LEFT to RIGHT - // later by the BuildProbeSideOptimizer, and we strongly prefer LEFT - if (new_cost == old_cost) { - auto new_right_cardinality = right_plan->second->cardinality; - auto existing_right = plans.find(entry->second->right_set); - if (existing_right != plans.end()) { - auto old_right_cardinality = existing_right->second->cardinality; - if (new_right_cardinality > old_right_cardinality) { - plans[new_set] = std::move(new_plan); - return plans[new_set].get(); - } - } - } - // Create join node from the plan currently in the DP table. - return entry->second.get(); -} - -bool PlanEnumerator::TryEmitPair(JoinRelationSet &left, JoinRelationSet &right, - const vector> &info) { - pairs++; - // If a full plan is created, it's possible a node in the plan gets updated. When this happens, make sure you keep - // emitting pairs until you emit another final plan. Another final plan is guaranteed to be produced because of - // our symmetry guarantees. - if (pairs >= 10000) { - // when the amount of pairs gets too large we exit the dynamic programming and resort to a greedy algorithm - // FIXME: simple heuristic currently - // at 10K pairs stop searching exactly and switch to heuristic - return false; - } - EmitPair(left, right, info); - return true; -} - -bool PlanEnumerator::EmitCSG(JoinRelationSet &node) { - if (node.count == query_graph_manager.relation_manager.NumRelations()) { - return true; - } - // create the exclusion set as everything inside the subgraph AND anything with members BELOW it - unordered_set exclusion_set; - for (idx_t i = 0; i < node.relations[0].index; i++) { - exclusion_set.emplace(i); - } - UpdateExclusionSet(&node, exclusion_set); - // find the neighbors given this exclusion set - auto neighbors = query_graph.GetNeighbors(node, exclusion_set); - if (neighbors.empty()) { - return true; - } - - //! Neighbors should be reversed when iterating over them. - std::sort(neighbors.begin(), neighbors.end(), std::greater()); - for (idx_t i = 0; i < neighbors.size() - 1; i++) { - D_ASSERT(neighbors[i] > neighbors[i + 1]); - } - - // Dphyp paper missing this. - // Because we are traversing in reverse order, we need to add neighbors whose number is smaller than the current - // node to exclusion_set - // This avoids duplicated enumeration - unordered_set new_exclusion_set = exclusion_set; - for (idx_t i = 0; i < neighbors.size(); ++i) { - D_ASSERT(new_exclusion_set.find(neighbors[i]) == new_exclusion_set.end()); - new_exclusion_set.insert(neighbors[i]); - } - - for (auto neighbor : neighbors) { - // since the GetNeighbors only returns the smallest element in a list, the entry might not be connected to - // (only!) this neighbor, hence we have to do a connectedness check before we can emit it - auto &neighbor_relation = query_graph_manager.set_manager.GetJoinRelation(neighbor); - auto &connections = GetConnections(node, neighbor_relation); - if (!connections.empty()) { - if (!TryEmitPair(node, neighbor_relation, connections)) { - return false; - } - } - - if (!EnumerateCmpRecursive(node, neighbor_relation, new_exclusion_set)) { - return false; - } - - new_exclusion_set.erase(neighbor); - } - return true; -} - -bool PlanEnumerator::EnumerateCmpRecursive(JoinRelationSet &left, JoinRelationSet &right, - unordered_set &exclusion_set) { - // get the neighbors of the second relation under the exclusion set - auto neighbors = query_graph.GetNeighbors(right, exclusion_set); - if (neighbors.empty()) { - return true; - } - - auto &all_subset = GetAllNeighborRelationSets(neighbors); - vector> union_sets; - union_sets.reserve(all_subset.size()); - for (auto &neighbor : all_subset) { - // emit the combinations of this node and its neighbors - auto &combined_set = query_graph_manager.set_manager.Union(right, neighbor.get()); - // If combined_set.count == right.count, This means we found a neighbor that has been present before - // This means we didn't set exclusion_set correctly. - D_ASSERT(combined_set.count > right.count); - if (plans.find(combined_set) != plans.end()) { - auto &connections = GetConnections(left, combined_set); - if (!connections.empty()) { - if (!TryEmitPair(left, combined_set, connections)) { - return false; - } - } - } - union_sets.push_back(combined_set); - } - - unordered_set new_exclusion_set = exclusion_set; - for (const auto &neighbor : neighbors) { - new_exclusion_set.insert(neighbor); - } - - // recursively enumerate the sets - for (idx_t i = 0; i < union_sets.size(); i++) { - // updated the set of excluded entries with this neighbor - if (!EnumerateCmpRecursive(left, union_sets[i], new_exclusion_set)) { - return false; - } - } - return true; -} - -bool PlanEnumerator::EnumerateCSGRecursive(JoinRelationSet &node, unordered_set &exclusion_set) { - // find neighbors of S under the exclusion set - auto neighbors = query_graph.GetNeighbors(node, exclusion_set); - if (neighbors.empty()) { - return true; - } - - auto &all_subset = GetAllNeighborRelationSets(neighbors); - vector> union_sets; - union_sets.reserve(all_subset.size()); - for (auto &neighbor : all_subset) { - // emit the combinations of this node and its neighbors - auto &new_set = query_graph_manager.set_manager.Union(node, neighbor.get()); - D_ASSERT(new_set.count > node.count); - if (plans.find(new_set) != plans.end()) { - if (!EmitCSG(new_set)) { - return false; - } - } - union_sets.push_back(new_set); - } - - unordered_set new_exclusion_set = exclusion_set; - for (const auto &neighbor : neighbors) { - new_exclusion_set.insert(neighbor); - } - - // recursively enumerate the sets - for (idx_t i = 0; i < union_sets.size(); i++) { - // updated the set of excluded entries with this neighbor - if (!EnumerateCSGRecursive(union_sets[i], new_exclusion_set)) { - return false; - } - } - return true; -} - -bool PlanEnumerator::SolveJoinOrderExactly() { - // now we perform the actual dynamic programming to compute the final result - // we enumerate over all the possible pairs in the neighborhood - for (idx_t i = query_graph_manager.relation_manager.NumRelations(); i > 0; i--) { - // for every node in the set, we consider it as the start node once - auto &start_node = query_graph_manager.set_manager.GetJoinRelation(RelationIndex(i - 1)); - // emit the start node - if (!EmitCSG(start_node)) { - return false; - } - // initialize the set of exclusion_set as all the nodes with a number below this - unordered_set exclusion_set; - for (idx_t j = 0; j < i; j++) { - exclusion_set.emplace(j); - } - // then we recursively search for neighbors that do not belong to the banned entries - if (!EnumerateCSGRecursive(start_node, exclusion_set)) { - return false; - } - } - return true; +void PlanEnumerator::InitLeafPlans() { + candidate_evaluator.InitLeafPlans(plans); } bool PlanEnumerator::SolveJoinOrderApproximately() { - // Keep the incoming join order as a candidate for the greedy search. - for (auto &op : query_graph_manager.GetJoinOperators()) { - auto &left = op->left_relations.get(); - auto &right = op->right_relations.get(); - if (plans.find(left) == plans.end() || plans.find(right) == plans.end()) { - continue; - } - auto &connections = GetConnections(left, right); - if (!connections.empty()) { - EmitPair(left, right, connections); - } - } - // at this point, we exited the dynamic programming but did not compute the final join order because it took too - // long instead, we use a greedy heuristic to obtain a join ordering now we use Greedy Operator Ordering to - // construct the result tree first we start out with all the base relations (the to-be-joined relations) - vector> join_relations; // T in the paper - for (idx_t i = 0; i < query_graph_manager.relation_manager.NumRelations(); i++) { - join_relations.push_back(query_graph_manager.set_manager.GetJoinRelation(RelationIndex(i))); - } - - // in every step of the algorithm, we greedily pick the join between the to-be-joined relations that has the - // smallest cost. Pair costs are deterministic while the query graph is unchanged, so we evaluate each pair once - // and keep the viable candidates in a list, instead of re-emitting every pair in every step - struct GreedyCandidate { - optional_ptr left; - optional_ptr right; - JoinPlanCost cost; - }; - vector candidates; - auto EmitOrientation = [&](JoinRelationSet &left, JoinRelationSet &right) -> optional_ptr { - auto &connection = GetConnections(left, right); - if (connection.empty()) { - return nullptr; - } - return EmitPair(left, right, connection); - }; - auto EmitCandidate = [&](JoinRelationSet &left, JoinRelationSet &right) { - // non-commutative joins (e.g. LEFT, SEMI, ANTI) are only valid in one orientation - auto node = EmitOrientation(left, right); - if (!node) { - node = EmitOrientation(right, left); - } - if (node) { - candidates.push_back({&left, &right, cost_model.GetCost(*node)}); - } - }; - auto InitializeCandidates = [&]() { - candidates.clear(); - for (idx_t i = 0; i < join_relations.size(); i++) { - for (idx_t j = i + 1; j < join_relations.size(); j++) { - EmitCandidate(join_relations[i], join_relations[j]); - } - } - }; - InitializeCandidates(); - - while (join_relations.size() > 1) { - optional_ptr best_left; - optional_ptr best_right; - JoinPlanCost best_cost {NumericLimits::Maximum(), NumericLimits::Maximum()}; - for (auto &candidate : candidates) { - if (!best_left || candidate.cost < best_cost) { - best_cost = candidate.cost; - best_left = candidate.left; - best_right = candidate.right; - } - } - if (!best_left) { - if (ActivateRequiredCrossProducts()) { - // the query graph gained edges, which invalidates the evaluated candidates - InitializeCandidates(); - continue; - } - // Optimizer-introduced cross products are valid only inside an inner-join companion set (Section 6.2). - for (idx_t i = 0; i < join_relations.size(); i++) { - auto &left = join_relations[i].get(); - for (idx_t j = i + 1; j < join_relations.size(); j++) { - auto &right = join_relations[j].get(); - if (!query_graph_manager.CanCreateCrossProduct(left, right)) { - continue; - } - auto left_plan = plans.find(left); - auto right_plan = plans.find(right); - D_ASSERT(left_plan != plans.end() && right_plan != plans.end()); - auto left_cost = cost_model.GetCost(*left_plan->second); - auto right_cost = cost_model.GetCost(*right_plan->second); - JoinPlanCost cost {left_cost.work + right_cost.work, - MaxValue(left_cost.memory_excess, right_cost.memory_excess)}; - if (!best_left || cost < best_cost) { - best_cost = cost; - best_left = left; - best_right = right; - } - } - } - if (!best_left) { - return false; - } - // create a cross product edge (i.e. edge with empty filter) between these two sets in the query graph - query_graph_manager.CreateQueryGraphCrossProduct(*best_left, *best_right); - // the new edge only connects this pair, which is merged below, so the other candidates remain valid - connection_cache.clear(); - // now emit the pair and continue with the algorithm - auto &connections = GetConnections(*best_left, *best_right); - D_ASSERT(!connections.empty()); - - auto cross_product = EmitPair(*best_left, *best_right, connections); - if (!cross_product) { - return false; - } - } - // now update the to-be-checked pairs: remove left and right, and add the combination - auto &new_set = query_graph_manager.set_manager.Union(*best_left, *best_right); - for (idx_t i = join_relations.size(); i > 0; i--) { - auto &relation = join_relations[i - 1].get(); - if (&relation == best_left.get() || &relation == best_right.get()) { - join_relations.erase(join_relations.begin() + NumericCast(i - 1)); - } - } - idx_t kept_candidates = 0; - for (idx_t candidate_idx = 0; candidate_idx < candidates.size(); candidate_idx++) { - auto &candidate = candidates[candidate_idx]; - if (candidate.left == best_left || candidate.left == best_right || candidate.right == best_left || - candidate.right == best_right) { - continue; - } - candidates[kept_candidates++] = candidate; - } - candidates.resize(kept_candidates); - for (auto &relation : join_relations) { - EmitCandidate(relation, new_set); - } - join_relations.push_back(new_set); - } - return true; + candidate_evaluator.InitInputPlan(plans); + GreedyJoinEnumerator greedy(query_graph_manager, candidate_evaluator); + return greedy.Solve(plans); } -bool PlanEnumerator::HasCompletePlan() const { +bool PlanEnumerator::HasCompletePlan(const JoinOrderPlanMap &memo) const { unordered_set bindings; for (idx_t relation_idx = 0; relation_idx < query_graph_manager.relation_manager.NumRelations(); relation_idx++) { bindings.emplace(relation_idx); } auto &total_relation = query_graph_manager.set_manager.GetJoinRelation(bindings); - return plans.find(total_relation) != plans.end(); + return memo.find(total_relation) != memo.end(); } -bool PlanEnumerator::ActivateRequiredCrossProducts() { - if (!query_graph_manager.ActivateRequiredCrossProducts()) { - return false; - } - pairs = 0; - connection_cache.clear(); - neighbor_set_cache.clear(); - return true; -} - -bool PlanEnumerator::PlanUsesCrossProduct(const DPJoinNode &node) const { +bool PlanEnumerator::PlanUsesCrossProduct(const JoinOrderPlanMap &memo, const DPJoinNode &node) const { if (node.is_leaf) { return false; } @@ -597,37 +42,12 @@ bool PlanEnumerator::PlanUsesCrossProduct(const DPJoinNode &node) const { (node.join_operator && node.join_operator->type == JoinOrderOperatorType::CROSS_PRODUCT)) { return true; } - auto left = plans.find(node.left_set); - auto right = plans.find(node.right_set); - D_ASSERT(left != plans.end() && right != plans.end()); - return PlanUsesCrossProduct(*left->second) || PlanUsesCrossProduct(*right->second); + auto left = memo.find(node.left_set); + auto right = memo.find(node.right_set); + D_ASSERT(left != memo.end() && right != memo.end()); + return PlanUsesCrossProduct(memo, *left->second) || PlanUsesCrossProduct(memo, *right->second); } -void PlanEnumerator::InitLeafPlans() { - auto relation_stats = query_graph_manager.relation_manager.GetRelationStats(); - auto &estimator = cost_model.GetCardinalityEstimator(); - estimator.Initialize(relation_stats, query_graph_manager.GetJoinOperators(), - query_graph_manager.relation_manager.GetColumnSources()); - for (idx_t i = 0; i < relation_stats.size(); i++) { - auto &relation_set = query_graph_manager.set_manager.GetJoinRelation(RelationIndex(i)); - auto join_node = make_uniq(relation_set); - join_node->cost = 0; - join_node->cardinality = estimator.EstimateCardinality(relation_set); - if (query_graph_manager.relation_manager.HasRecursiveRelations()) { - auto &relation = query_graph_manager.relation_manager.GetRelation(RelationIndex(i)); - relation.op.ResolveOperatorTypes(); - join_node->recursive_properties = relation.recursive_properties; - if (join_node->recursive_properties.depends_on_recursive_input) { - recursive_frontier_estimate = MaxValue(recursive_frontier_estimate, join_node->cardinality.GetDouble()); - } - } - plans[relation_set] = std::move(join_node); - } -} - -// the plan enumeration is a straight implementation of the paper "Dynamic Programming Strikes Back" by Guido -// Moerkotte and Thomas Neumannn, see that paper for additional info/documentation bonus slides: -// https://db.in.tum.de/teaching/ws1415/queryopt/chapter3.pdf?lang=de bool PlanEnumerator::SolveJoinOrder() { bool force_no_cross_product = Settings::Get(query_graph_manager.context); auto swap_to_approximate_threshold = @@ -638,11 +58,18 @@ bool PlanEnumerator::SolveJoinOrder() { if (query_graph_manager.relation_manager.NumRelations() >= swap_to_approximate_threshold) { solved = SolveJoinOrderApproximately(); } else { - auto completed_exactly = SolveJoinOrderExactly(); - if (completed_exactly && !HasCompletePlan() && ActivateRequiredCrossProducts()) { - completed_exactly = SolveJoinOrderExactly(); - } - if (!completed_exactly || !HasCompletePlan()) { + bool completed_exactly; + { + DPHypEnumerator exact(query_graph_manager, query_graph, candidate_evaluator, std::move(plans)); + completed_exactly = exact.Solve(); + if (completed_exactly && !HasCompletePlan(exact.GetPlans()) && + candidate_evaluator.ActivateRequiredCrossProducts()) { + exact.ResetAfterGraphChange(); + completed_exactly = exact.Solve(); + } + plans = exact.TakePlans(); + } + if (!completed_exactly || !HasCompletePlan(plans)) { // Exact enumeration either reached its pair budget or could not connect the graph. solved = SolveJoinOrderApproximately(); } else { @@ -672,7 +99,7 @@ bool PlanEnumerator::SolveJoinOrder() { } return false; } - if (force_no_cross_product && PlanUsesCrossProduct(*final_plan->second)) { + if (force_no_cross_product && PlanUsesCrossProduct(plans, *final_plan->second)) { throw InvalidInputException("Query requires a cross-product, but 'force_no_cross_product' PRAGMA is enabled"); } return true; diff --git a/src/duckdb/src/optimizer/join_order/relation_manager.cpp b/src/duckdb/src/optimizer/join_order/relation_manager.cpp index 7ffd48bdb..15b318b20 100644 --- a/src/duckdb/src/optimizer/join_order/relation_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/relation_manager.cpp @@ -520,12 +520,26 @@ static optional CombineNonReorderableStats(LogicalOperator &op, c return result; } +static void OptimizeChild(JoinOrderOptimizer &optimizer, LogicalOperator &op, idx_t child_index, + optional_ptr stats) { + auto projection_map = LogicalOperatorVisitor::GetProjectionMap(op, child_index); + vector old_bindings; + if (projection_map) { + old_bindings = op.children[child_index]->GetColumnBindings(); + } + op.children[child_index] = optimizer.Optimize(std::move(op.children[child_index]), stats); + if (projection_map) { + auto new_bindings = op.children[child_index]->GetColumnBindings(); + LogicalOperatorVisitor::RemapProjectionMap(*projection_map, old_bindings, new_bindings); + } +} + bool RelationManager::AddRelationWithChildren(JoinOrderOptimizer &optimizer, LogicalOperator &op, LogicalOperator &input_op, optional_ptr parent, RelationStats &child_stats) { D_ASSERT(!op.children.empty()); auto child_optimizer = optimizer.CreateChildOptimizer(); - op.children[0] = child_optimizer.Optimize(std::move(op.children[0]), &child_stats); + OptimizeChild(child_optimizer, op, 0, &child_stats); vector> children_stats {child_stats}; auto operator_stats = RelationStatisticsHelper::ExtractOperatorStats(op, context, children_stats); if (!operator_stats) { @@ -559,7 +573,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending auto &join = *relation.parent; RelationStats child_stats; auto child_optimizer = optimizer.CreateChildOptimizer(); - join.children[1] = child_optimizer.Optimize(std::move(join.children[1]), &child_stats); + OptimizeChild(child_optimizer, join, 1, &child_stats); if (!AddRelation(*join.children[1], join, child_stats)) { return false; } @@ -606,10 +620,10 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending // for this reason, we just start a new JoinOptimizer pass in each of the children of the join // stats.cardinality will be initiated to highest cardinality of the children. vector children_stats; - for (auto &child : op->children) { + for (idx_t child_index = 0; child_index < op->children.size(); child_index++) { auto stats = RelationStats(); auto child_optimizer = optimizer.CreateChildOptimizer(); - child = child_optimizer.Optimize(std::move(child), &stats); + OptimizeChild(child_optimizer, *op, child_index, &stats); children_stats.push_back(stats); } @@ -627,7 +641,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending // optimize children RelationStats child_stats; auto child_optimizer = optimizer.CreateChildOptimizer(); - op->children[0] = child_optimizer.Optimize(std::move(op->children[0]), &child_stats); + 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); @@ -643,7 +657,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending // optimize children RelationStats child_stats; auto child_optimizer = optimizer.CreateChildOptimizer(); - op->children[0] = child_optimizer.Optimize(std::move(op->children[0]), &child_stats); + OptimizeChild(child_optimizer, *op, 0, &child_stats); auto &window = op->Cast(); auto operator_stats = RelationStatisticsHelper::ExtractWindowStats(window, child_stats); if (!operator_stats) { @@ -659,7 +673,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending // the boundary - its own estimate, and the domains of its columns only if it may propagate statistics RelationStats child_stats; auto child_optimizer = optimizer.CreateChildOptimizer(); - op->children[0] = child_optimizer.Optimize(std::move(op->children[0]), &child_stats); + OptimizeChild(child_optimizer, *op, 0, &child_stats); auto &secure_view = op->Cast(); RelationStats stats; stats.cardinality = secure_view.EstimateCardinality(context); @@ -741,7 +755,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending RelationStats child_stats; // optimize the child and copy the stats auto child_optimizer = optimizer.CreateChildOptimizer(); - op->children[0] = child_optimizer.Optimize(std::move(op->children[0]), &child_stats); + OptimizeChild(child_optimizer, *op, 0, &child_stats); auto &proj = op->Cast(); // Projection can create columns so we need to add them here auto proj_stats = RelationStatisticsHelper::ExtractProjectionStats(proj, child_stats); @@ -772,7 +786,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending RelationStats lhs_stats; // optimize the lhs child and copy the stats auto lhs_optimizer = optimizer.CreateChildOptimizer(); - op->children[0] = lhs_optimizer.Optimize(std::move(op->children[0]), &lhs_stats); + OptimizeChild(lhs_optimizer, *op, 0, &lhs_stats); // optimize the rhs child auto rhs_optimizer = optimizer.CreateChildOptimizer(); auto table_index = op->Cast().table_index; @@ -783,7 +797,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending rhs_optimizer.recursive_cte_indexes.insert(op->Cast().table_index); } RelationStats rhs_stats; - op->children[1] = rhs_optimizer.Optimize(std::move(op->children[1]), &rhs_stats); + OptimizeChild(rhs_optimizer, *op, 1, &rhs_stats); // create the stats for the CTE auto child_2_card = rhs_stats.stats_initialized ? rhs_stats.cardinality : 0; @@ -851,7 +865,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending // optimize LHS (duplicate-eliminated) child RelationStats lhs_stats; auto lhs_optimizer = optimizer.CreateChildOptimizer(); - op->children[0] = lhs_optimizer.Optimize(std::move(op->children[0]), &lhs_stats); + OptimizeChild(lhs_optimizer, *op, 0, &lhs_stats); // create dummy aggregation for the duplicate elimination auto dummy_aggr = make_uniq(TableIndex(DConstants::INVALID_INDEX - 1), TableIndex(), @@ -873,7 +887,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending RelationStats rhs_stats; auto rhs_optimizer = optimizer.CreateChildOptimizer(); rhs_optimizer.AddDelimScanStats(*lhs_delim_stats); - op->children[1] = rhs_optimizer.Optimize(std::move(op->children[1]), rhs_stats); + OptimizeChild(rhs_optimizer, *op, 1, &rhs_stats); RelationStats dj_stats; switch (delim_join.join_type) { diff --git a/src/duckdb/src/optimizer/mark_join_simplifier.cpp b/src/duckdb/src/optimizer/mark_join_simplifier.cpp index 32550da1a..5efb67118 100644 --- a/src/duckdb/src/optimizer/mark_join_simplifier.cpp +++ b/src/duckdb/src/optimizer/mark_join_simplifier.cpp @@ -4,15 +4,19 @@ #include "duckdb/optimizer/column_binding_replacer.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/planner/binder.hpp" +#include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression/bound_columnref_expression.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_operator_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/expression_nullability.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_set_operation.hpp" #include "duckdb/planner/subquery/has_volatile_expressions.hpp" namespace duckdb { @@ -145,6 +149,48 @@ static void SimplifyNullSafeSemiJoinConditions(NotNullExpressionAnalyzer &analyz } } +static void ApplyMarkJoinConversion(Optimizer &optimizer, unique_ptr &op, idx_t predicate_index, + const column_binding_map_t &marker_values, + NotNullExpressionAnalyzer &nullability, BindingReplacementGraph &replacements, + const std::function &)> &rewrite_join) { + auto &filter = op->Cast(); + auto &original = *filter.children[0]; + original.ResolveOperatorTypes(); + const auto old_bindings = original.GetColumnBindings(); + vector> expressions; + for (idx_t i = 0; i < old_bindings.size(); i++) { + auto marker = marker_values.find(old_bindings[i]); + if (marker != marker_values.end()) { + expressions.push_back(make_uniq(marker->second)); + } else { + expressions.push_back(make_uniq(original.types[i], old_bindings[i])); + } + } + auto projection = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(expressions)); + BindingReplacementGraph local_replacements; + auto new_bindings = projection->GetColumnBindings(); + for (idx_t i = 0; i < old_bindings.size(); i++) { + if (!local_replacements.Find(old_bindings[i])) { + local_replacements.Add(old_bindings[i], new_bindings[i]); + } + } + filter.expressions.erase_at(predicate_index); + ColumnBindingRewrite::RewriteChild( + op, 0, [&](unique_ptr &child, BindingReplacementGraph &child_replacements) { + rewrite_join(child); + auto &join = child->Cast(); + D_ASSERT(join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI); + projection->children.push_back(std::move(child)); + child = std::move(projection); + child_replacements.Merge(local_replacements); + // CTE nullability analysis needs the replacement attached to the complete plan. + if (join.join_type == JoinType::SEMI) { + SimplifyNullSafeSemiJoinConditions(nullability, join); + } + }); + replacements.Merge(local_replacements); +} + bool MarkJoinSimplifier::TrySimplify(unique_ptr &op, NotNullExpressionAnalyzer &nullability, BindingReplacementGraph &replacements) { auto &filter = op->Cast(); @@ -185,51 +231,225 @@ bool MarkJoinSimplifier::TrySimplify(unique_ptr &op, NotNullExp return false; } } - join.ResolveOperatorTypes(); - const auto old_bindings = join.GetColumnBindings(); - vector> expressions; - for (idx_t col_idx = 0; col_idx < old_bindings.size(); col_idx++) { - if (old_bindings[col_idx] == marker) { - expressions.push_back( - make_uniq(Value::BOOLEAN(target_type == JoinType::SEMI))); - } else { - expressions.push_back(make_uniq(join.types[col_idx], old_bindings[col_idx])); + ApplyMarkJoinConversion(optimizer, op, i, {{marker, Value::BOOLEAN(target_type == JoinType::SEMI)}}, + nullability, replacements, [&](unique_ptr &child) { + auto &converted_join = child->Cast(); + converted_join.join_type = target_type; + converted_join.mark_types.clear(); + }); + return true; + } + return false; +} + +static bool GetDisjunctiveMarkers(const Expression &expr, column_binding_set_t &markers) { + if (expr.GetExpressionType() == ExpressionType::CONJUNCTION_OR) { + for (auto &child : expr.Cast().GetChildren()) { + if (!GetDisjunctiveMarkers(*child, markers)) { + return false; } } - filter.expressions.erase_at(i); - auto projection = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(expressions)); - BindingReplacementGraph local_replacements; - auto new_bindings = projection->GetColumnBindings(); - for (idx_t col_idx = 0; col_idx < old_bindings.size(); col_idx++) { - if (!local_replacements.Find(old_bindings[col_idx])) { - local_replacements.Add(old_bindings[col_idx], new_bindings[col_idx]); + return true; + } + if (expr.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF || expr.GetReturnType() != LogicalType::BOOLEAN) { + return false; + } + auto &column = expr.Cast(); + if (column.Depth() != 0) { + return false; + } + markers.insert(column.Binding()); + return true; +} + +static bool CanDiscardMarkers(const Expression &expr, const column_binding_set_t &markers) { + switch (expr.GetExpressionClass()) { + case ExpressionClass::BOUND_COLUMN_REF: { + auto &column = expr.Cast(); + return column.Depth() == 0 && !markers.count(column.Binding()); + } + case ExpressionClass::BOUND_REF: + case ExpressionClass::BOUND_SUBQUERY: + return false; + default: + break; + } + bool result = true; + ExpressionIterator::EnumerateChildren( + expr, [&](const Expression &child) { result = result && CanDiscardMarkers(child, markers); }); + return result; +} + +static bool CanDiscardMarkers(const LogicalOperator &op, const column_binding_set_t &markers) { + bool result = true; + LogicalOperatorVisitor::EnumerateExpressions( + op, [&](const unique_ptr *expr) { result = result && CanDiscardMarkers(**expr, markers); }); + return result; +} + +static bool MarkersAreUnused(const LogicalFilter &filter, idx_t predicate_index, + const vector> &ancestors, const column_binding_set_t &markers) { + for (idx_t i = 0; i < filter.expressions.size(); i++) { + if (i != predicate_index && !CanDiscardMarkers(*filter.expressions[i], markers)) { + return false; + } + } + for (idx_t i = ancestors.size(); i > 0; i--) { + auto &ancestor = ancestors[i - 1].get(); + if (!CanDiscardMarkers(ancestor, markers)) { + return false; + } + switch (ancestor.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + // Any use above this binding boundary must first read a marker in its expressions. + return true; + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_ORDER_BY: + case LogicalOperatorType::LOGICAL_TOP_N: + case LogicalOperatorType::LOGICAL_LIMIT: + case LogicalOperatorType::LOGICAL_WINDOW: + break; + default: + // Do not infer liveness across positional consumers or dependent sibling subtrees. + return false; + } + if (ancestor.children.size() != 1) { + return false; + } + } + return false; +} + +static bool BuildIsIndependent(const LogicalOperator &op, const column_binding_set_t &markers) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_DELIM_GET: + case LogicalOperatorType::LOGICAL_DELIM_JOIN: + case LogicalOperatorType::LOGICAL_DEPENDENT_JOIN: + case LogicalOperatorType::LOGICAL_EXTENSION_OPERATOR: + return false; + default: + break; + } + if (!CanDiscardMarkers(op, markers)) { + return false; + } + for (auto &child : op.children) { + if (!BuildIsIndependent(*child, markers)) { + return false; + } + } + return true; +} + +static bool SameMarkJoinKeys(const LogicalComparisonJoin &join, const LogicalComparisonJoin &other) { + if (join.conditions.empty() || join.conditions.size() != other.conditions.size()) { + return false; + } + for (idx_t i = 0; i < join.conditions.size(); i++) { + auto &condition = join.conditions[i]; + auto &other_condition = other.conditions[i]; + if (!condition.IsComparison() || !other_condition.IsComparison()) { + return false; + } + auto comparison = condition.GetComparisonType(); + if ((comparison != ExpressionType::COMPARE_EQUAL && comparison != ExpressionType::COMPARE_NOT_DISTINCT_FROM) || + comparison != other_condition.GetComparisonType() || !condition.GetLHS().Equals(other_condition.GetLHS()) || + !condition.GetLHS().GetReturnType().EqualsIncludingCollation(other_condition.GetLHS().GetReturnType()) || + !condition.GetRHS().GetReturnType().EqualsIncludingCollation(other_condition.GetRHS().GetReturnType()) || + condition.GetLHS().CanThrow() || condition.GetRHS().CanThrow()) { + return false; + } + } + return true; +} + +bool MarkJoinSimplifier::TrySimplifyDisjunction(unique_ptr &op, NotNullExpressionAnalyzer &nullability, + const vector> &ancestors, + BindingReplacementGraph &replacements) { + auto &filter = op->Cast(); + for (idx_t predicate_index = 0; predicate_index < filter.expressions.size(); predicate_index++) { + auto &predicate = *filter.expressions[predicate_index]; + if (predicate.GetExpressionType() != ExpressionType::CONJUNCTION_OR) { + continue; + } + column_binding_set_t markers; + if (!GetDisjunctiveMarkers(predicate, markers) || markers.size() < 2 || + !MarkersAreUnused(filter, predicate_index, ancestors, markers)) { + continue; + } + vector> joins; + auto remaining = markers; + optional_ptr probe = filter.children[0].get(); + while (probe->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &join = probe->Cast(); + if (join.join_type != JoinType::MARK || !join.duplicate_eliminated_columns.empty() || + !remaining.erase(ColumnBinding(join.mark_index, ProjectionIndex(0))) || + !SameMarkJoinKeys(join, joins.empty() ? join : joins[0].get()) || !CanDiscardMarkers(join, markers) || + !BuildIsIndependent(*join.children[1], markers)) { + break; } + joins.push_back(join); + probe = join.children[0].get(); + if (remaining.empty()) { + break; + } + } + if (joins.size() != markers.size() || HasVolatileExpressionsIgnoringError(filter)) { + continue; } - ColumnBindingRewrite::RewriteChild( - op, 0, [&](unique_ptr &child, BindingReplacementGraph &child_replacements) { - join.join_type = target_type; - join.mark_types.clear(); - if (target_type == JoinType::SEMI) { - SimplifyNullSafeSemiJoinConditions(nullability, join); + column_binding_map_t marker_values; + for (auto &marker : markers) { + // The individual marks are dead, but retain their slots until ordinary column pruning. + marker_values.emplace(marker, Value(LogicalType::BOOLEAN)); + } + ApplyMarkJoinConversion( + optimizer, op, predicate_index, marker_values, nullability, replacements, + [&](unique_ptr &child) { + auto &top = joins[0].get(); + const auto union_index = optimizer.binder.GenerateTableIndex(); + auto semi = make_uniq(JoinType::SEMI); + for (idx_t i = 0; i < top.conditions.size(); i++) { + auto &condition = top.conditions[i]; + auto key = make_uniq(condition.GetRHS().GetReturnType(), + ColumnBinding(union_index, ProjectionIndex(i))); + semi->conditions.emplace_back(condition.GetLHS().Copy(), std::move(key), + condition.GetComparisonType()); + } + vector> builds; + for (auto &join_ref : joins) { + auto &join = join_ref.get(); + vector> keys; + for (auto &condition : join.conditions) { + keys.push_back(condition.GetRHS().Copy()); + } + auto build = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(keys)); + build->children.push_back(std::move(join.children[1])); + builds.push_back(std::move(build)); } - projection->children.push_back(std::move(child)); - child = std::move(projection); - child_replacements.Merge(local_replacements); + auto union_op = make_uniq(union_index, semi->conditions.size(), std::move(builds), + LogicalOperatorType::LOGICAL_UNION, true); + semi->children.push_back(std::move(joins.back().get().children[0])); + semi->children.push_back(std::move(union_op)); + child = std::move(semi); }); - replacements.Merge(local_replacements); return true; } return false; } void MarkJoinSimplifier::Rewrite(unique_ptr &op, NotNullExpressionAnalyzer &nullability, - BindingReplacementGraph &replacements) { + BindingReplacementGraph &replacements, vector> &ancestors) { + ancestors.push_back(*op); for (auto &child : op->children) { - Rewrite(child, nullability, replacements); + Rewrite(child, nullability, replacements, ancestors); } + ancestors.pop_back(); // Visit original consumers before adding their enclosing conversion's replacement edges. ColumnBindingRewrite::ApplyToOperatorBindings(*op, replacements); - if (op->type == LogicalOperatorType::LOGICAL_FILTER && TrySimplify(op, nullability, replacements)) { + if (op->type == LogicalOperatorType::LOGICAL_FILTER && + (TrySimplify(op, nullability, replacements) || + TrySimplifyDisjunction(op, nullability, ancestors, replacements))) { auto &filter = op->Cast(); if (filter.expressions.empty() && !filter.HasProjectionMap()) { op = std::move(filter.children[0]); @@ -240,7 +460,8 @@ void MarkJoinSimplifier::Rewrite(unique_ptr &op, NotNullExpress void MarkJoinSimplifier::Optimize(unique_ptr &plan) { NotNullExpressionAnalyzer nullability(optimizer.context, *plan); BindingReplacementGraph replacements; - Rewrite(plan, nullability, replacements); + vector> ancestors; + Rewrite(plan, nullability, replacements, ancestors); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/remove_unused_columns.cpp b/src/duckdb/src/optimizer/remove_unused_columns.cpp index 02059896f..dfb2a7dd7 100644 --- a/src/duckdb/src/optimizer/remove_unused_columns.cpp +++ b/src/duckdb/src/optimizer/remove_unused_columns.cpp @@ -516,6 +516,7 @@ static bool IsDuplicateCondition(const vector &conditions, const void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { const bool analyze = mode == RemoveUnusedColumnsMode::ANALYZE; auto &op = *op_ref; + vector> join_key_replacements; switch (op.type) { case LogicalOperatorType::LOGICAL_WINDOW: { auto &window = op.Cast(); @@ -618,7 +619,8 @@ void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { // we can replace any references to the RHS (Y) to references to the LHS (X) // this reduces the amount of columns we need to extract from the join hash table // (except in the case of floating point numbers which have +0 and -0, equal but different). - for (auto &cond : comp_join.conditions) { + for (idx_t condition_idx = 0; condition_idx < comp_join.conditions.size(); condition_idx++) { + auto &cond = comp_join.conditions[condition_idx]; if (!cond.IsComparison() || cond.GetComparisonType() != ExpressionType::COMPARE_EQUAL) { continue; } @@ -649,6 +651,15 @@ void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { colref_slot = colref_slot->Cast().WithBinding(lhs_binding); AddBinding(colref_slot); } + join_key_replacements.emplace_back(rhs_col.Binding(), condition_idx); + if (!comp_join.left_projection_map.empty()) { + auto index = + ColumnBindingLayout(comp_join.children[0]->GetColumnBindings()).GetProjectionIndex(lhs_binding); + auto &projection_map = comp_join.left_projection_map; + if (std::find(projection_map.begin(), projection_map.end(), index) == projection_map.end()) { + projection_map.push_back(index); + } + } column_references.erase(rhs_col.Binding()); } break; @@ -1010,6 +1021,13 @@ void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { LogicalOperatorVisitor::VisitOperatorExpressions(op); VisitPrunableChildren(op); + // Join conditions track child rewrites, including further key substitution and column renumbering. + for (auto &replacement : join_key_replacements) { + auto &join = op.Cast(); + auto &lhs = join.conditions[replacement.second].GetLHS().Cast(); + root.projection_map_replacements[replacement.first] = {lhs.Binding()}; + } + if (!analyze && (op.type == LogicalOperatorType::LOGICAL_ASOF_JOIN || op.type == LogicalOperatorType::LOGICAL_DELIM_JOIN || op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN)) { diff --git a/src/duckdb/src/optimizer/rule/predicate_factoring.cpp b/src/duckdb/src/optimizer/rule/predicate_factoring.cpp index 526425849..5be219610 100644 --- a/src/duckdb/src/optimizer/rule/predicate_factoring.cpp +++ b/src/duckdb/src/optimizer/rule/predicate_factoring.cpp @@ -36,7 +36,7 @@ static bool ColumnBindingIsvalid(const ColumnBinding &column_binding) { } static bool GetSingleColumnBinding(const Expression &expr, ColumnBinding &column_binding) { - if (expr.IsVolatile()) { + if (expr.IsVolatile() || expr.CanThrow()) { return false; } @@ -83,47 +83,61 @@ static void ExtractDisjunctedPredicates(Expression &expression, } } -static column_binding_map_t>> GetDisjunctedPredicateMap(Expression &expression) { +//! The predicates one disjunct has on a column all hold together +static unique_ptr CombineConjuncts(const vector> &predicates) { + D_ASSERT(!predicates.empty()); + vector> children; + for (auto &predicate : predicates) { + auto copy = predicate.get().Copy(); + bool found = false; + for (auto &child : children) { + found = found || child->Equals(*copy); + } + if (!found) { + children.push_back(std::move(copy)); + } + } + return BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_AND, std::move(children)); +} + +//! For every column that each disjunct restricts, the distinct restrictions the disjuncts place on it +static column_binding_map_t>> GetDisjunctedPredicateMap(Expression &expression) { vector> disjuncted_children; ExtractDisjunctedPredicates(expression, disjuncted_children); D_ASSERT(disjuncted_children.size() > 1); - // Extract predicates of the first child - auto &first_child = disjuncted_children[0].get(); - D_ASSERT(!ExpressionIsDisjunction(first_child)); - column_binding_map_t>> remaining_binding_map; - ExtractDisjunctedPredicates(first_child, remaining_binding_map); - - for (idx_t child_idx = 1; child_idx < disjuncted_children.size(); child_idx++) { + column_binding_map_t>> result; + for (idx_t child_idx = 0; child_idx < disjuncted_children.size(); child_idx++) { auto &child = disjuncted_children[child_idx].get(); D_ASSERT(!ExpressionIsDisjunction(child)); column_binding_map_t>> child_binding_map; ExtractDisjunctedPredicates(child, child_binding_map); - // Bindings must appear in both maps to be considered for predicate factoring - for (auto it = remaining_binding_map.begin(); it != remaining_binding_map.end();) { + if (child_idx == 0) { + for (auto &entry : child_binding_map) { + result[entry.first].push_back(CombineConjuncts(entry.second)); + } + continue; + } + // Bindings must appear in every disjunct to be considered for predicate factoring + for (auto it = result.begin(); it != result.end();) { auto child_it = child_binding_map.find(it->first); if (child_it == child_binding_map.end()) { - it = remaining_binding_map.erase(it); - } else { - for (auto &new_predicate : child_it->second) { - bool found = false; - for (auto &existing_predicate : it->second) { - if (new_predicate.get().Equals(existing_predicate.get())) { - found = true; - break; - } - } - if (!found) { - it->second.push_back(new_predicate.get()); - } - } - it++; + it = result.erase(it); + continue; + } + auto restriction = CombineConjuncts(child_it->second); + bool found = false; + for (auto &existing : it->second) { + found = found || restriction->Equals(*existing); + } + if (!found) { + it->second.push_back(std::move(restriction)); } + it++; } } - - return remaining_binding_map; + return result; } unique_ptr PredicateFactoringRule::Apply(LogicalOperator &op, vector> &bindings, @@ -145,7 +159,7 @@ unique_ptr PredicateFactoringRule::Apply(LogicalOperator &op, vector } // Extract map from single column binding to expression it is contained in - const auto binding_map = GetDisjunctedPredicateMap(bindings[0].get()); + auto binding_map = GetDisjunctedPredicateMap(bindings[0].get()); if (binding_map.empty()) { return nullptr; // None qualify } @@ -155,16 +169,8 @@ unique_ptr PredicateFactoringRule::Apply(LogicalOperator &op, vector D_ASSERT(!entry.second.empty()); // Create disjunction on single-column predicates - unique_ptr column_filter; - for (auto &expr : entry.second) { - if (!column_filter) { - column_filter = expr.get().Copy(); - } else { - auto new_disjunction = make_uniq( - ExpressionType::CONJUNCTION_OR, std::move(column_filter), expr.get().Copy()); - column_filter = std::move(new_disjunction); - } - } + auto column_filter = + BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_OR, std::move(entry.second)); // Conjunct each single-column predicate together if (!derived_filter) { diff --git a/src/duckdb/src/parser/parsed_data/create_info.cpp b/src/duckdb/src/parser/parsed_data/create_info.cpp index 2f55a8a6b..68582540e 100644 --- a/src/duckdb/src/parser/parsed_data/create_info.cpp +++ b/src/duckdb/src/parser/parsed_data/create_info.cpp @@ -3,21 +3,36 @@ #include "duckdb/parser/parsed_data/create_index_info.hpp" #include "duckdb/parser/parsed_data/alter_info.hpp" #include "duckdb/parser/parsed_data/create_macro_info.hpp" +#include "duckdb/parser/parsed_data/create_table_info.hpp" namespace duckdb { +//! PRIMARY KEY, UNIQUE and FOREIGN KEY constraints are backed by indexes +static bool HasIndexConstraint(const CreateTableInfo &info) { + for (auto &constraint : info.constraints) { + if (constraint->type != ConstraintType::NOT_NULL && constraint->type != ConstraintType::CHECK) { + return true; + } + } + return false; +} + DatabaseModificationType CreateInfo::GetModifications() const { switch (type) { - case CatalogType::TABLE_ENTRY: - case CatalogType::INDEX_ENTRY: - case CatalogType::TRIGGER_ENTRY: - return DatabaseModificationType::CREATE_CATALOG_ENTRY; - case CatalogType::SCHEMA_ENTRY: - // replacing a schema drops the existing one - if (on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT) { + case CatalogType::TABLE_ENTRY: { + auto &table_info = Cast(); + // FIXME: temporary, until tables with indexes run alongside checkpoints as well + if (HasIndexConstraint(table_info)) { return DatabaseModificationType::CREATE_CATALOG_ENTRY; } + // no checkpoint lock, but like INSERT ... SELECT, CREATE TABLE AS keeps checkpoints from vacuuming meanwhile + if (table_info.query) { + return DatabaseModificationType::INSERT_DATA; + } return DatabaseModificationType(); + } + case CatalogType::INDEX_ENTRY: + return DatabaseModificationType::CREATE_CATALOG_ENTRY; default: return DatabaseModificationType(); } diff --git a/src/duckdb/src/parser/parsed_data/drop_info.cpp b/src/duckdb/src/parser/parsed_data/drop_info.cpp index 656e227b3..8a96b474e 100644 --- a/src/duckdb/src/parser/parsed_data/drop_info.cpp +++ b/src/duckdb/src/parser/parsed_data/drop_info.cpp @@ -18,7 +18,7 @@ DatabaseModificationType DropInfo::GetModifications() const { if (type == CatalogType::TABLE_ENTRY || type == CatalogType::INDEX_ENTRY || cascade) { return DatabaseModificationType::DROP_CATALOG_ENTRY; } - // a schema is only dropped without CASCADE when it is empty + // the other entries have no table storage, and a schema is only dropped without CASCADE when it is empty return DatabaseModificationType(); } diff --git a/src/duckdb/src/planner/binder/statement/bind_create_table.cpp b/src/duckdb/src/planner/binder/statement/bind_create_table.cpp index acd5af50d..004350f35 100644 --- a/src/duckdb/src/planner/binder/statement/bind_create_table.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_create_table.cpp @@ -779,9 +779,25 @@ unique_ptr Binder::BindCreateTableInfo(unique_ptrtype != CatalogType::TABLE_ENTRY) { + return false; + } + auto &table = entry->Cast(); + return !table.IsDuckTable() || table.GetStorage().HasIndexes(); +} + unique_ptr Binder::BindCreateTableInfo(unique_ptr info) { auto &base = info->Cast(); auto &schema = BindCreateSchema(base); + // FIXME: temporary, until the drops that involve indexes run alongside checkpoints as well + if (base.on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT && ReplacesTableWithIndexes(context, schema, base)) { + GetStatementProperties().RegisterDBModify(schema.ParentCatalog(), context, + DatabaseModificationType::CREATE_CATALOG_ENTRY); + } return BindCreateTableInfo(std::move(info), schema); } diff --git a/src/duckdb/src/planner/binder/statement/bind_drop.cpp b/src/duckdb/src/planner/binder/statement/bind_drop.cpp index 6e578585b..b17dd1a01 100644 --- a/src/duckdb/src/planner/binder/statement/bind_drop.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_drop.cpp @@ -29,7 +29,7 @@ void Binder::BindDropTrigger(DropStatement &stmt, StatementProperties &propertie auto &table_entry = Catalog::GetEntry(context, base_table_ref.GetQualifiedName()); // the trigger lives in the same (possibly nested) schema as its base table stmt.info->SetQualifiedName(table_entry.ParentSchema().GetQualifiedName(stmt.info->GetQualifiedName().Name())); - properties.RegisterDBModify(table_entry.ParentCatalog(), context, DatabaseModificationType::DROP_CATALOG_ENTRY); + properties.RegisterDBModify(table_entry.ParentCatalog(), context, stmt.info->GetModifications()); } BoundStatement Binder::Bind(DropStatement &stmt) { diff --git a/src/duckdb/src/planner/table_filter_state.cpp b/src/duckdb/src/planner/table_filter_state.cpp index 849771b6b..e3dcfe6dc 100644 --- a/src/duckdb/src/planner/table_filter_state.cpp +++ b/src/duckdb/src/planner/table_filter_state.cpp @@ -6,6 +6,7 @@ #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/common/vector_operations/selection_helpers.hpp" #include "duckdb/common/vector/constant_vector.hpp" +#include "duckdb/common/vector/dictionary_vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" @@ -54,7 +55,7 @@ class BooleanFilterCache final : public TableFilterCache { if (count == 0 || match_count == value_count) { return; } - if (result.Capacity() < count) { + if (!result.IsSet() || result.Capacity() < count) { result.Initialize(count); } idx_t accepted = 0; @@ -69,7 +70,8 @@ class BooleanFilterCache final : public TableFilterCache { } } if (accepted != count) { - sel.Initialize(result); + // Transfer ownership so later filters cannot overwrite a retained selection. + sel = std::move(result); } count = accepted; } @@ -171,7 +173,8 @@ struct FilterCacheProperties { static FilterCacheProperties GetCacheProperties(const Expression &expression) { FilterCacheProperties result; - if (expression.CanThrow() || expression.IsVolatile()) { + // Verification statistics describe logical rows, not unused dictionary entries. + if (expression.CanThrow() || expression.IsVolatile() || expression.GetVerificationStats()) { result.safe = false; return result; } @@ -233,6 +236,34 @@ ExpressionFilterState::ExpressionFilterState(Context &context, const Expression ExpressionFilterState::~ExpressionFilterState() { } +bool ExpressionFilterState::TryFilterDictionary(SelectionVector &sel, Vector &vector, idx_t &approved_tuple_count) { + static constexpr idx_t MAX_DICTIONARY_SIZE_THRESHOLD = 20000; + if (!can_cache || vector.GetVectorType() != VectorType::DICTIONARY_VECTOR) { + return false; + } + const auto size = DictionaryVector::DictionarySize(vector); + const auto &id = DictionaryVector::DictionaryId(vector); + auto &values = DictionaryVector::Child(vector); + if (!size.IsValid() || id.empty() || size.GetIndex() >= MAX_DICTIONARY_SIZE_THRESHOLD || + values.GetVectorType() != VectorType::FLAT_VECTOR) { + return false; + } + if (approved_tuple_count == 0) { + return true; + } + if (!dictionary_cache || dictionary_id != id) { + // Avoid evaluating a large dictionary for only a few selected rows. + if (size.GetIndex() > STANDARD_VECTOR_SIZE && approved_tuple_count <= STANDARD_VECTOR_SIZE / 2) { + return false; + } + auto new_cache = CreateCache(values, size.GetIndex()); + dictionary_id = id; + dictionary_cache = std::move(new_cache); + } + dictionary_cache->Filter(DictionaryVector::SelVector(vector), sel, approved_tuple_count); + return true; +} + class ConjunctionAndFilterExecutor final : public ExpressionFilterExecutor { public: explicit ConjunctionAndFilterExecutor(vector> children_p) diff --git a/src/duckdb/src/storage/compression/rle.cpp b/src/duckdb/src/storage/compression/rle.cpp index 43a8fc963..c3354cf93 100644 --- a/src/duckdb/src/storage/compression/rle.cpp +++ b/src/duckdb/src/storage/compression/rle.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/types/null_value.hpp" +#include "duckdb/common/vector/dictionary_vector.hpp" #include "duckdb/function/compression/compression.hpp" #include "duckdb/function/compression_function.hpp" #include "duckdb/storage/buffer_manager.hpp" @@ -374,7 +375,8 @@ struct RLEScanState : public SegmentScanState { explicit RLEScanState(BufferHandle handle_p, ColumnSegment &segment) : handle(std::move(handle_p)), segment_count(segment.count.load()), - layout(ReadSegmentLayout(handle, segment, segment_count)), entry_pos(0), position_in_entry(0) { + can_have_null(segment.GetStats().CanHaveNull()), layout(ReadSegmentLayout(handle, segment, segment_count)), + entry_pos(0), position_in_entry(0) { } //! Advances past empty entries within the validated range. @@ -450,9 +452,75 @@ struct RLEScanState : public SegmentScanState { return selected_rows; } + void CopyRunValues(Vector &result, idx_t run_count) { + const auto values = layout.GetRunValues(run_count); + memcpy(FlatVector::GetDataMutable(result), values.data(), run_count * sizeof(T)); + switch (result.GetType().id()) { + case LogicalTypeId::BOOLEAN: + case LogicalTypeId::DECIMAL: + case LogicalTypeId::TIME: + case LogicalTypeId::TIME_NS: + case LogicalTypeId::TIME_TZ: + break; + default: + return; + } + // NULL-only and unused legacy runs can contain a placeholder outside these logical domains. + // Other types can store the same physical value as a valid value, so preserve it there. + auto &validity = FlatVector::ValidityMutable(result); + for (idx_t i = 0; i < run_count; i++) { + if (values[i] == NullValue()) { + validity.SetInvalid(i); + } + } + } + + bool ShouldUseDictionary(idx_t scan_count, idx_t sel_count) const { + // Sparse selection can remove the repetition that makes a dictionary useful. + return double(sel_count) * double(segment_count) > + 2.0 * double(scan_count) * (double(layout.GetEntryCapacity()) + 1.0); + } + + bool EnsureDictionary(const LogicalType &type) { + static constexpr idx_t MAX_DICTIONARY_SIZE_THRESHOLD = DEFAULT_STANDARD_VECTOR_SIZE; + if (dictionary) { + return true; + } + // Keep emitted dictionaries within a default-sized vector and avoid poorly compressed segments. + const auto capacity = layout.GetEntryCapacity(); + if (capacity + 1 >= MAX_DICTIONARY_SIZE_THRESHOLD || (capacity + 1) * 2 >= segment_count) { + return false; + } + const auto run_count = layout.ValidateAllRuns(); + const auto dictionary_count = run_count + (can_have_null ? 1 : 0); + dictionary = DictionaryVector::CreateReusableDictionary(type, dictionary_count); + CopyRunValues(dictionary->data, run_count); + if (can_have_null) { + FlatVector::ValidityMutable(dictionary->data).SetInvalid(run_count); + } + return true; + } + + SelectionVector &GetDictionarySelection(idx_t count) { + if (dictionary_sel.Capacity() < count || dictionary_sel.sel_data().use_count() > 1) { + dictionary_sel.Initialize(count); + } + return dictionary_sel; + } + + void EmitDictionary(Vector &result, idx_t count) { + result.Dictionary(dictionary, dictionary_sel, count); + if (can_have_null) { + // Let validity map NULL rows in place when the result has no other readers. + // Non-null segments can retain the selection for reuse by the next scan. + dictionary_sel = SelectionVector(); + } + } + BufferHandle handle; //! Segment row count loaded from the file and used to validate runs as they are reached. const idx_t segment_count; + const bool can_have_null; SegmentLayout layout; idx_t entry_pos; idx_t position_in_entry; @@ -460,6 +528,8 @@ struct RLEScanState : public SegmentScanState { unique_ptr filter_cache; SelectionVector run_indices; SelectionVector selected_rows; + SelectionVector dictionary_sel; + buffer_ptr dictionary; vector run_offsets; vector run_row_counts; }; @@ -513,24 +583,30 @@ static void RLEScanConstant(RLEScanState &scan_state, const typename RLEScanS } } -template -void RLEScanPartialInternal(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, - idx_t result_offset) { - auto &scan_state = state.scan_state->Cast>(); - D_ASSERT(state.GetPositionInSegment() <= scan_state.segment_count); - D_ASSERT(scan_count <= scan_state.segment_count - state.GetPositionInSegment()); - scan_state.layout.ValidateUntil(scan_state.segment_count - state.GetPositionInSegment() - scan_count); - - // If we are scanning an entire Vector and it contains only a single run - auto current_run = scan_state.GetCurrentRun(); - if (scan_state.position_in_entry < current_run.length && - CanEmitConstantVector(scan_state.position_in_entry, current_run.length, scan_count)) { - RLEScanConstant(scan_state, current_run, scan_count, result); +template +static void RLEFillRun(T *data, idx_t count, T value) { + if (count < 4) { + for (idx_t i = 0; i < count; i++) { + data[i] = value; + } return; } + for (idx_t i = 0; i + 4 < count; i += 4) { + data[i] = value; + data[i + 1] = value; + data[i + 2] = value; + data[i + 3] = value; + } + // Overlap the last block to avoid a scalar tail. + data[count - 4] = value; + data[count - 3] = value; + data[count - 2] = value; + data[count - 1] = value; +} - auto result_data = FlatVector::GetDataMutable(result); - +template +static void RLEScanValues(RLEScanState &scan_state, OUTPUT_TYPE *result_data, idx_t scan_count, idx_t result_offset, + VALUE_OP make_value) { const idx_t result_end = result_offset + scan_count; auto entry_pos = scan_state.entry_pos; auto position_in_entry = scan_state.position_in_entry; @@ -539,18 +615,14 @@ void RLEScanPartialInternal(ColumnSegment &segment, ColumnScanState &state, idx_ auto run = scan_state.layout.GetValidatedRun(entry_pos); auto run_count = run.length - position_in_entry; idx_t remaining_scan_count = result_end - result_offset; - T element = run.value; + const auto element = make_value(run.value, entry_pos); if (DUCKDB_UNLIKELY(run_count > remaining_scan_count)) { - for (idx_t i = 0; i < remaining_scan_count; i++) { - result_data[result_offset + i] = element; - } + RLEFillRun(result_data + result_offset, remaining_scan_count, element); position_in_entry += remaining_scan_count; break; } - for (idx_t i = 0; i < run_count; i++) { - result_data[result_offset + i] = element; - } + RLEFillRun(result_data + result_offset, run_count, element); result_offset += run_count; entry_pos++; @@ -560,6 +632,40 @@ void RLEScanPartialInternal(ColumnSegment &segment, ColumnScanState &state, idx_ scan_state.position_in_entry = position_in_entry; } +template +static bool TryRLEScanDictionary(RLEScanState &scan_state, idx_t scan_count, Vector &result) { + if (!scan_state.EnsureDictionary(result.GetType())) { + return false; + } + auto &sel = scan_state.GetDictionarySelection(scan_count); + RLEScanValues(scan_state, sel.data(), scan_count, 0, [](T, idx_t run) { return UnsafeNumericCast(run); }); + scan_state.EmitDictionary(result, scan_count); + return true; +} + +template +void RLEScanPartialInternal(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, + idx_t result_offset) { + auto &scan_state = state.scan_state->Cast>(); + D_ASSERT(state.GetPositionInSegment() <= scan_state.segment_count); + D_ASSERT(scan_count <= scan_state.segment_count - state.GetPositionInSegment()); + scan_state.layout.ValidateUntil(scan_state.segment_count - state.GetPositionInSegment() - scan_count); + + // If we are scanning an entire Vector and it contains only a single run + auto current_run = scan_state.GetCurrentRun(); + if (scan_state.position_in_entry < current_run.length && + CanEmitConstantVector(scan_state.position_in_entry, current_run.length, scan_count)) { + RLEScanConstant(scan_state, current_run, scan_count, result); + return; + } + if (ENTIRE_VECTOR && TryRLEScanDictionary(scan_state, scan_count, result)) { + return; + } + + RLEScanValues(scan_state, FlatVector::GetDataMutable(result), scan_count, result_offset, + [](T value, idx_t) { return value; }); +} + template void RLEScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset) { @@ -589,7 +695,6 @@ void RLESelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector_coun RLEScanConstant(scan_state, current_run, vector_count, result); return; } - auto result_data = FlatVector::Writer(result, sel_count, result_offset); // Keep the current run until the selection advances past it. @@ -628,18 +733,25 @@ void RLEFilter(ColumnSegment &segment, ColumnScanState &state, idx_t vector_coun return; } const auto run_values = scan_state.layout.GetRunValues(run_count); + const auto has_dictionary = scan_state.EnsureDictionary(result.GetType()); if (!scan_state.filter_cache || !scan_state.filter_cache->IsValidFor(filter_state)) { - Vector values(result.GetType(), run_count); - memcpy(FlatVector::GetDataMutable(values), run_values.data(), run_count * sizeof(T)); - FlatVector::SetSize(values, count_t(run_count)); - scan_state.filter_cache = filter_state.CreateCache(values, run_count); + if (has_dictionary) { + auto &values = scan_state.dictionary->data; + scan_state.filter_cache = filter_state.CreateCache(values, values.size()); + } else { + Vector values(result.GetType(), run_count); + scan_state.CopyRunValues(values, run_count); + FlatVector::SetSize(values, count_t(run_count)); + scan_state.filter_cache = filter_state.CreateCache(values, run_count); + } } if (scan_state.filter_cache->CanSkipAll()) { scan_state.SkipInternal(vector_count); sel_count = 0; return; } - if (scan_state.filter_cache->CanAcceptAll()) { + const bool use_dictionary = has_dictionary && scan_state.ShouldUseDictionary(vector_count, sel_count); + if (scan_state.filter_cache->CanAcceptAll() && (!has_dictionary || use_dictionary)) { SelectionVector no_values; scan_state.filter_cache->Filter(no_values, sel, sel_count); RLEScan(segment, state, vector_count, result); diff --git a/src/duckdb/src/storage/table/chunk_info.cpp b/src/duckdb/src/storage/table/chunk_info.cpp index 784968a77..0a9b01319 100644 --- a/src/duckdb/src/storage/table/chunk_info.cpp +++ b/src/duckdb/src/storage/table/chunk_info.cpp @@ -990,9 +990,25 @@ transaction_t ChunkVectorInfo::ConstantDeleteId() const { void ChunkVectorInfo::Write(WriteStream &writer, VisibilityBound visibility_bound, idx_t row_count) const { D_ASSERT(row_count > 0 && row_count <= STANDARD_VECTOR_SIZE); - SelectionVector sel(STANDARD_VECTOR_SIZE); - transaction_t transaction_id = DConstants::INVALID_INDEX; - idx_t count = GetSelVector(TransactionData(transaction_id, visibility_bound), sel, row_count); + TransactionData transaction(DConstants::INVALID_INDEX, visibility_bound); + // all rows are inserted and the rows in deleted_mask are exactly the deleted rows + const bool use_deleted_mask = delete_state == DeleteIdState::MASKED && HasConstantInsertionId() && + transaction.view.Sees(ConstantInsertId()) && transaction.view.Sees(mask_delete_id); + SelectionVector sel; + idx_t count; + if (use_deleted_mask) { + count = row_count - deleted_mask.CountValid(row_count); +#ifdef DEBUG + SelectionVector verify_sel(STANDARD_VECTOR_SIZE); + D_ASSERT(GetSelVector(transaction, verify_sel, row_count) == count); + for (idx_t i = 0; i < count; i++) { + D_ASSERT(!deleted_mask.RowIsValid(verify_sel.get_index(i))); + } +#endif + } else { + sel.Initialize(STANDARD_VECTOR_SIZE); + count = GetSelVector(transaction, sel, row_count); + } if (count == row_count) { // nothing is deleted: skip writing anything writer.Write(ChunkInfoType::EMPTY_INFO); @@ -1008,12 +1024,27 @@ void ChunkVectorInfo::Write(WriteStream &writer, VisibilityBound visibility_boun writer.Write(ChunkInfoType::VECTOR_INFO); writer.Write(start); ValidityMask mask(STANDARD_VECTOR_SIZE); - mask.Initialize(STANDARD_VECTOR_SIZE); - for (idx_t i = 0; i < count; i++) { - mask.SetInvalid(sel.get_index(i)); - } - for (idx_t i = row_count; i < STANDARD_VECTOR_SIZE; i++) { - mask.SetInvalid(i); + if (use_deleted_mask) { + mask.Copy(deleted_mask, STANDARD_VECTOR_SIZE); + mask.EnsureWritable(); + for (idx_t i = row_count; i < STANDARD_VECTOR_SIZE; i++) { + mask.SetInvalidUnsafe(i); + } + } else { + // sel holds the visible rows in ascending order: only the rows in between are deleted + mask.SetAllInvalid(STANDARD_VECTOR_SIZE); + idx_t row_idx = 0; + for (idx_t i = 0; i < count; i++) { + auto visible_idx = sel.get_index(i); + D_ASSERT(visible_idx >= row_idx); + for (; row_idx < visible_idx; row_idx++) { + mask.SetValidUnsafe(row_idx); + } + row_idx = visible_idx + 1; + } + for (; row_idx < row_count; row_idx++) { + mask.SetValidUnsafe(row_idx); + } } mask.Write(writer, STANDARD_VECTOR_SIZE); } diff --git a/src/duckdb/src/storage/table/column_segment.cpp b/src/duckdb/src/storage/table/column_segment.cpp index b0fb07b61..dd072f1d7 100644 --- a/src/duckdb/src/storage/table/column_segment.cpp +++ b/src/duckdb/src/storage/table/column_segment.cpp @@ -506,6 +506,9 @@ idx_t ColumnSegment::FilterSelection(SelectionVector &sel, Vector &vector, Unifi idx_t ColumnSegment::FilterSelection(SelectionVector &sel, Vector &vector, TableFilterState &filter_state, idx_t scan_count, idx_t &approved_tuple_count) { auto &state = filter_state.Cast(); + if (state.TryFilterDictionary(sel, vector, approved_tuple_count)) { + return approved_tuple_count; + } if (state.fast_executor && (scan_count <= STANDARD_VECTOR_SIZE || (vector.GetVectorType() == VectorType::FLAT_VECTOR && !vector.GetType().IsNested() && scan_count <= vector.size()))) { diff --git a/src/duckdb/src/storage/table/standard_column_data.cpp b/src/duckdb/src/storage/table/standard_column_data.cpp index c9170845b..6c06d1474 100644 --- a/src/duckdb/src/storage/table/standard_column_data.cpp +++ b/src/duckdb/src/storage/table/standard_column_data.cpp @@ -6,6 +6,7 @@ #include "duckdb/storage/table/column_checkpoint_state.hpp" #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/storage/table/column_data_checkpointer.hpp" +#include "duckdb/storage/table/column_segment.hpp" namespace duckdb { @@ -88,18 +89,27 @@ void StandardColumnData::Filter(TransactionData transaction, idx_t vector_index, auto scan_type = GetVectorScanType(state, target_count, result); bool scan_entire_vector = scan_type == ScanVectorType::SCAN_ENTIRE_VECTOR; bool verify_fetch_row = state.scan_options && state.scan_options->force_fetch_row; - if (!has_filter || !validity_has_filter || !scan_entire_vector || verify_fetch_row || !filter_state.can_cache) { - // Cached evaluation requires safe predicates and complete value validity. - ColumnData::Filter(transaction, vector_index, state, result, sel, count, filter, filter_state); - return; - } - bool needs_row_validity = false; - if (!filter_includes_validity) { + bool use_specialized_filter = + has_filter && validity_has_filter && scan_entire_vector && !verify_fetch_row && filter_state.can_cache; + if (use_specialized_filter && !filter_includes_validity) { lock_guard guard(stats_lock); - needs_row_validity = state.current->GetNode().GetStats().CanHaveNull(); + use_specialized_filter = !state.current->GetNode().GetStats().CanHaveNull(); } - if (needs_row_validity) { - ColumnData::Filter(transaction, vector_index, state, result, sel, count, filter, filter_state); + if (!use_specialized_filter) { + // Avoid constructing dictionary selections when few rows remain or only validity is tested. + if (compression && compression->type == CompressionType::COMPRESSION_RLE && !verify_fetch_row && + result.GetVectorType() == VectorType::FLAT_VECTOR && + (count <= target_count / 2 || IsDirectNullCheckFilter(filter))) { + const auto scan_count = ScanVector(transaction, vector_index, state, result, target_count, + ScanVectorType::SCAN_FLAT_VECTOR, state.update_scan_type); + validity->ScanVector(transaction, vector_index, state.child_states[0], result, target_count, + ScanVectorType::SCAN_FLAT_VECTOR, state.update_scan_type); + FlatVector::SetSize(result, count_t(scan_count)); + ColumnSegment::FilterSelection(sel, result, filter_state, scan_count, count); + } else { + // Cached evaluation requires safe predicates and complete value validity. + ColumnData::Filter(transaction, vector_index, state, result, sel, count, filter, filter_state); + } return; } FilterVector(state, result, target_count, sel, count, filter, filter_state); diff --git a/src/duckdb/src/storage/table/validity_column_data.cpp b/src/duckdb/src/storage/table/validity_column_data.cpp index 0ca346de0..f38296ae0 100644 --- a/src/duckdb/src/storage/table/validity_column_data.cpp +++ b/src/duckdb/src/storage/table/validity_column_data.cpp @@ -1,6 +1,7 @@ #include "duckdb/storage/table/validity_column_data.hpp" #include "duckdb/storage/table/column_checkpoint_state.hpp" #include "duckdb/storage/table/scan_state.hpp" +#include "duckdb/common/vector/dictionary_vector.hpp" namespace duckdb { @@ -31,6 +32,17 @@ static void ScanValidityMask(ColumnSegment &segment, Vector &result, idx_t count return; } } + if (result.GetVectorType() == VectorType::DICTIONARY_VECTOR) { + validity_t entries[ValidityMask::STANDARD_ENTRY_COUNT] = {}; + ValidityMask mask(entries, STANDARD_VECTOR_SIZE); + if (count > STANDARD_VECTOR_SIZE) { + mask.Initialize(count); + } + mask.SetAllValid(count); + scan(mask); + DictionaryVector::ApplyValidity(result, mask); + return; + } result.Flatten(); } scan(FlatVector::ValidityMutable(result)); diff --git a/src/duckdb/ub_src_function_scalar_variant.cpp b/src/duckdb/ub_src_function_scalar_variant.cpp index 77e49c36d..4782ee1e6 100644 --- a/src/duckdb/ub_src_function_scalar_variant.cpp +++ b/src/duckdb/ub_src_function_scalar_variant.cpp @@ -24,3 +24,5 @@ #include "src/function/scalar/variant/variant_utils.cpp" +#include "src/function/scalar/variant/variant_value.cpp" + diff --git a/src/duckdb/ub_src_main_capi_v2.cpp b/src/duckdb/ub_src_main_capi_v2.cpp index ee9017386..5c70d1a2a 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_crypto.cpp" + #include "src/main/capi/v2/capi_v2_custom_option.cpp" #include "src/main/capi/v2/capi_v2_custom_type.cpp" diff --git a/src/duckdb/ub_src_optimizer_join_order.cpp b/src/duckdb/ub_src_optimizer_join_order.cpp index ad09a8c90..66661b4d2 100644 --- a/src/duckdb/ub_src_optimizer_join_order.cpp +++ b/src/duckdb/ub_src_optimizer_join_order.cpp @@ -2,10 +2,16 @@ #include "src/optimizer/join_order/cost_model.cpp" +#include "src/optimizer/join_order/dphyp_enumerator.cpp" + #include "src/optimizer/join_order/filter_info.cpp" +#include "src/optimizer/join_order/greedy_join_enumerator.cpp" + #include "src/optimizer/join_order/join_node.cpp" +#include "src/optimizer/join_order/join_order_candidate.cpp" + #include "src/optimizer/join_order/join_order_operator.cpp" #include "src/optimizer/join_order/join_order_optimizer.cpp"