From b16f3151bfb59b8aeaf954a9032282c7da5af645 Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Tue, 24 Nov 2026 04:19:51 +0000 Subject: [PATCH] Update vendored DuckDB sources to 94a1663a4d3 --- .../core_functions/scalar/date/date_sub.cpp | 80 +- .../json_functions/json_serialize_plan.cpp | 3 + .../json_functions/json_serialize_sql.cpp | 3 + ...nerated_extension_loader_package_build.cpp | 8 +- .../catalog_entry/duck_schema_entry.cpp | 7 +- .../catalog_entry/macro_catalog_entry.cpp | 3 +- src/duckdb/src/common/sort/hashed_sort.cpp | 19 +- src/duckdb/src/common/sort/sort.cpp | 17 + src/duckdb/src/common/sort/sorted_run.cpp | 16 +- .../src/common/sort/sorted_run_merger.cpp | 12 + src/duckdb/src/common/types/type_manager.cpp | 4 + src/duckdb/src/execution/join_hashtable.cpp | 19 - .../operator/join/join_filter_pushdown.cpp | 39 +- .../join/physical_blockwise_nl_join.cpp | 11 +- .../physical_plan/plan_aggregate.cpp | 18 +- .../src/execution/radix_ht_adaptivity.cpp | 5 +- .../execution/radix_partitioned_hashtable.cpp | 7 +- .../aggregate_state_serialization.cpp | 26 + .../function/scalar/struct/remap_struct.cpp | 23 +- .../system/duckdb_grammar_extensions.cpp | 89 ++ .../src/function/table/system_functions.cpp | 1 + src/duckdb/src/function/table/table_scan.cpp | 2 + .../function/table/version/pragma_version.cpp | 6 +- .../include/duckdb/common/sorting/sort.hpp | 3 + .../duckdb/common/sorting/sort_key_prefix.hpp | 45 + .../src/include/duckdb/common/thread.hpp | 5 + .../duckdb/execution/join_hashtable.hpp | 4 - .../duckdb/execution/radix_ht_adaptivity.hpp | 4 +- .../function/aggregate_state_layout.hpp | 3 + .../function/table/system_functions.hpp | 4 + .../duckdb/main/capi_v2/extension_api_v2.hpp | 103 +++ .../src/include/duckdb/main/secret/secret.hpp | 8 + .../duckdb/main/secret/secret_manager.hpp | 11 + .../include/duckdb/parser/grammar_change.hpp | 15 + .../src/include/duckdb/parser/peg/matcher.hpp | 1 + .../parser/peg/transformer/parse_result.hpp | 174 ++-- .../duckdb/storage/table/append_state.hpp | 2 + .../duckdb/transaction/duck_transaction.hpp | 2 + .../duckdb/transaction/local_storage.hpp | 4 + .../duckdb/transaction/meta_transaction.hpp | 3 + .../duckdb/transaction/transaction.hpp | 2 +- src/duckdb/src/include/duckdb_extension_v2.h | 163 ++++ src/duckdb/src/include/duckdb_v2.h | 819 ++++++++++++++++++ .../src/main/capi/v2/capi_v2_secret.cpp | 675 +++++++++++++++ src/duckdb/src/main/secret/secret_manager.cpp | 91 +- .../optimizer/common_subplan_optimizer.cpp | 28 +- .../optimizer/pushdown/pushdown_aggregate.cpp | 15 +- .../pushdown/pushdown_outer_join.cpp | 108 ++- .../pushdown/pushdown_projection.cpp | 56 +- .../src/optimizer/rule/date_part_to_func.cpp | 55 ++ .../rule/date_trunc_simplification.cpp | 46 - src/duckdb/src/parser/peg/grammar_change.cpp | 23 + src/duckdb/src/parser/peg/matcher.cpp | 7 +- .../transformer/peg_transformer_factory.cpp | 50 +- src/duckdb/src/storage/local_storage.cpp | 3 + src/duckdb/src/storage/table/chunk_info.cpp | 4 + .../src/transaction/duck_transaction.cpp | 3 + .../src/transaction/meta_transaction.cpp | 2 + src/duckdb/ub_src_main_capi_v2.cpp | 2 + src/duckdb/ub_src_optimizer_rule.cpp | 2 + 60 files changed, 2618 insertions(+), 345 deletions(-) create mode 100644 src/duckdb/src/include/duckdb/common/sorting/sort_key_prefix.hpp create mode 100644 src/duckdb/src/main/capi/v2/capi_v2_secret.cpp create mode 100644 src/duckdb/src/optimizer/rule/date_part_to_func.cpp diff --git a/src/duckdb/extension/core_functions/scalar/date/date_sub.cpp b/src/duckdb/extension/core_functions/scalar/date/date_sub.cpp index 5f7840d10..d3b052716 100644 --- a/src/duckdb/extension/core_functions/scalar/date/date_sub.cpp +++ b/src/duckdb/extension/core_functions/scalar/date/date_sub.cpp @@ -7,6 +7,7 @@ #include "duckdb/common/types/timestamp.hpp" #include "duckdb/common/vector_operations/ternary_executor.hpp" #include "duckdb/optimizer/statistics_propagator.hpp" +#include "duckdb/storage/statistics/numeric_stats.hpp" namespace duckdb { @@ -446,8 +447,84 @@ void DateSubFunction(DataChunk &args, ExpressionState &state, Vector &result) { } // namespace +static int64_t CalendarMonthNumber(timestamp_t timestamp) { + int32_t year, month, day; + Date::Convert(Timestamp::GetDate(timestamp), year, month, day); + return int64_t(year) * Interval::MONTHS_PER_YEAR + month; +} + +static unique_ptr DateSubMonthStatistics(ClientContext &, FunctionStatisticsInput &input) { + const auto &starts = input.child_stats[1]; + const auto &ends = input.child_stats[2]; + if (!NumericStats::HasMinMax(starts) || !NumericStats::HasMinMax(ends)) { + return nullptr; + } + const auto start_min = NumericStats::GetMin(starts); + const auto start_max = NumericStats::GetMax(starts); + const auto end_min = NumericStats::GetMin(ends); + const auto end_max = NumericStats::GetMax(ends); + if (!start_min.IsFinite() || !start_max.IsFinite() || !end_min.IsFinite() || !end_max.IsFinite()) { + return nullptr; + } + const auto first_start_month = CalendarMonthNumber(start_min); + const auto first_end_month = CalendarMonthNumber(end_min); + // Leave the partial first month, where finite extrema can enclose -infinity, to scalar evaluation. + static const auto first_month = CalendarMonthNumber(timestamp_t(NumericLimits::Minimum())); + if (first_start_month == first_month || first_end_month == first_month) { + return nullptr; + } + const auto min_months = first_end_month - CalendarMonthNumber(start_max); + const auto max_months = CalendarMonthNumber(end_max) - first_start_month; + // An incomplete month can move the signed calendar-month difference one step toward zero. + auto result = BaseStatistics::CreateUnknown(LogicalType::BIGINT); + NumericStats::SetMin(result, min_months > 0 ? min_months - 1 : min_months); + NumericStats::SetMax(result, max_months < 0 ? max_months + 1 : max_months); + return result.ToUnique(); +} + +static unique_ptr BindDateSub(BindScalarFunctionInput &input) { + auto part = input.TryGetConstant(0); + DatePartSpecifier unit; + if (!part || part->IsNull() || !TryGetDatePartSpecifier(part->ToString(), unit)) { + return nullptr; + } + auto &function = input.GetBoundFunction(); + switch (unit) { + case DatePartSpecifier::MONTH: + if (function.GetArguments()[1].id() == LogicalTypeId::TIMESTAMP) { + function.SetStatisticsCallback(DateSubMonthStatistics); + } + return nullptr; + case DatePartSpecifier::WEEK: + case DatePartSpecifier::YEARWEEK: + case DatePartSpecifier::DAY: + case DatePartSpecifier::DOW: + case DatePartSpecifier::ISODOW: + case DatePartSpecifier::DOY: + case DatePartSpecifier::JULIAN_DAY: + if (function.GetArguments()[1].id() == LogicalTypeId::TIME) { + return nullptr; + } + break; + case DatePartSpecifier::MICROSECONDS: + case DatePartSpecifier::MILLISECONDS: + case DatePartSpecifier::SECOND: + case DatePartSpecifier::EPOCH: + case DatePartSpecifier::MINUTE: + case DatePartSpecifier::HOUR: + break; + default: + return nullptr; + } + function.SetArgProperties(1, ArgProperties().NonIncreasing()); + function.SetArgProperties(2, ArgProperties().NonDecreasing()); + function.SetStatisticsCallback(StatisticsPropagator::PropagateFiniteMonotoneBounds); + return nullptr; +} + // Names the "part,startdate,enddate" triple shared by date_sub's per-type overloads. static ScalarFunction NameDateSubPartStartEndArguments(ScalarFunction fun, const LogicalType &type) { + fun.SetBindCallback(BindDateSub); fun.GetSignature() .AddParameter("part", LogicalType::VARCHAR) .AddParameter("startdate", type) @@ -465,9 +542,6 @@ ScalarFunctionSet DateSubFun::GetFunctions() { ScalarFunction({}, LogicalType::BIGINT, DateSubFunction), LogicalType::TIME)); // throws for unsupported date parts, and when the difference overflows date_sub.SetFallible(); - date_sub.SetArgProperties(1, ArgProperties().NonIncreasing()); - date_sub.SetArgProperties(2, ArgProperties().NonDecreasing()); - date_sub.SetStatisticsCallback(StatisticsPropagator::PropagateFiniteMonotoneBounds); return date_sub; } diff --git a/src/duckdb/extension/json/json_functions/json_serialize_plan.cpp b/src/duckdb/extension/json/json_functions/json_serialize_plan.cpp index a9d9f250d..cb0dbbeed 100644 --- a/src/duckdb/extension/json/json_functions/json_serialize_plan.cpp +++ b/src/duckdb/extension/json/json_functions/json_serialize_plan.cpp @@ -181,6 +181,9 @@ static void JsonSerializePlanFunction(DataChunk &args, ExpressionState &state, V } catch (std::exception &ex) { ErrorData error(ex); + if (error.Type() == ExceptionType::OUT_OF_MEMORY) { + throw; + } yyjson_mut_obj_add_true(doc, result_obj, "error"); // error type and message yyjson_mut_obj_add_strcpy(doc, result_obj, "error_type", diff --git a/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp b/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp index 4acd351aa..511a9597a 100644 --- a/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp +++ b/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp @@ -129,6 +129,9 @@ static void JsonSerializeFunction(DataChunk &args, ExpressionState &state, Vecto } catch (std::exception &ex) { ErrorData error(ex); + if (error.Type() == ExceptionType::OUT_OF_MEMORY) { + throw; + } yyjson_mut_obj_add_true(doc, result_obj, "error"); yyjson_mut_obj_add_strcpy(doc, result_obj, "error_type", StringUtil::Lower(Exception::ExceptionTypeToString(error.Type())).c_str()); diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 1001ddaf9..301086e44 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-alpha57181"; + descriptor->api_version = "v2.1.0-alpha57291"; 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-alpha57181"; + descriptor->api_version = "v2.1.0-alpha57291"; 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-alpha57181"; + descriptor->api_version = "v2.1.0-alpha57291"; 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-alpha57181"; + descriptor->api_version = "v2.1.0-alpha57291"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/catalog/catalog_entry/duck_schema_entry.cpp b/src/duckdb/src/catalog/catalog_entry/duck_schema_entry.cpp index 70dd8e76e..ea05f63fc 100644 --- a/src/duckdb/src/catalog/catalog_entry/duck_schema_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/duck_schema_entry.cpp @@ -152,9 +152,12 @@ optional_ptr DuckSchemaEntry::AddEntryInternal(CatalogTransaction auto existing_entry = set.GetEntry(transaction, entry_name); auto existing_type = existing_entry ? existing_entry->type : entry_type; throw CatalogException::EntryAlreadyExists(existing_type, entry_name); - } else { - return nullptr; } + if (on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT) { + // the entry was created after it was dropped: by a concurrent statement of this transaction + throw TransactionException("Catalog write-write conflict on create or replace of %s", entry_name); + } + return nullptr; } return result; } diff --git a/src/duckdb/src/catalog/catalog_entry/macro_catalog_entry.cpp b/src/duckdb/src/catalog/catalog_entry/macro_catalog_entry.cpp index e3106ced3..3ef8c27f1 100644 --- a/src/duckdb/src/catalog/catalog_entry/macro_catalog_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/macro_catalog_entry.cpp @@ -100,7 +100,8 @@ unique_ptr MacroCatalogEntry::AlterEntry(CatalogTransaction transa if (!temporary && attached.HasStorageManager() && !attached.IsTemporary()) { auto &storage_manager = attached.GetStorageManager(); const auto since = StorageCompatibility::FromString("v2.1.0").storage_version; - if (!storage_manager.InMemory() && storage_manager.GetStorageVersion() < since) { + // a committed record replays regardless of the version in the file header + if (storage_manager.IsLoaded() && !storage_manager.InMemory() && storage_manager.GetStorageVersion() < since) { string msg = "Dropping a single overload is only supported for storage versions v2.1.0 and higher.\n"; msg += "Use an in-memory database, ATTACH with (STORAGE_VERSION v2.1.0), or a TEMP macro"; throw CatalogException(msg); diff --git a/src/duckdb/src/common/sort/hashed_sort.cpp b/src/duckdb/src/common/sort/hashed_sort.cpp index bf18a3856..33007e3f9 100644 --- a/src/duckdb/src/common/sort/hashed_sort.cpp +++ b/src/duckdb/src/common/sort/hashed_sort.cpp @@ -23,7 +23,7 @@ class HashedSortGroup { using Orders = vector; using Types = vector; - HashedSortGroup(ClientContext &client, Sort &sort, idx_t group_idx); + HashedSortGroup(Sort &sort, idx_t group_idx); const idx_t group_idx; atomic count; @@ -42,9 +42,8 @@ class HashedSortGroup { ColumnDataAppendState direct_append_state; }; -HashedSortGroup::HashedSortGroup(ClientContext &client, Sort &sort, idx_t group_idx) +HashedSortGroup::HashedSortGroup(Sort &sort, idx_t group_idx) : group_idx(group_idx), count(0), sort(sort), tasks_completed(0) { - sort_global = sort.GetGlobalSinkState(client); } //===--------------------------------------------------------------------===// @@ -293,7 +292,7 @@ void HashedSortGlobalSinkState::CombineLocalPartition(GroupingPartition &local_p auto &group_data = groups[group_idx]; if (group_data->Count()) { - hash_group = make_uniq(client, *hashed_sort.sort, group_idx); + hash_group = make_uniq(*hashed_sort.sort, group_idx); } } @@ -339,6 +338,17 @@ SinkFinalizeType HashedSort::Finalize(ClientContext &client, OperatorSinkFinaliz continue; } + // The partition is complete: register the group's sort now, reserving its size if below the default minimum + if (!gsink.CanBypassSort(hash_bin)) { + hash_group->sort_global = sort->GetGlobalSinkState(client); + const auto count = partition.Count(); + const auto row_size = count * partition.GetLayout().GetRowWidth(); + D_ASSERT(partition.SizeInBytes() >= row_size); + // the variable-size data is what the partition holds beyond its fixed-size rows + const auto variable_data_size = partition.SizeInBytes() - row_size; + sort->SetExpectedSize(client, *hash_group->sort_global, count, variable_data_size); + } + // Prepare to scan into the sort auto ¶llel_scan = hash_group->parallel_scan; partition.InitializeScan(parallel_scan, partition_ids); @@ -564,6 +574,7 @@ void HashedSort::SortColumnData(ExecutionContext &context, hash_t hash_bin, Oper TupleDataLocalScanState local_scan; partition.InitializeScan(local_scan); + D_ASSERT(hash_group.sort_global); auto sort_local = sort->GetLocalSinkState(context); OperatorSinkInput sink {*hash_group.sort_global, *sort_local, finalize.interrupt_state}; idx_t combined = 0; diff --git a/src/duckdb/src/common/sort/sort.cpp b/src/duckdb/src/common/sort/sort.cpp index c6782a5b8..5b010899d 100644 --- a/src/duckdb/src/common/sort/sort.cpp +++ b/src/duckdb/src/common/sort/sort.cpp @@ -532,6 +532,23 @@ OperatorPartitionData Sort::GetPartitionData(ExecutionContext &context, DataChun //===--------------------------------------------------------------------===// // Non-Standard Interface //===--------------------------------------------------------------------===// +void Sort::SetExpectedSize(ClientContext &context, GlobalSinkState &gstate, idx_t count, + idx_t variable_data_size) const { + auto &sink = gstate.Cast(); + D_ASSERT(sink.sunk_tuples == 0); + // key and payload rows, variable-size data and merge buffer, as SizeInBytesForSorting measures them + const auto key_width = key_layout->GetRowWidth(); + auto expected_size = count * (key_width + payload_layout->GetRowWidth()) + variable_data_size + + SortMergeBuffer::MaximumSize(count, key_width); + auto &state = *sink.temporary_memory_state; + // only lower the reservation: a larger sort keeps the default minimum and grows on demand + expected_size = MinValue(expected_size, state.GetMinimumReservation()); + if (expected_size == 0) { + return; + } + state.SetRemainingSizeAndUpdateReservation(context.GetContext(), expected_size); +} + SourceResultType Sort::MaterializeColumnData(ExecutionContext &context, OperatorSourceInput &input) const { auto &gstate = input.global_state.Cast(); diff --git a/src/duckdb/src/common/sort/sorted_run.cpp b/src/duckdb/src/common/sort/sorted_run.cpp index ee7abbcb5..4c3f9c4bc 100644 --- a/src/duckdb/src/common/sort/sorted_run.cpp +++ b/src/duckdb/src/common/sort/sorted_run.cpp @@ -8,6 +8,7 @@ #include "duckdb/common/types/row/tuple_data_collection.hpp" #include "duckdb/common/sorting/sort.hpp" #include "duckdb/common/sorting/sort_key.hpp" +#include "duckdb/common/sorting/sort_key_prefix.hpp" #include "duckdb/common/sorting/buffered_merge.hpp" #include "duckdb/common/types/row/block_iterator.hpp" @@ -338,24 +339,13 @@ static void SortTiedBucket(ClientContext &context, const ITERATOR &begin, const } varying_bits |= words[0] ^ SUFFIX::ExtractWord(*it, offset); } - // The common first word can cache the suffix during this synchronous refinement. - struct PrefixRestorer { - ITERATOR begin; - ITERATOR end; - uint64_t prefix; - - ~PrefixRestorer() { - for (auto it = begin; it != end; ++it) { - it->part0 = prefix; - } - } - } restore {begin, end, samples[0].part0}; + SortKeyPrefixScope prefix_scope(begin, end); scanned = 0; for (auto it = begin; it != end; ++it) { if (++scanned % STANDARD_VECTOR_SIZE == 0) { context.FastInterruptCheck(); } - it->part0 = SUFFIX::ExtractWord(*it, offset); + prefix_scope.Set(*it, SUFFIX::ExtractWord(*it, offset)); } SUFFIX suffix(extract_key, varying_bits); duckdb_ska_sort::ska_sort(begin, end, suffix, merge); diff --git a/src/duckdb/src/common/sort/sorted_run_merger.cpp b/src/duckdb/src/common/sort/sorted_run_merger.cpp index b813fb008..b7b7972ce 100644 --- a/src/duckdb/src/common/sort/sorted_run_merger.cpp +++ b/src/duckdb/src/common/sort/sorted_run_merger.cpp @@ -8,6 +8,7 @@ #include "duckdb/common/thread_annotation.hpp" #include "duckdb/common/sorting/sorted_run.hpp" #include "duckdb/common/sorting/sort_key.hpp" +#include "duckdb/common/sorting/sort_key_prefix.hpp" #include "duckdb/common/sorting/buffered_merge.hpp" #include "duckdb/common/types/row/block_iterator.hpp" #include "duckdb/common/types/row/tuple_data_collection.hpp" @@ -83,6 +84,9 @@ struct MergePrefixLess { } bool operator()(const SORT_KEY &lhs, const SORT_KEY &rhs) const { + if (lhs.part0 != rhs.part0) { + return lhs.part0 < rhs.part0; + } const auto lhs_size = lhs.GetHeapSize(); const auto rhs_size = rhs.GetHeapSize(); D_ASSERT(lhs_size > SORT_KEY::INLINE_LENGTH && rhs_size > SORT_KEY::INLINE_LENGTH); @@ -782,6 +786,14 @@ void SortedRunMergerLocalState::TemplatedMergePartition(SortedRunMergerGlobalSta unsafe_array_ptr(merged_partition_keys, merged_partition_count), run_boundaries); if (prefix != 0) { // Sorted endpoints establish this prefix for every key in each gathered fragment. + unsafe_array_ptr keys(merged_partition_keys, merged_partition_count); + SortKeyPrefixScope> prefix_scope(keys.begin(), keys.end()); + for (auto &key : keys) { + D_ASSERT(key.GetHeapSize() >= prefix); + uint64_t word = 0; + memcpy(&word, key.GetData() + prefix, MinValue(sizeof(word), key.GetHeapSize() - prefix)); + prefix_scope.Set(key, BSwapIfLE(word)); + } const MergePrefixLess compare(prefix); const auto prefix_fallback = [&](SORT_KEY *begin, SORT_KEY *end) { duckdb_pdqsort::pdqsort_branchless(begin, end, compare); diff --git a/src/duckdb/src/common/types/type_manager.cpp b/src/duckdb/src/common/types/type_manager.cpp index f0a8deb4d..b0d54d04a 100644 --- a/src/duckdb/src/common/types/type_manager.cpp +++ b/src/duckdb/src/common/types/type_manager.cpp @@ -1,6 +1,7 @@ #include "duckdb/common/types/type_manager.hpp" #include "duckdb/common/type_visitor.hpp" +#include "duckdb/common/error_data.hpp" #include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/parser/parser.hpp" #include "duckdb/planner/binder.hpp" @@ -26,6 +27,9 @@ static LogicalType TransformStringToUnboundType(const string &str, ClientContext try { column_list = Parser(context).ParseColumnList("dummy " + str); } catch (const std::runtime_error &e) { + if (ErrorData(e).Type() == ExceptionType::OUT_OF_MEMORY) { + throw; + } const vector suggested_types {"BIGINT", "INT8", "LONG", diff --git a/src/duckdb/src/execution/join_hashtable.cpp b/src/duckdb/src/execution/join_hashtable.cpp index 781b63b05..053ceaa34 100644 --- a/src/duckdb/src/execution/join_hashtable.cpp +++ b/src/duckdb/src/execution/join_hashtable.cpp @@ -2778,25 +2778,6 @@ idx_t JoinHashTable::FillWithHTOffsets(JoinHTScanState &state, Vector &addresses return key_count; } -idx_t JoinHashTable::ScanKeyColumn(Vector &addresses, Vector &result, idx_t column_index) const { - FlatVector::SetSize(result, count_t(0)); - // nothing to scan if the build side is empty - if (data_collection->ChunkCount() == 0) { - return 0; - } - D_ASSERT(result.GetType() == layout_ptr->GetTypes()[column_index]); - JoinHTScanState join_ht_state(*data_collection, 0, data_collection->ChunkCount(), output_columns.size(), - TupleDataPinProperties::KEEP_EVERYTHING_PINNED); - auto key_count = FillWithHTOffsets(join_ht_state, addresses); - if (key_count == 0) { - return 0; - } - const auto &sel = *FlatVector::IncrementalSelectionVector(); - data_collection->Gather(addresses, sel, key_count, column_index, result, sel, nullptr); - FlatVector::SetSize(result, count_t(key_count)); - return key_count; -} - idx_t JoinHashTable::GetTotalSize(const vector &partition_sizes, const vector &partition_counts, idx_t &max_partition_size, idx_t &max_partition_count) const { const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits); diff --git a/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp b/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp index 489955acd..29a31ff84 100644 --- a/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp +++ b/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp @@ -470,25 +470,36 @@ static unique_ptr CreateJoinFilterComparisonExpression( return RetainRuntimeFilterNulls(std::move(filter_expr), std::move(null_check_input)); } -static bool CollectInFilterValues(ClientContext &context, Vector &build_vector, const LogicalType &filter_input_type, - idx_t threshold, bool retain_nulls, vector &in_list) { +static bool CollectInFilterValues(ClientContext &context, TupleDataCollection &collection, column_t column_index, + const LogicalType &filter_input_type, idx_t threshold, bool retain_nulls, + vector &in_list) { + const auto total_count = collection.Count(); + if (total_count == 0) { + return false; + } + TupleDataScanState scan_state; + collection.InitializeScan(scan_state, {column_index}, TupleDataPinProperties::UNPIN_AFTER_DONE); + DataChunk build_keys; + collection.InitializeScanChunk(scan_state, build_keys); GroupedAggregateHashTable distinct_keys(context, Allocator::Get(context), {filter_input_type}); DataChunk keys; keys.Initialize(context, {filter_input_type}); - Vector input(build_vector.GetType()); Vector addresses(LogicalType::POINTER); SelectionVector new_groups(STANDARD_VECTOR_SIZE); CastFunctionSet cast_functions; auto cast_input = GetCastFunctionInput::Default(); - for (idx_t offset = 0; offset < build_vector.size(); offset += STANDARD_VECTOR_SIZE) { - const auto count = MinValue(STANDARD_VECTOR_SIZE, build_vector.size() - offset); + idx_t scanned_count = 0; + // Read one chunk at a time so oversized filters can stop early. + while (collection.Scan(scan_state, build_keys)) { keys.Reset(); - input.Slice(build_vector, offset, offset + count); + const auto count = build_keys.size(); + scanned_count += count; + auto &build_vector = build_keys.data[0]; if (build_vector.GetType() == filter_input_type) { - keys.data[0].Reference(input); + keys.data[0].Reference(build_vector); } else { string error; - if (!VectorOperations::TryCast(cast_functions, cast_input, input, keys.data[0], count, &error)) { + if (!VectorOperations::TryCast(cast_functions, cast_input, build_vector, keys.data[0], count, &error)) { return false; } } @@ -508,7 +519,7 @@ static bool CollectInFilterValues(ClientContext &context, Vector &build_vector, } } } - return true; + return scanned_count == total_count; } bool JoinFilterPushdownInfo::PushInFilter(ClientContext &context, const JoinFilterPushdownFilter &info, @@ -518,12 +529,6 @@ bool JoinFilterPushdownInfo::PushInFilter(ClientContext &context, const JoinFilt // Generate an IN filter by scanning the build-side key column. auto build_idx = join_condition[filter_idx]; const auto &runtime_type = ht.conditions[build_idx].GetLHS().GetReturnType(); - Vector tuples_addresses(LogicalType::POINTER, ht.Count()); - Vector build_vector(ht.layout_ptr->GetTypes()[build_idx], ht.Count()); - auto key_count = ht.ScanKeyColumn(tuples_addresses, build_vector, build_idx); - if (key_count == 0 || key_count != ht.Count()) { - return false; - } const auto retain_nulls = ht.conditions[build_idx].GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM; const auto reconstruct_expression = @@ -544,8 +549,8 @@ bool JoinFilterPushdownInfo::PushInFilter(ClientContext &context, const JoinFilt const auto dynamic_or_filter_threshold = Settings::Get(context); vector in_list; - if (!CollectInFilterValues(context, build_vector, filter_input_type, dynamic_or_filter_threshold, retain_nulls, - in_list)) { + if (!CollectInFilterValues(context, ht.GetDataCollection(), build_idx, filter_input_type, + dynamic_or_filter_threshold, retain_nulls, in_list)) { return false; } diff --git a/src/duckdb/src/execution/operator/join/physical_blockwise_nl_join.cpp b/src/duckdb/src/execution/operator/join/physical_blockwise_nl_join.cpp index 6089d6a62..952f4eb15 100644 --- a/src/duckdb/src/execution/operator/join/physical_blockwise_nl_join.cpp +++ b/src/duckdb/src/execution/operator/join/physical_blockwise_nl_join.cpp @@ -196,12 +196,19 @@ OperatorResultType PhysicalBlockwiseNLJoin::ExecuteInternal(ExecutionContext &co // set the match flags in the LHS state.left_outer.SetMatches(state.match_sel, result_count); // set the match flag in the RHS - gstate.right_outer.SetMatch(state.cross_product.ScanPosition() + state.cross_product.PositionInChunk()); + if (gstate.right_outer.Enabled()) { + lock_guard guard(gstate.lock); + gstate.right_outer.SetMatch(state.cross_product.ScanPosition() + + state.cross_product.PositionInChunk()); + } } else { // set the match flag in the LHS state.left_outer.SetMatch(state.cross_product.PositionInChunk()); // set the match flags in the RHS - gstate.right_outer.SetMatches(state.match_sel, result_count, state.cross_product.ScanPosition()); + if (gstate.right_outer.Enabled()) { + lock_guard guard(gstate.lock); + gstate.right_outer.SetMatches(state.match_sel, result_count, state.cross_product.ScanPosition()); + } } intermediate_chunk->Slice(state.match_sel, result_count); } diff --git a/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp b/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp index ec2b3cf1a..b5c6dcf10 100644 --- a/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp @@ -240,8 +240,22 @@ static bool CanUsePerfectHashAggregate(ClientContext &context, LogicalAggregate } for (auto &expression : op.expressions) { auto &aggregate = expression->Cast(); - if (aggregate.IsDistinct() || !aggregate.Function().HasStateCombineCallback()) { - // distinct aggregates are not supported in perfect hash aggregates + const auto &function = aggregate.Function(); + if (aggregate.IsDistinct() || !function.HasStateCombineCallback()) { + return false; + } + if (!function.HasGetStateTypeCallback() || function.HasStateDestructorCallback()) { + return false; + } + const auto layout = function.GetStateType(aggregate.BindInfo().get()); + // Preserve min/max and fixed-size sketch fast paths, excluding sorted aggregate buffers. + const auto &name = function.GetName(); + if (function.GetArguments().size() == 1 && layout.field.kind != AggregateFieldKind::LIST && + (name == "min" || name == "max" || name == "approx_count_distinct")) { + continue; + } + if (function.HasExportAggregateStateCallback() || function.HasImportAggregateStateCallback() || + !layout.field.IsFixedSize(layout.type)) { return false; } } diff --git a/src/duckdb/src/execution/radix_ht_adaptivity.cpp b/src/duckdb/src/execution/radix_ht_adaptivity.cpp index 9d0110ce6..b5ff89e45 100644 --- a/src/duckdb/src/execution/radix_ht_adaptivity.cpp +++ b/src/duckdb/src/execution/radix_ht_adaptivity.cpp @@ -110,8 +110,9 @@ bool RadixHTAdaptivity::TryGrow(RadixHTGlobalSinkState &gstate, RadixHTLocalSink void RadixHTAdaptivity::MaybeSkipLookups(const RadixHTGlobalSinkState &gstate, GroupedAggregateHashTable &ht) { const auto &state = ht.GetAdaptivityState(); + // Retries run at table boundaries, so keep each append-only fill within the retry window. if (state.LookupsSkipped() || gstate.number_of_threads <= RadixHTConfig::GROW_STRATEGY_THREAD_THRESHOLD || - ht.Capacity() != gstate.config.sink_capacity) { + GroupedAggregateHashTable::ResizeThreshold(ht.Capacity()) > MAX_LOOKUP_RETRY_ROWS) { return; } @@ -132,7 +133,7 @@ void RadixHTAdaptivity::MaybeSkipLookups(const RadixHTGlobalSinkState &gstate, G } const auto recent_reduction = static_cast(recent_reduced_rows) / static_cast(recent_input_rows); const auto reduction = static_cast(cycle_input - ht.Count()) / static_cast(cycle_input); - if (reduction < MINIMUM_SMALL_TABLE_REDUCTION && recent_reduction < MINIMUM_SMALL_TABLE_REDUCTION) { + if (reduction < MINIMUM_LOOKUP_REDUCTION && recent_reduction < MINIMUM_LOOKUP_REDUCTION) { retry_interval_rows = ClampValue(ht.GetMaterializedCount() / LOOKUP_RETRY_MATERIALIZED_ROWS_DIVISOR, MIN_LOOKUP_RETRY_ROWS, MAX_LOOKUP_RETRY_ROWS); ht.SkipLookups(); diff --git a/src/duckdb/src/execution/radix_partitioned_hashtable.cpp b/src/duckdb/src/execution/radix_partitioned_hashtable.cpp index af641fea5..a844cbfd4 100644 --- a/src/duckdb/src/execution/radix_partitioned_hashtable.cpp +++ b/src/duckdb/src/execution/radix_partitioned_hashtable.cpp @@ -843,8 +843,11 @@ void RadixPartitionedHashTable::Combine(ExecutionContext &context, GlobalSinkSta return; } - // Set any_combined, then check one last time whether we need to repartition - gstate.any_combined = true; + // Finish any in-flight partition update before freezing the target. + if (!gstate.any_combined) { + const annotated_lock_guard guard {gstate.lock}; + gstate.any_combined = true; + } MaybeRepartition(context.client, gstate, lstate, true); auto &ht = *lstate.ht; diff --git a/src/duckdb/src/function/aggregate_state_serialization.cpp b/src/duckdb/src/function/aggregate_state_serialization.cpp index f87ad5248..1d60d600a 100644 --- a/src/duckdb/src/function/aggregate_state_serialization.cpp +++ b/src/duckdb/src/function/aggregate_state_serialization.cpp @@ -11,6 +11,32 @@ namespace duckdb { +bool AggregateStateField::IsFixedSize(const LogicalType &type) const { + switch (kind) { + case AggregateFieldKind::PRIMITIVE: + return TypeIsConstantSize(type.InternalType()); + case AggregateFieldKind::OPTIONAL_VALUE: + return children.size() == 1 && children[0].IsFixedSize(type); + case AggregateFieldKind::STRUCT: { + if (type.id() != LogicalTypeId::STRUCT) { + return false; + } + const auto &types = StructType::GetChildTypes(type); + if (types.size() != children.size()) { + return false; + } + for (idx_t i = 0; i < types.size(); i++) { + if (!children[i].IsFixedSize(types[i].second)) { + return false; + } + } + return true; + } + default: + return false; + } +} + namespace { template diff --git a/src/duckdb/src/function/scalar/struct/remap_struct.cpp b/src/duckdb/src/function/scalar/struct/remap_struct.cpp index e276238e9..3e77fd559 100644 --- a/src/duckdb/src/function/scalar/struct/remap_struct.cpp +++ b/src/duckdb/src/function/scalar/struct/remap_struct.cpp @@ -23,10 +23,14 @@ static bool IsRemappable(const LogicalType &type) { struct RemapColumnInfo { optional_idx index; optional_idx default_index; + //! Whether the field is built from child_remap_info instead of being referenced as a whole. + //! A struct without fields is built from no children, so an empty child_remap_info does not tell the two apart. + bool is_nested = false; vector child_remap_info; inline bool operator==(const RemapColumnInfo &rhs) const { - return index == rhs.index && default_index == rhs.default_index && child_remap_info == rhs.child_remap_info; + return index == rhs.index && default_index == rhs.default_index && is_nested == rhs.is_nested && + child_remap_info == rhs.child_remap_info; }; }; @@ -73,7 +77,7 @@ void RemapChildVectors(const Vector &result, const vector> &in // set up the correct vector references for (idx_t i = 0; i < remap_info.size(); i++) { auto &remap = remap_info[i]; - if (remap.index.IsValid() && !remap.child_remap_info.empty()) { + if (remap.index.IsValid() && remap.is_nested) { // nested remap - recurse auto &input_vector = input_vectors[remap.index.GetIndex()]; reference child_default = default_vector; @@ -86,6 +90,7 @@ void RemapChildVectors(const Vector &result, const vector> &in } if (!remap.index.IsValid() && remap.default_index.IsValid() && !remap.child_remap_info.empty()) { // nested default without a source - remap the fields of the default to the target type + // (a default without fields has none to remap and is referenced below, so is_nested is not used here) auto &defaults = StructVector::GetEntries(default_vector); auto &nested_default = defaults[remap.default_index.GetIndex()]; if (nested_default.GetType().id() == LogicalTypeId::STRUCT && @@ -419,6 +424,12 @@ struct RemapEntry { // add to the map at this level only if it does not yet exist auto result_entry = result.find(Identifier(default_target)); if (result_entry == result.end()) { + if (target_type.id() != LogicalTypeId::STRUCT) { + // the defaults of a LIST or MAP fill the entries of the source - without a source there are none + throw BinderException("Default value for %s is a struct, but the target type '%s' is not mapped " + "to a source - map it to a source or provide a default of the target type", + default_target, target_type.ToString()); + } result.emplace(default_target, std::move(remap)); result_entry = result.find(Identifier(default_target)); result_entry->second.child_remaps = make_uniq>(); @@ -426,12 +437,13 @@ struct RemapEntry { // the entry exists - add the default index result_entry->second.default_index = default_idx; } + if (!result_entry->second.child_remaps || !entry->second.child_map) { + // the field is mapped without a child mapping - a struct default would replace its source + throw BinderException("No child remaps found"); + } auto &child_types = StructType::GetChildTypes(default_type); for (idx_t child_idx = 0; child_idx < child_types.size(); child_idx++) { auto &child_default = child_types[child_idx]; - if (!result_entry->second.child_remaps || !entry->second.child_map) { - throw BinderException("No child remaps found"); - } HandleDefault(child_idx, child_default.first.GetIdentifierName(), child_default.second, *entry->second.child_map, *result_entry->second.child_remaps); } @@ -463,6 +475,7 @@ struct RemapEntry { info.default_index = entry->second.default_index; if (IsRemappable(child_type) && entry->second.child_remaps) { // type is nested and a mapping for it is given - recurse + info.is_nested = true; info.child_remap_info = ConstructMap(child_type, *entry->second.child_remaps); } result.push_back(std::move(info)); diff --git a/src/duckdb/src/function/table/system/duckdb_grammar_extensions.cpp b/src/duckdb/src/function/table/system/duckdb_grammar_extensions.cpp index a8efa87f1..41b3e072a 100644 --- a/src/duckdb/src/function/table/system/duckdb_grammar_extensions.cpp +++ b/src/duckdb/src/function/table/system/duckdb_grammar_extensions.cpp @@ -6,6 +6,7 @@ #include "duckdb/main/config.hpp" #include "duckdb/main/extension_callback_manager.hpp" #include "duckdb/main/settings.hpp" +#include "duckdb/parser/grammar_change.hpp" #include "duckdb/parser/grammar_extension.hpp" namespace duckdb { @@ -91,6 +92,94 @@ void DuckDBGrammarExtensionsFun::RegisterFunction(BuiltinFunctions &set) { DuckDBGrammarExtensionsBind, DuckDBGrammarExtensionsInit)); } +//===--------------------------------------------------------------------===// +// duckdb_grammar_changes +//===--------------------------------------------------------------------===// +//! The grammar changes of the grammar extensions active in this connection, in the order they are applied. This is +//! what a client that parses on its own needs to parse the same grammar: the definitions are data, while a change +//! with `has_code` also depends on a function that cannot be described. +struct GrammarChangeRow { + string extension; + idx_t position; + string type; + string rule_name; + string definition; + bool collapsible; + bool suppress_suggestions; + bool has_code; +}; + +struct DuckDBGrammarChangesData : public GlobalTableFunctionState { + vector rows; + idx_t offset = 0; +}; + +static unique_ptr DuckDBGrammarChangesBind(ClientContext &context, TableFunctionBindInput &input, + vector &return_types, vector &names) { + names.emplace_back("extension"); + return_types.emplace_back(LogicalType::VARCHAR); + names.emplace_back("position"); + return_types.emplace_back(LogicalType::BIGINT); + names.emplace_back("type"); + return_types.emplace_back(LogicalType::VARCHAR); + names.emplace_back("rule_name"); + return_types.emplace_back(LogicalType::VARCHAR); + names.emplace_back("definition"); + return_types.emplace_back(LogicalType::VARCHAR); + names.emplace_back("collapsible"); + return_types.emplace_back(LogicalType::BOOLEAN); + names.emplace_back("suppress_suggestions"); + return_types.emplace_back(LogicalType::BOOLEAN); + names.emplace_back("has_code"); + return_types.emplace_back(LogicalType::BOOLEAN); + return nullptr; +} + +static unique_ptr DuckDBGrammarChangesInit(ClientContext &context, + TableFunctionInitInput &input) { + auto result = make_uniq(); + auto &callback_manager = ExtensionCallbackManager::Get(context); + auto selection = EffectiveGrammarExtensions(context); + if (!selection) { + return std::move(result); + } + for (auto &name : *selection) { + auto extension = callback_manager.FindGrammarExtension(name); + if (!extension) { + continue; + } + idx_t position = 0; + for (auto &change : extension->GetChanges()) { + result->rows.push_back({extension->Name(), position++, change.TypeName(), change.RuleName(), + change.Definition(), change.Collapsible(), change.SuppressSuggestions(), + change.HasCode()}); + } + } + return std::move(result); +} + +static void DuckDBGrammarChangesFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { + auto &data = data_p.global_state->Cast(); + idx_t count = 0; + while (data.offset < data.rows.size() && count < STANDARD_VECTOR_SIZE) { + auto &row = data.rows[data.offset++]; + output.data[0].Append(Value(row.extension)); + output.data[1].Append(Value::BIGINT(NumericCast(row.position))); + output.data[2].Append(Value(row.type)); + output.data[3].Append(Value(row.rule_name)); + output.data[4].Append(Value(row.definition)); + output.data[5].Append(Value::BOOLEAN(row.collapsible)); + output.data[6].Append(Value::BOOLEAN(row.suppress_suggestions)); + output.data[7].Append(Value::BOOLEAN(row.has_code)); + count++; + } +} + +void DuckDBGrammarChangesFun::RegisterFunction(BuiltinFunctions &set) { + set.AddFunction(TableFunction("duckdb_grammar_changes", {}, DuckDBGrammarChangesFunction, DuckDBGrammarChangesBind, + DuckDBGrammarChangesInit)); +} + //===--------------------------------------------------------------------===// // add_grammar_extension / remove_grammar_extension //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/function/table/system_functions.cpp b/src/duckdb/src/function/table/system_functions.cpp index 9d0686d23..893402a4b 100644 --- a/src/duckdb/src/function/table/system_functions.cpp +++ b/src/duckdb/src/function/table/system_functions.cpp @@ -34,6 +34,7 @@ void BuiltinFunctions::RegisterSQLiteFunctions() { DuckDBDependenciesFun::RegisterFunction(*this); DuckDBDialectsFun::RegisterFunction(*this); DuckDBGrammarExtensionsFun::RegisterFunction(*this); + DuckDBGrammarChangesFun::RegisterFunction(*this); ActiveGrammarExtensionFun::RegisterFunction(*this); DuckDBExtensionsFun::RegisterFunction(*this); DuckDBExtensionRepositoriesFun::RegisterFunction(*this); diff --git a/src/duckdb/src/function/table/table_scan.cpp b/src/duckdb/src/function/table/table_scan.cpp index 4d5003f0c..f7e30da34 100644 --- a/src/duckdb/src/function/table/table_scan.cpp +++ b/src/duckdb/src/function/table/table_scan.cpp @@ -355,6 +355,8 @@ class DuckTableScanState : public TableScanGlobalState { duck_table(bind_data.table.Cast()), tx(DuckTransaction::Get(context, duck_table.catalog)), storage(duck_table.GetStorage()), total_rows(storage.GetTotalRows()), progress(MaxValue(1, context.db->NumberOfThreads())) { + // Persisted row groups can be smaller than the configured target size. + max_threads = MaxValue(max_threads, total_row_groups_to_scan); for (auto &counter : progress) { counter.store(0, std::memory_order_relaxed); } diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index 4adf25a93..ad91e0e73 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-alpha57181" +#define DUCKDB_PATCH_VERSION "0-alpha57291" #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-alpha57181" +#define DUCKDB_VERSION "v2.1.0-alpha57291" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "3b3e55925f" +#define DUCKDB_SOURCE_ID "94a1663a4d" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/include/duckdb/common/sorting/sort.hpp b/src/duckdb/src/include/duckdb/common/sorting/sort.hpp index cc5171c44..b22a2ae0d 100644 --- a/src/duckdb/src/include/duckdb/common/sorting/sort.hpp +++ b/src/duckdb/src/include/duckdb/common/sorting/sort.hpp @@ -106,6 +106,9 @@ class Sort { //===--------------------------------------------------------------------===// // Non-Standard Interface //===--------------------------------------------------------------------===// + //! Before the first Sink, lower the reservation to the estimated sorting size, capped at the default minimum + void SetExpectedSize(ClientContext &context, GlobalSinkState &gstate, idx_t count, idx_t variable_data_size) const; + SourceResultType MaterializeColumnData(ExecutionContext &context, OperatorSourceInput &input) const; unique_ptr GetColumnData(OperatorSourceInput &input) const; diff --git a/src/duckdb/src/include/duckdb/common/sorting/sort_key_prefix.hpp b/src/duckdb/src/include/duckdb/common/sorting/sort_key_prefix.hpp new file mode 100644 index 000000000..ab71a2654 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/sorting/sort_key_prefix.hpp @@ -0,0 +1,45 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/sorting/sort_key_prefix.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/assert.hpp" +#include "duckdb/common/typedefs.hpp" + +namespace duckdb { + +//! Temporarily reuse a range's shared inline word, restoring canonical keys on scope exit. +template +class SortKeyPrefixScope { +public: + SortKeyPrefixScope(const ITERATOR &begin_p, const ITERATOR &end_p) + : begin(begin_p), end(end_p), original_part0((*begin).part0) { + } + + SortKeyPrefixScope(const SortKeyPrefixScope &) = delete; + SortKeyPrefixScope &operator=(const SortKeyPrefixScope &) = delete; + + ~SortKeyPrefixScope() { + for (auto it = begin; it != end; ++it) { + (*it).part0 = original_part0; + } + } + + template + void Set(SORT_KEY &key, uint64_t word) const { + D_ASSERT(key.part0 == original_part0); + key.part0 = word; + } + +private: + ITERATOR begin; + ITERATOR end; + const uint64_t original_part0; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/thread.hpp b/src/duckdb/src/include/duckdb/common/thread.hpp index ab8884458..4cf68c9d5 100644 --- a/src/duckdb/src/include/duckdb/common/thread.hpp +++ b/src/duckdb/src/include/duckdb/common/thread.hpp @@ -20,7 +20,12 @@ using thread_id = std::thread::id; } // namespace duckdb #else +#include "duckdb/common/typedefs.hpp" +#include "duckdb/common/string.hpp" + +namespace duckdb { using thread_id = uint64_t; +} // namespace duckdb #endif #include "duckdb/common/optional_ptr.hpp" diff --git a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp index 60b076b5f..6f67b787f 100644 --- a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp +++ b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp @@ -414,10 +414,6 @@ class JoinHashTable { D_ASSERT(IsLayoutFinalized()); return *data_collection; } - //! Perform a full scan of a build column, filling the provided addresses vector and result vector. - //! Returns the number of tuples found (can be smaller than the vector capacity). - idx_t ScanKeyColumn(Vector &addresses, Vector &result, idx_t column_index) const; - bool NullValuesAreEqual(idx_t col_idx) const { return null_values_are_equal[col_idx]; } diff --git a/src/duckdb/src/include/duckdb/execution/radix_ht_adaptivity.hpp b/src/duckdb/src/include/duckdb/execution/radix_ht_adaptivity.hpp index 3b988b579..bc9120215 100644 --- a/src/duckdb/src/include/duckdb/execution/radix_ht_adaptivity.hpp +++ b/src/duckdb/src/include/duckdb/execution/radix_ht_adaptivity.hpp @@ -44,8 +44,8 @@ class RadixHTAdaptivity { static constexpr idx_t LOOKUP_HISTORY_DECAY_THRESHOLD_ROWS = 128 * 1024; static constexpr idx_t MAX_LOOKUP_RETRY_ROWS = 1024 * 1024; static constexpr idx_t LOOKUP_RETRY_MATERIALIZED_ROWS_DIVISOR = 8; - static constexpr double GROWTH_DUPLICATE_BYTES_FACTOR = 4.0; - static constexpr double MINIMUM_SMALL_TABLE_REDUCTION = 0.05; + static constexpr double GROWTH_DUPLICATE_BYTES_FACTOR = 1.0; + static constexpr double MINIMUM_LOOKUP_REDUCTION = 0.05; private: //! Decayed observations from completed lookup-enabled cycles diff --git a/src/duckdb/src/include/duckdb/function/aggregate_state_layout.hpp b/src/duckdb/src/include/duckdb/function/aggregate_state_layout.hpp index 6a5793255..cd29acb51 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate_state_layout.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate_state_layout.hpp @@ -255,6 +255,9 @@ struct AggregateStateField { //! aggregate's empty-group finalize (e.g. count -> 0) instead of short-circuiting to NULL on a NULL state. bool list_empty_as_empty = false; + //! Whether the described native field consists entirely of fixed-size values. + bool IsFixedSize(const LogicalType &type) const; + //! The alignment of this field when placed as a struct member, mirroring the C++ struct layout rules. //! For OPTIONAL_VALUE the alignment is that of the wrapped value - the trailing is_set bool does not affect it. idx_t GetAlignment() const { diff --git a/src/duckdb/src/include/duckdb/function/table/system_functions.hpp b/src/duckdb/src/include/duckdb/function/table/system_functions.hpp index 03a1e8a16..4d1b25732 100644 --- a/src/duckdb/src/include/duckdb/function/table/system_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/table/system_functions.hpp @@ -94,6 +94,10 @@ struct DuckDBGrammarExtensionsFun { static void RegisterFunction(BuiltinFunctions &set); }; +struct DuckDBGrammarChangesFun { + static void RegisterFunction(BuiltinFunctions &set); +}; + struct ActiveGrammarExtensionFun { static void RegisterFunction(BuiltinFunctions &set); }; 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 7b0844662..5813725b5 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 @@ -1540,8 +1540,30 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_set_schema) (duckdb_v2_scalar_function_handle function, const char *schema, idx_t schema_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_create_secret) + (duckdb_v2_connection_handle conn, duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, + duckdb_v2_secret_handle *created, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_get_secret_by_name) + (duckdb_v2_connection_handle conn, const char *name, idx_t name_length, duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_lookup_secret) + (duckdb_v2_connection_handle conn, const char *path, idx_t path_length, const char *type, idx_t type_length, + duckdb_v2_secret_handle *secret, int64_t *score, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_register_secret_function) + (duckdb_v2_connection_handle conn, duckdb_v2_secret_function_handle function, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_create_secret) + (duckdb_v2_context_handle ctx, duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, + duckdb_v2_secret_handle *created, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_context_get_object_cache) (duckdb_v2_context_handle context, duckdb_v2_object_cache_handle *cache, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_get_secret_by_name) + (duckdb_v2_context_handle ctx, const char *name, idx_t name_length, duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_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_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_object_cache_delete) @@ -1560,6 +1582,57 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_object_cache_put) (duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, const char *key, idx_t key_length, duckdb_v2_opaque *data, idx_t size_bytes, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_add_redacted_key) + (duckdb_v2_secret_handle secret, const char *key, idx_t key_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_add_scope) + (duckdb_v2_secret_handle secret, const char *scope, idx_t scope_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_secret_clear_scope)(duckdb_v2_secret_handle secret, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_create) + (duckdb_v2_factory_handle factory, duckdb_v2_secret_handle *secret, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_secret_destroy)(duckdb_v2_secret_handle *secret); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_add_named_parameter) + (duckdb_v2_secret_function_handle function, const char *name, idx_t name_length, duckdb_v2_logical_type_handle type, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_create) + (duckdb_v2_factory_handle factory, duckdb_v2_secret_function_handle *function, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_secret_function_destroy)(duckdb_v2_secret_function_handle *function); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_set_create_callback) + (duckdb_v2_secret_function_handle function, duckdb_v2_secret_create_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_set_default) + (duckdb_v2_secret_function_handle function, bool is_default, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_set_provider) + (duckdb_v2_secret_function_handle function, const char *provider, idx_t provider_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_set_type) + (duckdb_v2_secret_function_handle function, const char *type, idx_t type_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_set_user_data) + (duckdb_v2_secret_function_handle function, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_key) + (duckdb_v2_secret_handle secret, idx_t index, const char **key, idx_t *key_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_key_count) + (duckdb_v2_secret_handle secret, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_property) + (duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_PROPERTY property, const char **value, idx_t *value_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_scope) + (duckdb_v2_secret_handle secret, idx_t index, const char **scope, idx_t *scope_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_scope_count) + (duckdb_v2_secret_handle secret, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_value) + (duckdb_v2_secret_handle secret, const char *key, idx_t key_length, duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_is_key_redacted) + (duckdb_v2_secret_handle secret, const char *key, idx_t key_length, bool *redacted, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_set_property) + (duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_PROPERTY property, const char *value, idx_t value_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_set_value) + (duckdb_v2_secret_handle secret, const char *key, idx_t key_length, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_to_string_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_to_string_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -2274,7 +2347,15 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_scalar_function_get_generic_property = duckdb_v2_scalar_function_get_generic_property; result.duckdb_v2_scalar_function_set_generic_property = duckdb_v2_scalar_function_set_generic_property; result.duckdb_v2_scalar_function_set_schema = duckdb_v2_scalar_function_set_schema; + result.duckdb_v2_connection_create_secret = duckdb_v2_connection_create_secret; + result.duckdb_v2_connection_get_secret_by_name = duckdb_v2_connection_get_secret_by_name; + result.duckdb_v2_connection_lookup_secret = duckdb_v2_connection_lookup_secret; + result.duckdb_v2_connection_register_secret_function = duckdb_v2_connection_register_secret_function; + result.duckdb_v2_context_create_secret = duckdb_v2_context_create_secret; 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_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_object_cache_delete = duckdb_v2_object_cache_delete; result.duckdb_v2_object_cache_entry_destroy = duckdb_v2_object_cache_entry_destroy; @@ -2282,6 +2363,28 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_object_cache_get = duckdb_v2_object_cache_get; result.duckdb_v2_object_cache_get_or_create = duckdb_v2_object_cache_get_or_create; result.duckdb_v2_object_cache_put = duckdb_v2_object_cache_put; + result.duckdb_v2_secret_add_redacted_key = duckdb_v2_secret_add_redacted_key; + result.duckdb_v2_secret_add_scope = duckdb_v2_secret_add_scope; + result.duckdb_v2_secret_clear_scope = duckdb_v2_secret_clear_scope; + result.duckdb_v2_secret_create = duckdb_v2_secret_create; + result.duckdb_v2_secret_destroy = duckdb_v2_secret_destroy; + result.duckdb_v2_secret_function_add_named_parameter = duckdb_v2_secret_function_add_named_parameter; + result.duckdb_v2_secret_function_create = duckdb_v2_secret_function_create; + result.duckdb_v2_secret_function_destroy = duckdb_v2_secret_function_destroy; + result.duckdb_v2_secret_function_set_create_callback = duckdb_v2_secret_function_set_create_callback; + result.duckdb_v2_secret_function_set_default = duckdb_v2_secret_function_set_default; + result.duckdb_v2_secret_function_set_provider = duckdb_v2_secret_function_set_provider; + result.duckdb_v2_secret_function_set_type = duckdb_v2_secret_function_set_type; + result.duckdb_v2_secret_function_set_user_data = duckdb_v2_secret_function_set_user_data; + result.duckdb_v2_secret_get_key = duckdb_v2_secret_get_key; + result.duckdb_v2_secret_get_key_count = duckdb_v2_secret_get_key_count; + result.duckdb_v2_secret_get_property = duckdb_v2_secret_get_property; + result.duckdb_v2_secret_get_scope = duckdb_v2_secret_get_scope; + result.duckdb_v2_secret_get_scope_count = duckdb_v2_secret_get_scope_count; + result.duckdb_v2_secret_get_value = duckdb_v2_secret_get_value; + result.duckdb_v2_secret_is_key_redacted = duckdb_v2_secret_is_key_redacted; + result.duckdb_v2_secret_set_property = duckdb_v2_secret_set_property; + result.duckdb_v2_secret_set_value = duckdb_v2_secret_set_value; result.duckdb_v2_table_function_set_to_string_callback = duckdb_v2_table_function_set_to_string_callback; result.duckdb_v2_table_function_to_string_get_bind_data = duckdb_v2_table_function_to_string_get_bind_data; result.duckdb_v2_table_function_to_string_get_user_data = duckdb_v2_table_function_to_string_get_user_data; diff --git a/src/duckdb/src/include/duckdb/main/secret/secret.hpp b/src/duckdb/src/include/duckdb/main/secret/secret.hpp index e9fc28dc7..08449afa8 100644 --- a/src/duckdb/src/include/duckdb/main/secret/secret.hpp +++ b/src/duckdb/src/include/duckdb/main/secret/secret.hpp @@ -27,6 +27,11 @@ class FileOpener; enum class SecretPersistType : uint8_t { DEFAULT, TEMPORARY, PERSISTENT, TRANSACTION }; //! Input passed to a CreateSecretFunction +//! State a CreateSecretFunction carries along, handed to its function through the CreateSecretInput +struct CreateSecretFunctionInfo { + virtual ~CreateSecretFunctionInfo() = default; +}; + struct CreateSecretInput { //! type Identifier type; @@ -44,6 +49,8 @@ struct CreateSecretInput { OnCreateConflict on_conflict; //! lifetime of the secret SecretPersistType persist_type; + //! the info of the function creating the secret, if it has any + optional_ptr function_info; }; typedef unique_ptr (*secret_deserializer_t)(Deserializer &deserializer, BaseSecret base_secret); @@ -56,6 +63,7 @@ class CreateSecretFunction { Identifier provider; create_secret_function_t function; named_parameter_type_map_t named_parameters; + shared_ptr info; }; //! CreateSecretFunctionsSet contains multiple functions of a single type, identified by the provider. The provider diff --git a/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp b/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp index 50ee83f70..1aa69542a 100644 --- a/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/secret/secret_manager.hpp @@ -121,8 +121,13 @@ class SecretManager { DUCKDB_API void RegisterSecretType(SecretType &type); //! Lookup a SecretType DUCKDB_API SecretType LookupType(const string &type); + //! Lookup a SecretType, autoloading the extension that defines it; returns false if there is none + DUCKDB_API bool TryLookupType(const Identifier &type, SecretType &type_out); //! Register a Secret Function i.e. a secret provider for a secret type DUCKDB_API void RegisterSecretFunction(CreateSecretFunction function, OnCreateConflict on_conflict); + //! Atomically register a secret function and, if it does not exist yet, its type. Throws if the provider exists, + //! or if the type exists and new_type names a default provider. + DUCKDB_API void RegisterSecretFunctionAndType(CreateSecretFunction function, SecretType &new_type); //! Register a secret by providing a secret manually DUCKDB_API unique_ptr RegisterSecret(CatalogTransaction transaction, unique_ptr secret, OnCreateConflict on_conflict, @@ -132,6 +137,12 @@ class SecretManager { //! The Bind for create secret is done by the secret manager DUCKDB_API BoundStatement BindCreateSecret(Context &context, CatalogTransaction transaction, CreateSecretInput &info); + //! Checks the options of a create secret input against its provider's named parameters and casts them to the + //! declared types, as CREATE SECRET does + DUCKDB_API void BindCreateSecretOptions(Context &context, CatalogTransaction transaction, CreateSecretInput &info); + //! The storage a secret with this persist type and (optional) storage is registered in; resolves a default + //! persist type in place + DUCKDB_API string ResolveSecretStorage(SecretPersistType &persist_type, const Identifier &storage); //! Lookup the best matching secret by matching the secret scopes to the path DUCKDB_API SecretMatch LookupSecret(CatalogTransaction transaction, const string &path, const string &type); //! Get a secret by name, optionally from a specific storage diff --git a/src/duckdb/src/include/duckdb/parser/grammar_change.hpp b/src/duckdb/src/include/duckdb/parser/grammar_change.hpp index 298c2820e..194c7f0cc 100644 --- a/src/duckdb/src/include/duckdb/parser/grammar_change.hpp +++ b/src/duckdb/src/include/duckdb/parser/grammar_change.hpp @@ -56,6 +56,21 @@ class GrammarChange { const string &Definition() const { return definition; } + //! See ParsedGrammar::SetTransformProcess for the meaning of collapsible + bool Collapsible() const { + return collapsible; + } + //! See ParsedGrammar::AddRule for the meaning of suppress_suggestions + bool SuppressSuggestions() const { + return suppress_suggestions; + } + //! Whether the change depends on a function (a cursor lookup or a terminal rule matcher), and so cannot be + //! rebuilt from its type, rule name and definition alone + bool HasCode() const { + return find_cursor || matcher_factory; + } + //! The change type as text, as listed by duckdb_grammar_changes() + DUCKDB_API string TypeName() const; public: void Apply(ParsedGrammar &grammar) const; diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp index 71f227652..51babc238 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp @@ -536,6 +536,7 @@ static constexpr idx_t PARSER_ARENA_INITIAL_CAPACITY = 8 * ArenaAllocator::ARENA class ParseResultAllocator { public: ParseResultAllocator(); + explicit ParseResultAllocator(Allocator &allocator); ~ParseResultAllocator(); template diff --git a/src/duckdb/src/include/duckdb/parser/peg/transformer/parse_result.hpp b/src/duckdb/src/include/duckdb/parser/peg/transformer/parse_result.hpp index d03a1a86f..53e390926 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/transformer/parse_result.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/transformer/parse_result.hpp @@ -496,15 +496,105 @@ class StringLiteralParseResult : public ParseResult { explicit StringLiteralParseResult(string string_p, SpecialStringCharacter string_type_p, optional_idx offset, optional_idx length = optional_idx()) : ParseResult(TYPE, offset, length), result(std::move(string_p)), string_type(string_type_p) { + if (string_type == SpecialStringCharacter::ESCAPE_STRING) { + result = DecodeEscapeString(); + } } string GetRawString() const { return result; } + string DecodeEscapeString() const { + string escaped_result; + escaped_result.reserve(result.size()); + + for (size_t i = 0; i < result.size(); ++i) { + if (result[i] == '\\' && i + 1 < result.size()) { + i++; + switch (result[i]) { + case 'b': + escaped_result += '\b'; + break; + case 'f': + escaped_result += '\f'; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': { + size_t oct_start = i; + size_t oct_end = oct_start + 1; + while (oct_end < result.size() && oct_end - oct_start < 3 && result[oct_end] >= '0' && + result[oct_end] <= '7') { + oct_end++; + } + string oct_str = result.substr(oct_start, oct_end - oct_start); + escaped_result += static_cast(strtoul(oct_str.c_str(), nullptr, 8)); + i = oct_end - 1; + break; + } + case 'x': { + size_t hex_start = i + 1; + size_t hex_end = hex_start; + while (hex_end < result.size() && hex_end - hex_start < 2 && + StringUtil::CharacterIsHex(result[hex_end])) { + hex_end++; + } + if (hex_end > hex_start) { + string hex_str = result.substr(hex_start, hex_end - hex_start); + escaped_result += static_cast(strtoul(hex_str.c_str(), nullptr, 16)); + i = hex_end - 1; + } else { + escaped_result += 'x'; + } + break; + } + case 'n': + escaped_result += '\n'; + break; + case 't': + escaped_result += '\t'; + break; + case 'r': + escaped_result += '\r'; + break; + case '\\': + escaped_result += '\\'; + break; + case '\'': + escaped_result += '\''; + break; + default: + escaped_result += result[i]; + break; + } + } else { + escaped_result += result[i]; + } + } + if (escaped_result.find('\0') != string::npos) { + throw ParserException("Null character not permitted in escape string literal"); + } + UnicodeInvalidReason reason; + size_t pos; + auto utf_validity = Utf8Proc::Analyze(escaped_result.c_str(), escaped_result.size(), &reason, &pos); + if (utf_validity == UnicodeType::INVALID) { + const char *reason_str = + reason == UnicodeInvalidReason::BYTE_MISMATCH ? "byte mismatch" : "invalid unicode codepoint"; + throw ParserException("Invalid UTF-8 in escape string literal at byte offset %d: %s", pos, reason_str); + } + return escaped_result; + } + virtual unique_ptr ToExpression() { switch (string_type) { case SpecialStringCharacter::STANDARD: + case SpecialStringCharacter::ESCAPE_STRING: return ConstantExpression::String(result); case SpecialStringCharacter::NATIONAL_STRING: return make_uniq(LogicalType::VARCHAR, ConstantExpression::String(result)); @@ -513,90 +603,6 @@ class StringLiteralParseResult : public ParseResult { return ConstantExpression::Hex(result); case SpecialStringCharacter::BIT_STRING: return ConstantExpression::Bit(result); - case SpecialStringCharacter::ESCAPE_STRING: - string escaped_result; - escaped_result.reserve(result.size()); - - for (size_t i = 0; i < result.size(); ++i) { - if (result[i] == '\\' && i + 1 < result.size()) { - i++; - switch (result[i]) { - case 'b': - escaped_result += '\b'; - break; - case 'f': - escaped_result += '\f'; - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': { - size_t oct_start = i; - size_t oct_end = oct_start + 1; - while (oct_end < result.size() && oct_end - oct_start < 3 && result[oct_end] >= '0' && - result[oct_end] <= '7') { - oct_end++; - } - string oct_str = result.substr(oct_start, oct_end - oct_start); - escaped_result += static_cast(strtoul(oct_str.c_str(), nullptr, 8)); - i = oct_end - 1; - break; - } - case 'x': { - size_t hex_start = i + 1; - size_t hex_end = hex_start; - while (hex_end < result.size() && hex_end - hex_start < 2 && - StringUtil::CharacterIsHex(result[hex_end])) { - hex_end++; - } - if (hex_end > hex_start) { - string hex_str = result.substr(hex_start, hex_end - hex_start); - escaped_result += static_cast(strtoul(hex_str.c_str(), nullptr, 16)); - i = hex_end - 1; - } else { - escaped_result += 'x'; - } - break; - } - case 'n': - escaped_result += '\n'; - break; - case 't': - escaped_result += '\t'; - break; - case 'r': - escaped_result += '\r'; - break; - case '\\': - escaped_result += '\\'; - break; - case '\'': - escaped_result += '\''; - break; - default: - escaped_result += result[i]; - break; - } - } else { - escaped_result += result[i]; - } - } - if (escaped_result.find('\0') != string::npos) { - throw ParserException("Null character not permitted in escape string literal"); - } - UnicodeInvalidReason reason; - size_t pos; - auto utf_validity = Utf8Proc::Analyze(escaped_result.c_str(), escaped_result.size(), &reason, &pos); - if (utf_validity == UnicodeType::INVALID) { - const char *reason_str = - reason == UnicodeInvalidReason::BYTE_MISMATCH ? "byte mismatch" : "invalid unicode codepoint"; - throw ParserException("Invalid UTF-8 in escape string literal at byte offset %d: %s", pos, reason_str); - } - return ConstantExpression::String(escaped_result); } return ConstantExpression::String(result); } diff --git a/src/duckdb/src/include/duckdb/storage/table/append_state.hpp b/src/duckdb/src/include/duckdb/storage/table/append_state.hpp index 7ae02e1e7..ae9956c9c 100644 --- a/src/duckdb/src/include/duckdb/storage/table/append_state.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/append_state.hpp @@ -131,6 +131,8 @@ struct LocalAppendState { //! The context of the operation that appends (the local storage can outlive the connection that created it) optional_ptr context; unique_ptr constraint_state; + //! Held from InitializeAppend until FinalizeAppend (or until the state is destroyed) + unique_ptr append_lock; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp b/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp index 3b16e70f2..e1f556a16 100644 --- a/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp +++ b/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp @@ -126,6 +126,8 @@ class DuckTransaction : public Transaction { UndoBuffer undo_buffer; //! The set of uncommitted appends for the transaction unique_ptr storage; + //! Guards checkpoint_lock and vacuum_lock (statements of the transaction can run concurrently) + mutex lock_keys_lock; //! Lock that prevents checkpoints from starting unique_ptr checkpoint_lock; //! Lock that prevents vacuums from starting diff --git a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp index 4ab935672..efb065cb7 100644 --- a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp +++ b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp @@ -10,6 +10,7 @@ #include "duckdb/storage/table/table_index_list.hpp" #include "duckdb/storage/optimistic_data_writer.hpp" +#include "duckdb/storage/storage_lock.hpp" #include "duckdb/common/error_data.hpp" #include "duckdb/common/query_context.hpp" #include "duckdb/common/reference_map.hpp" @@ -79,6 +80,9 @@ class LocalTableStorage : public enable_shared_from_this { //! Whether or not the storage was dropped bool is_dropped = false; + //! Serializes the appends and merges into the primary collection + StorageLock append_lock; + public: //! Initialize a scan; the context of the scanning query is used for pushed down casts and zonemap checks void InitializeScan(const QueryContext &context, CollectionScanState &state, diff --git a/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp b/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp index 463f641c6..62a86fd48 100644 --- a/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp +++ b/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp @@ -70,6 +70,7 @@ class MetaTransaction { bool IsReadOnly() const; void ModifyDatabase(ClientContext &context, AttachedDatabase &db, DatabaseModificationType modification); optional_ptr ModifiedDatabase() { + lock_guard guard(modification_lock); return modified_database; } const vector> &OpenedTransactions() const { @@ -89,6 +90,8 @@ class MetaTransaction { reference_map_t transactions; //! The set of referenced databases in invocation order. vector> all_transactions; + //! Guards modified_database and the read/write state of the transactions (statements can modify concurrently) + mutex modification_lock; //! The database we are modifying. We can only modify one database per meta transaction. optional_ptr modified_database; //! Whether the meta transaction is marked as read only. diff --git a/src/duckdb/src/include/duckdb/transaction/transaction.hpp b/src/duckdb/src/include/duckdb/transaction/transaction.hpp index 292732ca7..ce59557a5 100644 --- a/src/duckdb/src/include/duckdb/transaction/transaction.hpp +++ b/src/duckdb/src/include/duckdb/transaction/transaction.hpp @@ -80,7 +80,7 @@ class Transaction { } private: - bool is_read_only; + atomic is_read_only; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index bffcd9260..098058aee 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -1614,8 +1614,30 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_set_schema) (duckdb_v2_scalar_function_handle function, const char *schema, idx_t schema_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_create_secret) + (duckdb_v2_connection_handle conn, duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, + duckdb_v2_secret_handle *created, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_get_secret_by_name) + (duckdb_v2_connection_handle conn, const char *name, idx_t name_length, duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_lookup_secret) + (duckdb_v2_connection_handle conn, const char *path, idx_t path_length, const char *type, idx_t type_length, + duckdb_v2_secret_handle *secret, int64_t *score, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_connection_register_secret_function) + (duckdb_v2_connection_handle conn, duckdb_v2_secret_function_handle function, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_create_secret) + (duckdb_v2_context_handle ctx, duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, + duckdb_v2_secret_handle *created, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_context_get_object_cache) (duckdb_v2_context_handle context, duckdb_v2_object_cache_handle *cache, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_get_secret_by_name) + (duckdb_v2_context_handle ctx, const char *name, idx_t name_length, duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_context_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_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_object_cache_delete) @@ -1634,6 +1656,57 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_object_cache_put) (duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, const char *key, idx_t key_length, duckdb_v2_opaque *data, idx_t size_bytes, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_add_redacted_key) + (duckdb_v2_secret_handle secret, const char *key, idx_t key_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_add_scope) + (duckdb_v2_secret_handle secret, const char *scope, idx_t scope_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_secret_clear_scope)(duckdb_v2_secret_handle secret, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_create) + (duckdb_v2_factory_handle factory, duckdb_v2_secret_handle *secret, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_secret_destroy)(duckdb_v2_secret_handle *secret); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_add_named_parameter) + (duckdb_v2_secret_function_handle function, const char *name, idx_t name_length, duckdb_v2_logical_type_handle type, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_create) + (duckdb_v2_factory_handle factory, duckdb_v2_secret_function_handle *function, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_secret_function_destroy)(duckdb_v2_secret_function_handle *function); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_set_create_callback) + (duckdb_v2_secret_function_handle function, duckdb_v2_secret_create_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_set_default) + (duckdb_v2_secret_function_handle function, bool is_default, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_set_provider) + (duckdb_v2_secret_function_handle function, const char *provider, idx_t provider_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_set_type) + (duckdb_v2_secret_function_handle function, const char *type, idx_t type_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_function_set_user_data) + (duckdb_v2_secret_function_handle function, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_key) + (duckdb_v2_secret_handle secret, idx_t index, const char **key, idx_t *key_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_key_count) + (duckdb_v2_secret_handle secret, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_property) + (duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_PROPERTY property, const char **value, idx_t *value_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_scope) + (duckdb_v2_secret_handle secret, idx_t index, const char **scope, idx_t *scope_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_scope_count) + (duckdb_v2_secret_handle secret, idx_t *count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_get_value) + (duckdb_v2_secret_handle secret, const char *key, idx_t key_length, duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_is_key_redacted) + (duckdb_v2_secret_handle secret, const char *key, idx_t key_length, bool *redacted, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_set_property) + (duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_PROPERTY property, const char *value, idx_t value_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_secret_set_value) + (duckdb_v2_secret_handle secret, const char *key, idx_t key_length, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_to_string_callback) (duckdb_v2_table_function_handle function, duckdb_v2_table_function_to_string_callback_fn callback, duckdb_v2_error_info_handle *err); @@ -3720,9 +3793,33 @@ typedef struct { #define duckdb_v2_scalar_function_set_schema duckdb_ext_api.duckdb_v2_scalar_function_set_schema #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_connection_create_secret duckdb_ext_api.duckdb_v2_connection_create_secret +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_connection_get_secret_by_name duckdb_ext_api.duckdb_v2_connection_get_secret_by_name +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_connection_lookup_secret duckdb_ext_api.duckdb_v2_connection_lookup_secret +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_connection_register_secret_function duckdb_ext_api.duckdb_v2_connection_register_secret_function +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_create_secret duckdb_ext_api.duckdb_v2_context_create_secret +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_context_get_object_cache duckdb_ext_api.duckdb_v2_context_get_object_cache #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_get_secret_by_name duckdb_ext_api.duckdb_v2_context_get_secret_by_name +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_context_lookup_secret duckdb_ext_api.duckdb_v2_context_lookup_secret +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_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 @@ -3744,6 +3841,72 @@ typedef struct { #define duckdb_v2_object_cache_put duckdb_ext_api.duckdb_v2_object_cache_put #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_add_redacted_key duckdb_ext_api.duckdb_v2_secret_add_redacted_key +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_add_scope duckdb_ext_api.duckdb_v2_secret_add_scope +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_clear_scope duckdb_ext_api.duckdb_v2_secret_clear_scope +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_create duckdb_ext_api.duckdb_v2_secret_create +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_destroy duckdb_ext_api.duckdb_v2_secret_destroy +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_function_add_named_parameter duckdb_ext_api.duckdb_v2_secret_function_add_named_parameter +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_function_create duckdb_ext_api.duckdb_v2_secret_function_create +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_function_destroy duckdb_ext_api.duckdb_v2_secret_function_destroy +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_function_set_create_callback duckdb_ext_api.duckdb_v2_secret_function_set_create_callback +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_function_set_default duckdb_ext_api.duckdb_v2_secret_function_set_default +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_function_set_provider duckdb_ext_api.duckdb_v2_secret_function_set_provider +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_function_set_type duckdb_ext_api.duckdb_v2_secret_function_set_type +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_function_set_user_data duckdb_ext_api.duckdb_v2_secret_function_set_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_get_key duckdb_ext_api.duckdb_v2_secret_get_key +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_get_key_count duckdb_ext_api.duckdb_v2_secret_get_key_count +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_get_property duckdb_ext_api.duckdb_v2_secret_get_property +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_get_scope duckdb_ext_api.duckdb_v2_secret_get_scope +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_get_scope_count duckdb_ext_api.duckdb_v2_secret_get_scope_count +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_get_value duckdb_ext_api.duckdb_v2_secret_get_value +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_is_key_redacted duckdb_ext_api.duckdb_v2_secret_is_key_redacted +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_set_property duckdb_ext_api.duckdb_v2_secret_set_property +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_secret_set_value duckdb_ext_api.duckdb_v2_secret_set_value +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_set_to_string_callback duckdb_ext_api.duckdb_v2_table_function_set_to_string_callback #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index e3b53641c..0ee70cdf1 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -5143,6 +5143,825 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_schema_destroy(duckdb_v2_schema_handle *s /* --- Struct definitions for schema --- */ +/* ============================================================================ + * MODULE: secret + * ============================================================================ */ + +/* --- Enums for secret --- */ + +/*! + * A string property of a secret, next to its keys. Set with `duckdb_v2_secret_set_property()` and read with + * `duckdb_v2_secret_get_property()`. + */ +typedef enum DUCKDB_V2_SECRET_PROPERTY { + //! The secret type, e.g. `s3`. + DUCKDB_V2_SECRET_PROPERTY_TYPE = 0, + + //! The provider the secret is created with, e.g. `config`. + DUCKDB_V2_SECRET_PROPERTY_PROVIDER = 1, + + /*! + * The name of the secret. A secret created without one is named `__default_`, as by `CREATE SECRET`; only a + * secret built with `duckdb_v2_secret_create()` and not named yet reads back empty. + */ + DUCKDB_V2_SECRET_PROPERTY_NAME = 2, + + //! The name of the storage the secret lives in, e.g. `memory` or `local_file`. Empty when DuckDB chooses. + DUCKDB_V2_SECRET_PROPERTY_STORAGE = 3, + + /*! + * Where the secret lives, as one of `default` (DuckDB chooses, following the secret settings), `temporary` (in + * memory for the lifetime of the instance), `persistent` (written to disk) or `transaction` (in memory for the + * lifetime of the current transaction, for credentials a catalog hands out with a query). Matched + * case-insensitively; read back in lower case. + */ + DUCKDB_V2_SECRET_PROPERTY_PERSIST_TYPE = 4, + DUCKDB_V2_SECRET_PROPERTY_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_SECRET_PROPERTY; + +//! What creating a secret does when a secret of the same name already exists. +typedef enum DUCKDB_V2_SECRET_ON_CONFLICT { + //! Fail, as a plain `CREATE SECRET` does. + DUCKDB_V2_SECRET_ON_CONFLICT_ERROR = 0, + + //! Keep the existing secret and succeed, as `CREATE SECRET IF NOT EXISTS` does. + DUCKDB_V2_SECRET_ON_CONFLICT_IGNORE = 1, + + //! Replace the existing secret, as `CREATE OR REPLACE SECRET` does. + DUCKDB_V2_SECRET_ON_CONFLICT_REPLACE = 2, + DUCKDB_V2_SECRET_ON_CONFLICT_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_SECRET_ON_CONFLICT; + +/* --- Struct forward declarations for secret --- */ + +/* --- Types for secret --- */ + +/*! + * An owned opaque handle to a secret function being built: one provider of a secret type. Created with + * `duckdb_v2_secret_function_create()`, configured with the setters (e.g. `duckdb_v2_secret_function_set_provider()`, + * `duckdb_v2_secret_function_add_named_parameter()`, `duckdb_v2_secret_function_set_create_callback()`), made available + * with `duckdb_v2_connection_register_secret_function()` or `duckdb_v2_extension_register_secret_function()`, and + * destroyed with `duckdb_v2_secret_function_destroy()`. + */ +typedef struct _duckdb_v2_secret_function { + void *internal_ptr; +} * duckdb_v2_secret_function_handle; + +/*! + * A handle to a key/value secret. Owned when built with `duckdb_v2_secret_create()` or returned by + * `duckdb_v2_context_lookup_secret()`, `duckdb_v2_context_get_secret_by_name()`, `duckdb_v2_context_create_secret()` or + * their `connection_*` equivalents (`duckdb_v2_connection_lookup_secret()`, + * `duckdb_v2_connection_get_secret_by_name()`, `duckdb_v2_connection_create_secret()`): the caller destroys it with + * `duckdb_v2_secret_destroy()` and may change it with the setters, which never affects a stored secret. Borrowed when + * received by a create callback, valid only for the duration of the call: the `input` is read-only, describing the + * `CREATE SECRET` statement with its options as keys, and the `output` is the secret to fill, with its properties and + * scope already set from the statement. + */ +typedef struct _duckdb_v2_secret { + void *internal_ptr; +} * duckdb_v2_secret_handle; + +/* --- Constants for secret --- */ + +/* --- Function pointer typedefs for secret --- */ + +typedef void (*duckdb_v2_secret_create_callback_fn)(duckdb_v2_secret_handle input, duckdb_v2_secret_handle output, + void *user_data, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +/* --- Functions for secret --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a new secret function through a factory. + * + * The function starts out empty: configure it with the setters, then make it available with + * `duckdb_v2_connection_register_secret_function()` or `duckdb_v2_extension_register_secret_function()`. The caller + * owns the returned handle and must destroy it with `duckdb_v2_secret_function_destroy()`, also after registration. + * + * The function can only be registered on the instance the factory belongs to. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to create the secret function through. + * @param function On success, receives the newly created secret function. Owned by the caller. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_secret_function_handle *function, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the secret type the function creates secrets of, as `CREATE SECRET (TYPE ...)` and + * `duckdb_v2_context_lookup_secret()` name it. + * + * The name is borrowed and copied. Matched case-insensitively. A type must be set before registration. + * + * history: + * - unstable: v2.0.0 + * + * @param function The secret function to set the type of. + * @param type The name of the secret type. + * @param type_length The length of `type` in bytes. `type` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_function_set_type(duckdb_v2_secret_function_handle function, + const char *type, idx_t type_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the provider the function implements, as `CREATE SECRET (TYPE ..., PROVIDER )` names it. Common + * providers are `config`, which builds the secret from the named parameters alone, and `credential_chain`, which looks + * the values up in the environment. + * + * The provider is borrowed and copied. Matched case-insensitively. A provider must be set before registration. + * + * history: + * - unstable: v2.0.0 + * + * @param function The secret function to set the provider of. + * @param provider The provider to set. + * @param provider_length The length of `provider` in bytes. `provider` must be valid UTF-8, need not be + * null-terminated, and may be NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_function_set_provider(duckdb_v2_secret_function_handle function, + const char *provider, idx_t provider_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets whether the function is the default provider of its type: the one `CREATE SECRET (TYPE )` uses when the + * statement names no provider. Defaults to false. + * + * A type without a default provider requires every statement to name its provider. Only the function that defines the + * type, the first one registered for it, can be the default: registering a later function of an existing type with this + * set fails. + * + * history: + * - unstable: v2.0.0 + * + * @param function The secret function to configure. + * @param is_default Whether the function is the default provider of its type. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_function_set_default(duckdb_v2_secret_function_handle function, + bool is_default, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Declares a named parameter `CREATE SECRET` accepts for this provider, e.g. `region`. + * + * A value the user gives is cast to the declared type before the create callback sees it, and a parameter the function + * does not declare is rejected. Names are matched case-insensitively. Declaring the same name twice replaces the type. + * + * history: + * - unstable: v2.0.0 + * + * @param function The secret function to add the parameter to. + * @param name The name of the parameter. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param type The type of the parameter. Borrowed and copied. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_function_add_named_parameter(duckdb_v2_secret_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_logical_type_handle type, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the create callback of the secret function, invoked for every `CREATE SECRET` that resolves to its type and + * provider. + * + * The callback receives the statement as a read-only secret and fills a secret with the result, see + * `duckdb_v2_secret_create_callback_fn`. It runs on the thread running the statement, with a transaction active. A + * create callback must be set before registration. + * + * history: + * - unstable: v2.0.0 + * + * @param function The secret function to set the callback of. + * @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_secret_function_set_create_callback(duckdb_v2_secret_function_handle function, + duckdb_v2_secret_create_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets arbitrary user data on the secret function. + * + * Associates an opaque pointer with the function, handed to its create callback. The opaque handle bundles the pointer + * with an optional destructor, invoked when the data is no longer needed: once the secret function handle is destroyed + * and, if it was registered, the instance is too. + * + * history: + * - unstable: v2.0.0 + * + * @param function The secret function to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_function_set_user_data(duckdb_v2_secret_function_handle function, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Registers the secret function on the connection's instance, visible to every connection. + * + * Registration is not transactional: it takes effect at once, also inside an explicit transaction, and a rollback does + * not undo it. Registration requires a type, a provider and a create callback, defines the type if it is new, and fails + * with `ERROR_INPUT_INVALID` when a function for the same type and provider already exists, or when the function is the + * default provider of a type that exists already. A type an extension of DuckDB's defines (e.g. `s3` of httpfs) is not + * defined here: registration loads that extension, autoloading it if enabled, and fails with `ERROR_INPUT_INVALID` (or + * the autoload error) when it cannot. The secret function must have been created through a factory of the same + * instance. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_secret_function_destroy()`, which does not affect the registered function. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection to register on. + * @param function The secret function to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_secret_function(duckdb_v2_connection_handle conn, + duckdb_v2_secret_function_handle function, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Registers the secret function on the loading extension's instance, visible to every connection. A type it defines is + * attributed to the extension in `duckdb_secret_types()`; this does not make DuckDB load the extension when a statement + * names the type. + * + * Use this from the extension's load callback. Otherwise as `duckdb_v2_connection_register_secret_function()`. + * + * history: + * - unstable: v2.0.0 + * + * @param extension The loading extension. + * @param function The secret function to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_secret_function(duckdb_v2_extension_handle extension, + duckdb_v2_secret_function_handle function, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Destroys the secret function, releasing its resources. + * + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered function. + * + * history: + * - unstable: v2.0.0 + * + * @param function The secret function to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_function_destroy(duckdb_v2_secret_function_handle *function); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a new, empty secret through a factory, to fill in and hand to `duckdb_v2_context_create_secret()`. + * + * The secret starts out with no properties set, no scope and no keys. The caller owns the returned handle and must + * destroy it with `duckdb_v2_secret_destroy()`. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to create the secret through. + * @param secret On success, receives the newly created secret. 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_secret_create(duckdb_v2_factory_handle factory, duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets a string property of the secret, see `SECRET_PROPERTY`. The type is required to create the secret; the provider + * defaults to the default provider of the type, the name to one DuckDB chooses, the storage and persist type to what + * DuckDB chooses. + * + * The value is borrowed and copied. An invalid persist type fails with `ERROR_INPUT_INVALID`. Fails with + * `ERROR_INPUT_INVALID` on a read-only secret and on the secret a create callback fills, whose properties are fixed by + * the statement. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param property The property to set. + * @param value The value to set. + * @param value_length The length of `value` in bytes. `value` must be valid UTF-8, need not be null-terminated, and may + * be NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_set_property(duckdb_v2_secret_handle secret, + DUCKDB_V2_SECRET_PROPERTY property, const char *value, + idx_t value_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Adds a scope to the secret: a path prefix, e.g. `s3://bucket/dir`, the secret applies to. A lookup for a path picks + * the secret whose scope is the longest prefix of the path. A secret without scope applies to every path. + * + * The scope is borrowed and copied. Fails with `ERROR_INPUT_INVALID` on a read-only secret. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param scope The scope to add. + * @param scope_length The length of `scope` in bytes. `scope` must be valid UTF-8, need not be null-terminated, and may + * be NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_add_scope(duckdb_v2_secret_handle secret, const char *scope, + idx_t scope_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Removes every scope from the secret. In a create callback this includes the ones the user gave; check + * `duckdb_v2_secret_get_scope_count()` on the output first to supply a default scope only when the user gave none. + * Fails with `ERROR_INPUT_INVALID` on a read-only secret. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_clear_scope(duckdb_v2_secret_handle secret, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the value of a key of the secret. + * + * The value is borrowed and copied and can be of any type, nested ones included; a NULL value is stored as a NULL. + * Setting a key again replaces its value. Keys are matched case-insensitively and keep the casing given first. For the + * options of a `CREATE SECRET` this is the value the named parameter was given. Fails with `ERROR_INPUT_INVALID` on a + * read-only secret. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param key The key to set. + * @param key_length The length of `key` in bytes. `key` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param value The value to store. Borrowed and copied. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_set_value(duckdb_v2_secret_handle secret, const char *key, + idx_t key_length, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Marks a key as sensitive, so that its value is never displayed: `duckdb_secrets()` and the echo of `CREATE SECRET` + * show it as `redacted`, while `duckdb_v2_secret_get_value()` still returns it. The key does not have to hold a value + * yet, which suits keys only some secrets hold. Keys are matched case-insensitively. Fails with `ERROR_INPUT_INVALID` + * on a read-only secret. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param key The key to redact. + * @param key_length The length of `key` in bytes. `key` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_add_redacted_key(duckdb_v2_secret_handle secret, const char *key, + idx_t key_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Destroys the secret, releasing its resources. Values and views retrieved from it must not be used afterwards, except + * values the caller owns. + * + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Must only be called on an owned secret, never on the borrowed ones of a create callback. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_destroy(duckdb_v2_secret_handle *secret); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Borrows a string property of the secret, see `SECRET_PROPERTY`. Empty when the property is not set, except the + * persist type, which then reads back as `default`. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param property The property to read. + * @param value Receives a borrowed pointer to the value. Valid until the secret is destroyed or the property is set + * again. + * @param value_length Receives the length of `*value` in bytes. `*value` is not guaranteed to be null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_get_property(duckdb_v2_secret_handle secret, + DUCKDB_V2_SECRET_PROPERTY property, const char **value, + idx_t *value_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the number of scopes of the secret. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param count Receives the number of scopes. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_get_scope_count(duckdb_v2_secret_handle secret, idx_t *count, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Borrows a scope of the secret, in the order added. + * + * Fails with `ERROR_INPUT_OUT_OF_RANGE` when the index is not below `duckdb_v2_secret_get_scope_count()`. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param index The index of the scope. + * @param scope Receives a borrowed pointer to the scope. Valid until the secret is destroyed or its scopes change + * (`duckdb_v2_secret_add_scope()`, `duckdb_v2_secret_clear_scope()`). + * @param scope_length Receives the length of `*scope` in bytes. `*scope` is not guaranteed to be null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_get_scope(duckdb_v2_secret_handle secret, idx_t index, const char **scope, + idx_t *scope_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the number of keys of the secret. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param count Receives the number of keys. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_get_key_count(duckdb_v2_secret_handle secret, idx_t *count, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Borrows a key of the secret. The order is unspecified but stable for the handle. + * + * Fails with `ERROR_INPUT_OUT_OF_RANGE` when the index is not below `duckdb_v2_secret_get_key_count()`. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param index The index of the key. + * @param key Receives a borrowed pointer to the key. Valid until the secret is destroyed. + * @param key_length Receives the length of `*key` in bytes. `*key` is not guaranteed to be null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_get_key(duckdb_v2_secret_handle secret, idx_t index, const char **key, + idx_t *key_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the value of a key of the secret, unredacted. The returned value is owned by the caller and must be + * destroyed via `duckdb_v2_value_destroy()`. + * + * A key the secret does not have is not an error: `value` receives a null handle then, which tells it apart from a key + * holding a NULL value. Keys are matched case-insensitively. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param key The key to read. + * @param key_length The length of `key` in bytes. `key` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param value Receives the value, or a null handle if the secret has no such key. Owned by the caller; destroy via + * `duckdb_v2_value_destroy()`. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_get_value(duckdb_v2_secret_handle secret, const char *key, + idx_t key_length, duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves whether the value of the key is redacted when the secret is displayed. A key the secret does not have is + * not redacted. + * + * history: + * - unstable: v2.0.0 + * + * @param secret The secret. + * @param key The key to check. + * @param key_length The length of `key` in bytes. `key` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param redacted Receives whether the key is redacted. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_secret_is_key_redacted(duckdb_v2_secret_handle secret, const char *key, + idx_t key_length, bool *redacted, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Looks up the secret of a type that applies best to a path, the way DuckDB resolves the credentials of a file it + * opens. + * + * Of the secrets of the type visible to the context's transaction, the one whose scope is the longest prefix of the + * path wins; a secret without scope matches every path with the lowest score. When no secret matches, `secret` receives + * a null handle and the call still succeeds. The returned secret is a copy owned by the caller, to destroy via + * `duckdb_v2_secret_destroy()`. + * + * The lookup also sees secrets created in the transaction with the `transaction` persist type. + * + * history: + * - unstable: v2.0.0 + * + * @param ctx The context to look up in. + * @param path The path to find a secret for, e.g. `s3://bucket/key`. + * @param path_length The length of `path` in bytes. `path` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param type The secret type to look for, e.g. `s3`. + * @param type_length The length of `type` in bytes. `type` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param secret Receives the best matching secret, or a null handle if none matches. Owned by the caller. + * @param score Optional. Receives how well the secret matches: the length of the longest matching scope prefix, higher + * is better. Undefined when nothing matched. Lets the caller rank the matches of several types. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_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); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Looks up a secret by its name, across all storages. + * + * When no secret has the name, `secret` receives a null handle and the call still succeeds. The type is not checked: + * compare `SECRET_PROPERTY_TYPE` read with `duckdb_v2_secret_get_property()`. The returned secret is a copy owned by + * the caller, to destroy via `duckdb_v2_secret_destroy()`. + * + * Fails with `ERROR_CONFIGURATION_INVALID` when more than one storage holds a secret of the name. + * + * history: + * - unstable: v2.0.0 + * + * @param ctx The context to look up in. + * @param name The name of the secret. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param secret Receives the secret, or a null handle if there is none of that name. 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_context_get_secret_by_name(duckdb_v2_context_handle ctx, const char *name, + idx_t name_length, duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a secret, as the equivalent `CREATE SECRET` statement would, in the context's transaction. + * + * The keys of the given secret are the named parameters of the statement. The secret function for its type and provider + * runs to build the stored secret, and the secret manager stores it according to its persist type and storage. Use the + * `transaction` persist type for credentials that must not outlive the transaction. `created` is optional: when given, + * it receives a copy of the secret that now exists, which with `SECRET_ON_CONFLICT_IGNORE` is the existing one. The + * copy is owned by the caller, to destroy via `duckdb_v2_secret_destroy()`. + * + * Redacted keys of the given secret are ignored: the provider decides which keys of the stored secret are redacted. A + * secret read back with storage `transaction` (a transaction secret) is created with the `transaction` persist type. + * Fails with `ERROR_CONFIGURATION_PERMISSION` when `enable_external_access` is off, before the keys are checked, as + * `CREATE SECRET` does. + * + * To refresh a secret, create a new one through its provider: copy the old secret's properties + * (`duckdb_v2_secret_get_property()` / `duckdb_v2_secret_set_property()`, skipping empty ones) and scopes, set the + * refresh options as keys, and create it with `SECRET_ON_CONFLICT_REPLACE`. Do not copy the old secret's keys as is: + * they are the stored values, not the provider's named parameters. + * + * history: + * - unstable: v2.0.0 + * + * @param ctx The context to create the secret in. + * @param secret The description of the secret. Borrowed. + * @param on_conflict What to do when a secret of the same name exists. + * @param created Optional. Receives the secret. 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_context_create_secret(duckdb_v2_context_handle ctx, + duckdb_v2_secret_handle secret, + DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, + duckdb_v2_secret_handle *created, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Looks up the secret of a type that applies best to a path, the way DuckDB resolves the credentials of a file it + * opens. + * + * Of the secrets of the type visible to the connection's transaction, or one of their own when the connection has none + * open, the one whose scope is the longest prefix of the path wins; a secret without scope matches every path with the + * lowest score. When no secret matches, `secret` receives a null handle and the call still succeeds. The returned + * secret is a copy owned by the caller, to destroy via `duckdb_v2_secret_destroy()`. + * + * The lookup also sees secrets created in the transaction with the `transaction` persist type. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection to look up in. + * @param path The path to find a secret for, e.g. `s3://bucket/key`. + * @param path_length The length of `path` in bytes. `path` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param type The secret type to look for, e.g. `s3`. + * @param type_length The length of `type` in bytes. `type` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param secret Receives the best matching secret, or a null handle if none matches. Owned by the caller. + * @param score Optional. Receives how well the secret matches: the length of the longest matching scope prefix, higher + * is better. Undefined when nothing matched. Lets the caller rank the matches of several types. + * @param err Optional. On failure, receives an opaque 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_lookup_secret(duckdb_v2_connection_handle conn, const char *path, + idx_t path_length, const char *type, idx_t type_length, + duckdb_v2_secret_handle *secret, int64_t *score, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Looks up a secret by its name, across all storages. + * + * When no secret has the name, `secret` receives a null handle and the call still succeeds. The type is not checked: + * compare `SECRET_PROPERTY_TYPE` read with `duckdb_v2_secret_get_property()`. The returned secret is a copy owned by + * the caller, to destroy via `duckdb_v2_secret_destroy()`. + * + * Fails with `ERROR_CONFIGURATION_INVALID` when more than one storage holds a secret of the name. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection to look up in. + * @param name The name of the secret. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param secret Receives the secret, or a null handle if there is none of that name. 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_connection_get_secret_by_name(duckdb_v2_connection_handle conn, const char *name, + idx_t name_length, duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a secret, as the equivalent `CREATE SECRET` statement would, in the connection's transaction, or one of their + * own when the connection has none open. + * + * The keys of the given secret are the named parameters of the statement. The secret function for its type and provider + * runs to build the stored secret, and the secret manager stores it according to its persist type and storage. Use the + * `transaction` persist type for credentials that must not outlive the transaction. Outside an explicit transaction a + * secret with the `transaction` persist type ends with the implicit transaction the call runs in. `created` is + * optional: when given, it receives a copy of the secret that now exists, which with `SECRET_ON_CONFLICT_IGNORE` is the + * existing one. The copy is owned by the caller, to destroy via `duckdb_v2_secret_destroy()`. + * + * Redacted keys of the given secret are ignored: the provider decides which keys of the stored secret are redacted. A + * secret read back with storage `transaction` (a transaction secret) is created with the `transaction` persist type. + * Fails with `ERROR_CONFIGURATION_PERMISSION` when `enable_external_access` is off, before the keys are checked, as + * `CREATE SECRET` does. + * + * To refresh a secret, create a new one through its provider: copy the old secret's properties + * (`duckdb_v2_secret_get_property()` / `duckdb_v2_secret_set_property()`, skipping empty ones) and scopes, set the + * refresh options as keys, and create it with `SECRET_ON_CONFLICT_REPLACE`. Do not copy the old secret's keys as is: + * they are the stored values, not the provider's named parameters. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection to create the secret in. + * @param secret The description of the secret. Borrowed. + * @param on_conflict What to do when a secret of the same name exists. + * @param created Optional. Receives the secret. 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_connection_create_secret(duckdb_v2_connection_handle conn, + duckdb_v2_secret_handle secret, + DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, + duckdb_v2_secret_handle *created, + duckdb_v2_error_info_handle *err); +#endif + +/* --- Struct definitions for secret --- */ + /* ============================================================================ * MODULE: stats * ============================================================================ */ diff --git a/src/duckdb/src/main/capi/v2/capi_v2_secret.cpp b/src/duckdb/src/main/capi/v2/capi_v2_secret.cpp new file mode 100644 index 000000000..ca17e41a9 --- /dev/null +++ b/src/duckdb/src/main/capi/v2/capi_v2_secret.cpp @@ -0,0 +1,675 @@ +#include "duckdb/main/capi_v2/capi_v2_internal.hpp" +#include "duckdb/main/config.hpp" +#include "duckdb/main/extension/extension_loader.hpp" +#include "duckdb/main/extension_helper.hpp" +#include "duckdb/main/secret/secret.hpp" +#include "duckdb/main/secret/secret_manager.hpp" + +namespace duckdb::capiv2 { + +//! A key/value secret as the C API sees it: properties, scopes and keys, either owned and freely changeable, read-only, +//! or the output of a create callback (whose properties are fixed by the statement). +class CV2Secret { +public: + enum class Mode { OWNED, READ_ONLY, OUTPUT }; + + explicit CV2Secret(Mode mode = Mode::OWNED) : mode(mode) { + } + + //! A copy of a stored secret, owned by the caller. + static unique_ptr FromEntry(const SecretEntry &entry) { + auto &kv_secret = entry.secret->Cast(); + auto result = make_uniq(); + result->scope = kv_secret.GetScope(); + result->type = kv_secret.GetType(); + result->provider = kv_secret.GetProvider(); + result->name = kv_secret.GetName(); + result->storage = entry.storage_mode; + result->persist_type = entry.persist_type; + result->values = kv_secret.secret_map; + result->redacted = kv_secret.redact_keys; + return result; + } + + //! The statement being run, with its options as keys. + static unique_ptr FromInput(const CreateSecretInput &input, Mode mode) { + auto result = make_uniq(mode); + result->scope = input.scope; + result->type = input.type; + result->provider = input.provider; + result->name = input.name; + result->storage = input.storage_type.GetIdentifierName(); + result->persist_type = input.persist_type; + return result; + } + + void CheckWritable(bool is_property) const { + if (mode == Mode::READ_ONLY) { + throw InvalidInputException("The secret is read-only."); + } + if (mode == Mode::OUTPUT && is_property) { + throw InvalidInputException( + "The properties of the secret a create callback fills are fixed by the statement."); + } + } + + static std::string_view PersistTypeName(SecretPersistType persist_type) { + switch (persist_type) { + case SecretPersistType::TEMPORARY: + return "temporary"; + case SecretPersistType::PERSISTENT: + return "persistent"; + case SecretPersistType::TRANSACTION: + return "transaction"; + default: + return "default"; + } + } + + static SecretPersistType ParsePersistType(std::string_view name) { + auto lower = StringUtil::Lower(string(name)); + if (lower == "default") { + return SecretPersistType::DEFAULT; + } + if (lower == "temporary") { + return SecretPersistType::TEMPORARY; + } + if (lower == "persistent") { + return SecretPersistType::PERSISTENT; + } + if (lower == "transaction") { + return SecretPersistType::TRANSACTION; + } + throw InvalidInputException( + "Unknown persist type '%s', expected default, temporary, persistent or transaction.", string(name)); + } + + unique_ptr ToKeyValueSecret() const { + auto result = make_uniq(scope, type, provider, name); + result->secret_map = values; + result->redact_keys = redacted; + return result; + } + +public: + Mode mode; + vector scope; + Identifier type; + Identifier provider; + Identifier name; + string storage; + SecretPersistType persist_type = SecretPersistType::DEFAULT; + identifier_tree_t values; + identifier_set_t redacted; +}; + +static auto Convert(duckdb_v2_secret_handle secret) -> CV2Secret * { + return reinterpret_cast(secret); +} +static auto Convert(CV2Secret *secret) -> duckdb_v2_secret_handle { + return reinterpret_cast(secret); +} + +//! The create callback of a secret function, with the user data and parameters it was registered with. +class CV2CreateSecretInfo final : public CreateSecretFunctionInfo { +public: + duckdb_v2_secret_create_callback_fn callback = nullptr; + shared_ptr user_data; + named_parameter_type_map_t named_parameters; +}; + +static unique_ptr CallCreateCallback(ClientContext &context, CreateSecretInput &input) { + D_ASSERT(input.function_info); + auto &info = static_cast(*input.function_info); + + // the options are cast to the declared types, which a statement has been through already + auto in_secret = CV2Secret::FromInput(input, CV2Secret::Mode::READ_ONLY); + for (auto &option : input.options) { + auto param = info.named_parameters.find(Identifier(option.first)); + if (param == info.named_parameters.end()) { + throw InvalidInputException("Unknown parameter %s for secret type %s with provider %s", option.first, + input.type, input.provider); + } + in_secret->values[param->first] = option.second.CastAs(context, param->second); + } + auto out_secret = CV2Secret::FromInput(input, CV2Secret::Mode::OUTPUT); + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + CV2CallbackContext callback_context(context); + info.callback(Convert(in_secret.get()), Convert(out_secret.get()), + info.user_data ? info.user_data->GetData() : nullptr, Convert(&callback_context), &err_ptr); + if (err.HasError()) { + err.ThrowAsException(); + } + return out_secret->ToKeyValueSecret(); +} + +class CV2SecretFunction { +public: + explicit CV2SecretFunction(DatabaseInstance &db) : db(db) { + } + + void Register(DatabaseInstance &target, const string &extension_name) { + CheckRegistrationTarget(db, target, "secret function"); + if (type.empty()) { + throw InvalidInputException("A type must be set for the secret function."); + } + if (provider.empty()) { + throw InvalidInputException("A provider must be set for the secret function."); + } + if (!callback) { + throw InvalidInputException("A create callback must be set for the secret function."); + } + + auto &manager = *DBConfig::GetConfig(target).secret_manager; + // a type an extension defines is loaded as CREATE SECRET would load it, never defined here + auto owner = ExtensionHelper::FindExtensionInEntries(type, EXTENSION_SECRET_TYPES); + if (!owner.empty() && owner != extension_name) { + SecretType existing_type; + if (!manager.TryLookupType(type, existing_type)) { + throw InvalidInputException( + "Secret type %s is defined by the %s extension, load it before registering provider %s", type, + owner, provider); + } + } + + SecretType secret_type; + secret_type.name = type; + secret_type.deserializer = KeyValueSecret::Deserialize; + secret_type.default_provider = is_default ? provider.GetIdentifierName() : string(); + secret_type.extension = extension_name; + + auto info = make_shared_ptr(); + info->callback = callback; + info->user_data = user_data; + info->named_parameters = named_parameters; + CreateSecretFunction function; + function.secret_type = type.GetIdentifierName(); + function.provider = provider; + function.function = CallCreateCallback; + function.named_parameters = named_parameters; + function.info = std::move(info); + manager.RegisterSecretFunctionAndType(std::move(function), secret_type); + } + +public: + //! The database it was created for: the only one it can be registered on. + DatabaseInstance &db; + Identifier type; + Identifier provider; + bool is_default = false; + named_parameter_type_map_t named_parameters; + duckdb_v2_secret_create_callback_fn callback = nullptr; + shared_ptr user_data; +}; + +static auto Convert(duckdb_v2_secret_function_handle function) -> CV2SecretFunction * { + return reinterpret_cast(function); +} +static auto Convert(CV2SecretFunction *function) -> duckdb_v2_secret_function_handle { + return reinterpret_cast(function); +} + +static OnCreateConflict ConvertOnConflict(DUCKDB_V2_SECRET_ON_CONFLICT on_conflict) { + switch (on_conflict) { + case DUCKDB_V2_SECRET_ON_CONFLICT_ERROR: + return OnCreateConflict::ERROR_ON_CONFLICT; + case DUCKDB_V2_SECRET_ON_CONFLICT_IGNORE: + return OnCreateConflict::IGNORE_ON_CONFLICT; + case DUCKDB_V2_SECRET_ON_CONFLICT_REPLACE: + return OnCreateConflict::REPLACE_ON_CONFLICT; + default: + throw InvalidInputException("Unknown conflict behavior."); + } +} + +} // namespace duckdb::capiv2 + +//---------------------------------------------------------------------------------------------------------------------- +// Public Functions +//---------------------------------------------------------------------------------------------------------------------- + +using namespace duckdb::capiv2; + +//-------------------------------------------------------- Secret function --------------------------------------------- + +DUCKDB_V2_ERROR duckdb_v2_secret_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_secret_function_handle *function, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(factory); + DUCKDB_CHECK_ARG(function); + *function = nullptr; + return WithErrorHandler(err, [&]() { + auto result = duckdb::make_uniq(Convert(factory)->GetDatabase()); + *function = Convert(result.release()); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_function_set_type(duckdb_v2_secret_function_handle function, const char *type, + idx_t type_length, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_STR_ARG(type, type_length); + return WithErrorHandler( + err, [&]() { Convert(function)->type = duckdb::Identifier(ConvertIdentifierName(type, type_length)); }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_function_set_provider(duckdb_v2_secret_function_handle function, const char *provider, + idx_t provider_length, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_STR_ARG(provider, provider_length); + return WithErrorHandler(err, [&]() { + Convert(function)->provider = duckdb::Identifier(ConvertIdentifierName(provider, provider_length)); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_function_set_default(duckdb_v2_secret_function_handle function, bool is_default, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { Convert(function)->is_default = is_default; }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_function_add_named_parameter(duckdb_v2_secret_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_logical_type_handle type, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_STR_ARG(name, name_length); + DUCKDB_CHECK_ARG(type); + return WithErrorHandler(err, [&]() { + auto parameter_type = Convert(type); + Convert(function)->named_parameters[duckdb::Identifier(ConvertIdentifierName(name, name_length))] = + *parameter_type; + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_function_set_create_callback(duckdb_v2_secret_function_handle function, + duckdb_v2_secret_create_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { Convert(function)->callback = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_function_set_user_data(duckdb_v2_secret_function_handle function, + duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { + Convert(function)->user_data = duckdb::make_shared_ptr(data->ptr, data->destroy, data->equals); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_connection_register_secret_function(duckdb_v2_connection_handle conn, + duckdb_v2_secret_function_handle function, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(conn); + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { Convert(function)->Register(*Convert(conn)->context->db, duckdb::string()); }); +} + +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_CHECK_ARG(extension); + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { + auto &loader = GetExtensionLoader(extension); + Convert(function)->Register(loader.GetDatabaseInstance(), + loader.GetRegisteredExtensionName().GetIdentifierName()); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_function_destroy(duckdb_v2_secret_function_handle *function) { + return WithErrorHandler(nullptr, [&]() { + if (!function) { + return; + } + if (*function) { + delete Convert(*function); + *function = nullptr; + } + }); +} + +//-------------------------------------------------------- Building a secret ------------------------------------------- + +DUCKDB_V2_ERROR duckdb_v2_secret_create(duckdb_v2_factory_handle factory, duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(factory); + DUCKDB_CHECK_ARG(secret); + *secret = nullptr; + return WithErrorHandler(err, [&]() { *secret = Convert(new CV2Secret()); }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_set_property(duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_PROPERTY property, + const char *value, idx_t value_length, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_STR_ARG(value, value_length); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + self.CheckWritable(true); + switch (property) { + case DUCKDB_V2_SECRET_PROPERTY_TYPE: + self.type = duckdb::Identifier(ConvertIdentifierName(value, value_length)); + break; + case DUCKDB_V2_SECRET_PROPERTY_PROVIDER: + self.provider = duckdb::Identifier(ConvertIdentifierName(value, value_length)); + break; + case DUCKDB_V2_SECRET_PROPERTY_NAME: + self.name = duckdb::Identifier(ConvertIdentifierName(value, value_length)); + break; + case DUCKDB_V2_SECRET_PROPERTY_STORAGE: + self.storage = duckdb::string(Convert(value, value_length)); + break; + case DUCKDB_V2_SECRET_PROPERTY_PERSIST_TYPE: + self.persist_type = CV2Secret::ParsePersistType(Convert(value, value_length)); + break; + default: + throw duckdb::InvalidInputException("Unknown secret property."); + } + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_add_scope(duckdb_v2_secret_handle secret, const char *scope, idx_t scope_length, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_STR_ARG(scope, scope_length); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + self.CheckWritable(false); + self.scope.push_back(duckdb::string(Convert(scope, scope_length))); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_clear_scope(duckdb_v2_secret_handle secret, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + self.CheckWritable(false); + self.scope.clear(); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_set_value(duckdb_v2_secret_handle secret, const char *key, idx_t key_length, + duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_ARG(value); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + self.CheckWritable(false); + self.values[duckdb::Identifier(ConvertIdentifierName(key, key_length))] = *Convert(value); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_add_redacted_key(duckdb_v2_secret_handle secret, const char *key, idx_t key_length, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_STR_ARG(key, key_length); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + self.CheckWritable(false); + self.redacted.insert(duckdb::Identifier(ConvertIdentifierName(key, key_length))); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_destroy(duckdb_v2_secret_handle *secret) { + return WithErrorHandler(nullptr, [&]() { + if (!secret) { + return; + } + if (*secret) { + delete Convert(*secret); + *secret = nullptr; + } + }); +} + +//-------------------------------------------------------- Reading a secret -------------------------------------------- + +DUCKDB_V2_ERROR duckdb_v2_secret_get_property(duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_PROPERTY property, + const char **value, idx_t *value_length, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_ARG(value); + DUCKDB_CHECK_ARG(value_length); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + switch (property) { + case DUCKDB_V2_SECRET_PROPERTY_TYPE: + SetStringOut(value, value_length, self.type); + break; + case DUCKDB_V2_SECRET_PROPERTY_PROVIDER: + SetStringOut(value, value_length, self.provider); + break; + case DUCKDB_V2_SECRET_PROPERTY_NAME: + SetStringOut(value, value_length, self.name); + break; + case DUCKDB_V2_SECRET_PROPERTY_STORAGE: + SetStringOut(value, value_length, std::string_view(self.storage)); + break; + case DUCKDB_V2_SECRET_PROPERTY_PERSIST_TYPE: + SetStringOut(value, value_length, CV2Secret::PersistTypeName(self.persist_type)); + break; + default: + throw duckdb::InvalidInputException("Unknown secret property."); + } + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_get_scope_count(duckdb_v2_secret_handle secret, idx_t *count, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_ARG(count); + return WithErrorHandler(err, [&]() { *count = Convert(secret)->scope.size(); }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_get_scope(duckdb_v2_secret_handle secret, idx_t index, const char **scope, + idx_t *scope_length, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_ARG(scope); + DUCKDB_CHECK_ARG(scope_length); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + if (index >= self.scope.size()) { + throw duckdb::OutOfRangeException("The scope index %llu is out of range.", index); + } + SetStringOut(scope, scope_length, std::string_view(self.scope[index])); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_get_key_count(duckdb_v2_secret_handle secret, idx_t *count, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_ARG(count); + return WithErrorHandler(err, [&]() { *count = Convert(secret)->values.size(); }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_get_key(duckdb_v2_secret_handle secret, idx_t index, const char **key, + idx_t *key_length, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_ARG(key); + DUCKDB_CHECK_ARG(key_length); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + if (index >= self.values.size()) { + throw duckdb::OutOfRangeException("The key index %llu is out of range.", index); + } + SetStringOut(key, key_length, std::next(self.values.begin(), static_cast(index))->first); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_get_value(duckdb_v2_secret_handle secret, const char *key, idx_t key_length, + duckdb_v2_value_handle *value, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_ARG(value); + *value = nullptr; + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + auto entry = self.values.find(duckdb::Identifier(ConvertIdentifierName(key, key_length))); + if (entry != self.values.end()) { + *value = Convert(new duckdb::Value(entry->second)); + } + }); +} + +DUCKDB_V2_ERROR duckdb_v2_secret_is_key_redacted(duckdb_v2_secret_handle secret, const char *key, idx_t key_length, + bool *redacted, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_ARG(redacted); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + auto identifier = duckdb::Identifier(ConvertIdentifierName(key, key_length)); + *redacted = self.redacted.find(identifier) != self.redacted.end() && self.values.count(identifier) > 0; + }); +} + +//-------------------------------------------------------- Finding and creating secrets -------------------------------- + +namespace { + +DUCKDB_V2_ERROR LookupSecret(CV2Context &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_CHECK_STR_ARG(path, path_length); + DUCKDB_CHECK_STR_ARG(type, type_length); + DUCKDB_CHECK_ARG(secret); + *secret = nullptr; + return WithErrorHandler(err, [&]() { + auto path_string = duckdb::string(Convert(path, path_length)); + auto type_string = duckdb::string(ConvertIdentifierName(type, type_length)); + ctx.WithContext([&](duckdb::ClientContext &context) { + auto transaction = duckdb::CatalogTransaction::GetSystemCatalogTransaction(context); + auto match = duckdb::SecretManager::Get(context).LookupSecret(transaction, path_string, type_string); + if (match.HasMatch()) { + *secret = Convert(CV2Secret::FromEntry(*match.secret_entry).release()); + if (score) { + *score = match.score; + } + } + }); + }); +} + +DUCKDB_V2_ERROR GetSecretByName(CV2Context &ctx, const char *name, idx_t name_length, duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_STR_ARG(name, name_length); + DUCKDB_CHECK_ARG(secret); + *secret = nullptr; + return WithErrorHandler(err, [&]() { + auto name_string = duckdb::string(ConvertIdentifierName(name, name_length)); + ctx.WithContext([&](duckdb::ClientContext &context) { + auto transaction = duckdb::CatalogTransaction::GetSystemCatalogTransaction(context); + auto entry = duckdb::SecretManager::Get(context).GetSecretByName(transaction, name_string); + if (entry) { + *secret = Convert(CV2Secret::FromEntry(*entry).release()); + } + }); + }); +} + +DUCKDB_V2_ERROR CreateSecret(CV2Context &ctx, duckdb_v2_secret_handle secret, DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, + duckdb_v2_secret_handle *created, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(secret); + if (created) { + *created = nullptr; + } + return WithErrorHandler(err, [&]() { + auto &self = *Convert(secret); + if (self.type.empty()) { + throw duckdb::InvalidInputException("A type must be set to create the secret."); + } + duckdb::CreateSecretInput input; + input.type = self.type; + input.provider = self.provider; + // an unnamed secret gets the default name of its type, as CREATE SECRET without a name does + input.name = self.name.empty() + ? duckdb::Identifier("__default_" + duckdb::StringUtil::Lower(self.type.GetIdentifierName())) + : self.name; + input.scope = self.scope; + for (auto &value : self.values) { + input.options[value.first.GetIdentifierName()] = value.second; + } + input.on_conflict = ConvertOnConflict(on_conflict); + // a looked-up transaction secret reports storage `transaction`: that is its persist type, not a storage + auto storage = duckdb::Identifier(self.storage); + auto persist_type = self.persist_type; + if (storage == duckdb::SecretManager::TRANSACTION_STORAGE_NAME) { + if (persist_type != duckdb::SecretPersistType::DEFAULT && + persist_type != duckdb::SecretPersistType::TRANSACTION) { + throw duckdb::InvalidInputException( + "Storage 'transaction' requires the 'transaction' persist type, not '%s'", + duckdb::string(CV2Secret::PersistTypeName(persist_type))); + } + persist_type = duckdb::SecretPersistType::TRANSACTION; + storage = duckdb::Identifier(); + } + input.storage_type = storage; + input.persist_type = persist_type; + ctx.WithContext([&](duckdb::ClientContext &context) { + duckdb::SecretManager::ThrowIfSecretCreationDisabled(*context.db, input.type, input.provider); + auto &manager = duckdb::SecretManager::Get(context); + auto transaction = duckdb::CatalogTransaction::GetSystemCatalogTransaction(context); + manager.BindCreateSecretOptions(context.GetContext(), transaction, input); + auto entry = manager.CreateSecret(context, input); + if (!created) { + return; + } + if (!entry) { + // the conflict was ignored: return the secret it was with, from the storage the request resolved to + auto persist_type = input.persist_type; + auto storage = manager.ResolveSecretStorage(persist_type, input.storage_type); + entry = manager.GetSecretByName(transaction, input.name.GetIdentifierName(), storage); + } + if (entry) { + *created = Convert(CV2Secret::FromEntry(*entry).release()); + } + }); + }); +} + +} // namespace + +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_CHECK_ARG(ctx); + return LookupSecret(*Convert(ctx), path, path_length, type, type_length, secret, score, err); +} + +DUCKDB_V2_ERROR duckdb_v2_connection_lookup_secret(duckdb_v2_connection_handle conn, const char *path, + idx_t path_length, const char *type, idx_t type_length, + duckdb_v2_secret_handle *secret, int64_t *score, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(conn); + return LookupSecret(Convert(conn)->context_handle, path, path_length, type, type_length, secret, score, err); +} + +DUCKDB_V2_ERROR duckdb_v2_context_get_secret_by_name(duckdb_v2_context_handle ctx, const char *name, idx_t name_length, + duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(ctx); + return GetSecretByName(*Convert(ctx), name, name_length, secret, err); +} + +DUCKDB_V2_ERROR duckdb_v2_connection_get_secret_by_name(duckdb_v2_connection_handle conn, const char *name, + idx_t name_length, duckdb_v2_secret_handle *secret, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(conn); + return GetSecretByName(Convert(conn)->context_handle, name, name_length, secret, err); +} + +DUCKDB_V2_ERROR duckdb_v2_context_create_secret(duckdb_v2_context_handle ctx, duckdb_v2_secret_handle secret, + DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, + duckdb_v2_secret_handle *created, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(ctx); + return CreateSecret(*Convert(ctx), secret, on_conflict, created, err); +} + +DUCKDB_V2_ERROR duckdb_v2_connection_create_secret(duckdb_v2_connection_handle conn, duckdb_v2_secret_handle secret, + DUCKDB_V2_SECRET_ON_CONFLICT on_conflict, + duckdb_v2_secret_handle *created, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(conn); + return CreateSecret(Convert(conn)->context_handle, secret, on_conflict, created, err); +} diff --git a/src/duckdb/src/main/secret/secret_manager.cpp b/src/duckdb/src/main/secret/secret_manager.cpp index 1b9416cf0..f401c5cf7 100644 --- a/src/duckdb/src/main/secret/secret_manager.cpp +++ b/src/duckdb/src/main/secret/secret_manager.cpp @@ -156,6 +156,25 @@ void SecretManager::RegisterSecretFunction(CreateSecretFunction function, OnCrea RegisterSecretFunctionInternal(std::move(function), on_conflict); } +void SecretManager::RegisterSecretFunctionAndType(CreateSecretFunction function, SecretType &new_type) { + D_ASSERT(Identifier(function.secret_type) == new_type.name); + lock_guard lck(manager_lock); + auto functions = secret_functions.find(new_type.name); + if (functions != secret_functions.end() && functions->second.ProviderExists(function.provider)) { + throw InvalidInputException("A secret function for type %s and provider %s already exists.", new_type.name, + function.provider); + } + auto type_exists = secret_types.find(new_type.name) != secret_types.end(); + if (type_exists && !new_type.default_provider.empty()) { + throw InvalidInputException("Only the secret function that defines the type %s can be its default provider.", + new_type.name); + } + if (!type_exists) { + RegisterSecretTypeInternal(new_type); + } + RegisterSecretFunctionInternal(std::move(function), OnCreateConflict::ERROR_ON_CONFLICT); +} + unique_ptr SecretManager::RegisterSecret(CatalogTransaction transaction, unique_ptr secret, OnCreateConflict on_conflict, SecretPersistType persist_type, const string &storage) { @@ -178,26 +197,7 @@ unique_ptr SecretManager::RegisterSecretInternal(CatalogTransaction return backend.StoreSecret(std::move(secret), on_conflict, &transaction); } - //! Handle default for persist type - if (persist_type == SecretPersistType::DEFAULT) { - if (storage.empty()) { - persist_type = config.default_persist_type; - } else { - // Derive the persist type from the named storage's own flag, so that *any* registered temporary storage - // (not only "memory") accepts a default `CREATE SECRET ... IN ` without the TEMPORARY keyword. - auto storage_backend = GetSecretStorage(storage); - persist_type = (storage_backend && !storage_backend->Persistent()) ? SecretPersistType::TEMPORARY - : SecretPersistType::PERSISTENT; - } - } - - //! Resolve storage - string resolved_storage; - if (storage.empty()) { - resolved_storage = persist_type == SecretPersistType::PERSISTENT ? DefaultStorage() : TEMPORARY_STORAGE_NAME; - } else { - resolved_storage = storage.GetIdentifierName(); - } + auto resolved_storage = ResolveSecretStorage(persist_type, storage); //! Lookup which backend to store the secret in auto backend = GetSecretStorage(Identifier(resolved_storage)); @@ -229,6 +229,27 @@ unique_ptr SecretManager::RegisterSecretInternal(CatalogTransaction return backend->StoreSecret(std::move(secret), on_conflict, &transaction); } +string SecretManager::ResolveSecretStorage(SecretPersistType &persist_type, const Identifier &storage) { + if (persist_type == SecretPersistType::TRANSACTION) { + return TRANSACTION_STORAGE_NAME; + } + if (persist_type == SecretPersistType::DEFAULT) { + if (storage.empty()) { + persist_type = config.default_persist_type; + } else { + // Derive the persist type from the named storage's own flag, so that *any* registered temporary storage + // (not only "memory") accepts a default `CREATE SECRET ... IN ` without the TEMPORARY keyword. + auto storage_backend = GetSecretStorage(storage); + persist_type = (storage_backend && !storage_backend->Persistent()) ? SecretPersistType::TEMPORARY + : SecretPersistType::PERSISTENT; + } + } + if (storage.empty()) { + return persist_type == SecretPersistType::PERSISTENT ? DefaultStorage() : TEMPORARY_STORAGE_NAME; + } + return storage.GetIdentifierName(); +} + optional_ptr SecretManager::LookupFunctionInternal(const Identifier &type, const Identifier &provider) { unique_lock lck(manager_lock); @@ -290,6 +311,7 @@ unique_ptr SecretManager::CreateSecret(ClientContext &context, cons } // Call the function + function_input.function_info = function_lookup->info.get(); auto secret = function_lookup->function(context, function_input); if (!secret) { @@ -308,6 +330,16 @@ BoundStatement SecretManager::BindCreateSecret(Context &context, CatalogTransact if (info.persist_type == SecretPersistType::TRANSACTION || info.storage_type == TRANSACTION_STORAGE_NAME) { throw BinderException("Transaction-scoped secrets cannot be created through SQL"); } + BindCreateSecretOptions(context, transaction, info); + + BoundStatement result; + result.names = {"Success"}; + result.types = {LogicalType::BOOLEAN}; + result.plan = make_uniq(info); + return result; +} + +void SecretManager::BindCreateSecretOptions(Context &context, CatalogTransaction transaction, CreateSecretInput &info) { InitializeSecrets(transaction); auto type = info.type; @@ -339,6 +371,12 @@ BoundStatement SecretManager::BindCreateSecret(Context &context, CatalogTransact type, default_string, provider); } + auto option_name = Identifier(matched_param->first.GetIdentifierName()).GetIdentifierName(); + if (matched_param->second.id() == LogicalTypeId::ANY) { + // a parameter of type ANY takes the value as provided + bound_info.options[option_name] = param.second; + continue; + } // Cast the provided value to the expected type string error_msg; auto cast_value = param.second.TryCastAs(context, matched_param->second, &error_msg); @@ -347,14 +385,9 @@ BoundStatement SecretManager::BindCreateSecret(Context &context, CatalogTransact matched_param->second.ToString(), error_msg); } - bound_info.options[Identifier(matched_param->first.GetIdentifierName()).GetIdentifierName()] = {*cast_value}; + bound_info.options[option_name] = {*cast_value}; } - - BoundStatement result; - result.names = {"Success"}; - result.types = {LogicalType::BOOLEAN}; - result.plan = make_uniq(std::move(bound_info)); - return result; + info.options = std::move(bound_info.options); } SecretMatch SecretManager::LookupSecret(CatalogTransaction transaction, const string &path, const string &type) { @@ -507,6 +540,10 @@ SecretType SecretManager::LookupType(const string &type) { return LookupTypeInternal(Identifier(type)); } +bool SecretManager::TryLookupType(const Identifier &type, SecretType &type_out) { + return TryLookupTypeInternal(type, type_out); +} + void SecretManager::RegisterSecretTypeInternal(SecretType &type) { auto lookup = secret_types.find(type.name); if (lookup != secret_types.end()) { diff --git a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp index 511fbc7e1..13c9fefcc 100644 --- a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp +++ b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp @@ -108,32 +108,6 @@ static bool CanShareSubplanExpression(const Expression &expr) { return !unsafe; } -static bool HasFixedSizeState(const LogicalType &type, const AggregateStateField &field) { - switch (field.kind) { - case AggregateFieldKind::PRIMITIVE: - return TypeIsConstantSize(type.InternalType()); - case AggregateFieldKind::OPTIONAL_VALUE: - return field.children.size() == 1 && HasFixedSizeState(type, field.children[0]); - case AggregateFieldKind::STRUCT: { - if (type.id() != LogicalTypeId::STRUCT) { - return false; - } - const auto &types = StructType::GetChildTypes(type); - if (types.size() != field.children.size()) { - return false; - } - for (idx_t i = 0; i < types.size(); i++) { - if (!HasFixedSizeState(types[i].second, field.children[i])) { - return false; - } - } - return true; - } - default: - return false; - } -} - static bool CanCombineAggregateState(const BoundAggregateExpression &aggregate) { const auto &function = aggregate.Function(); if (aggregate.IsDistinct() || aggregate.GetOrderBys() || @@ -143,7 +117,7 @@ static bool CanCombineAggregateState(const BoundAggregateExpression &aggregate) } // Combining growing states can use more memory than evaluating the original aggregates separately. const auto layout = function.GetStateType(aggregate.BindInfo().get()); - return HasFixedSizeState(layout.type, layout.field); + return layout.field.IsFixedSize(layout.type); } enum class ConversionType { diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp index c1899b91b..99dacd1e3 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp @@ -9,15 +9,16 @@ namespace duckdb { using Filter = FilterPushdown::Filter; -static bool IsVolatile(LogicalAggregate &aggr, const Expression &expr) { - bool is_volatile = false; +static bool CanInlineGroupBindings(LogicalAggregate &aggr, const Expression &expr) { + bool can_inline = true; ExpressionIterator::VisitExpression(expr, [&](const BoundColumnRefExpression &colref) { D_ASSERT(colref.Depth() == 0); - if (aggr.GetExpression(colref.Binding()).IsVolatile()) { - is_volatile = true; + auto &group_expr = aggr.GetExpression(colref.Binding()); + if (group_expr.IsVolatile() || group_expr.CanThrow()) { + can_inline = false; } }); - return is_volatile; + return can_inline; } static unique_ptr ReplaceGroupBindings(LogicalAggregate &aggr, unique_ptr root_expr) { @@ -82,8 +83,8 @@ unique_ptr FilterPushdown::PushdownAggregate(unique_ptrIsVolatile() || IsVolatile(aggr, *f.filter)) { - // a volatile filter is evaluated once per group, not once per input row + if (f.filter->IsVolatile() || !CanInlineGroupBindings(aggr, *f.filter)) { + // Keep volatile evaluation counts and the rows seen by throwing group expressions unchanged. continue; } // no aggregate! we can push this down diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp index 8e481476d..b09980ead 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp @@ -1,7 +1,13 @@ #include "duckdb/optimizer/filter_pushdown.hpp" #include "duckdb/parser/expression_map.hpp" +#include "duckdb/planner/expression/bound_between_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" +#include "duckdb/planner/expression/expression_barrier.hpp" #include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" namespace duckdb { @@ -93,7 +99,7 @@ static bool ExprIsFunctionOnlyOf(const Expression &expr, const expression_set_t //! is a join condition of the form `l = r` where `l` and `r` are join keys for //! the left and right table respectively, then pushdown `P(l)` to the left //! table, `P(r)` to the right table, and remove the original filter. -static bool +static void PushDownFiltersOnCoalescedEqualJoinKeys(vector> &filters, vector &join_conditions, const std::function filter)> &pushdown_left, const std::function filter)> &pushdown_right) { @@ -116,10 +122,9 @@ PushDownFiltersOnCoalescedEqualJoinKeys(vector> &filters, vec } if (join_cond_by_coalesced_join_keys.empty()) { - return false; + return; } - bool has_applied_pushdown = false; for (idx_t i = 0; i < filters.size(); i++) { auto &filter = filters[i]->filter; if (filter->IsVolatile() || filter->CanThrow()) { @@ -164,38 +169,97 @@ PushDownFiltersOnCoalescedEqualJoinKeys(vector> &filters, vec pushdown_left(std::move(left_filter)); pushdown_right(std::move(right_filter)); filters.erase_at(i); - has_applied_pushdown = true; i--; } +} - return has_applied_pushdown; +static bool CanSplitOuterJoinFilters(LogicalOperator &join, const vector> &filters) { + for (auto &filter : filters) { + if (filter->filter->IsVolatile() || filter->filter->CanThrow()) { + return false; + } + } + bool can_split = true; + LogicalOperatorVisitor::EnumerateExpressions(join, [&](unique_ptr *expr) { + if ((*expr)->IsVolatile() || ExpressionBarrier::Contains(**expr)) { + can_split = false; + } + }); + return can_split; +} + +static void PushDownComparisonFilters(vector> &filters, const unordered_set &bindings, + vector> &child_filters) { + auto is_non_null_constant = [](const Expression &expr) { + return expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT && + !expr.Cast().GetValue().IsNull(); + }; + for (auto &filter_ptr : filters) { + auto &filter = *filter_ptr; + auto &expr = *filter.filter; + optional_ptr column; + if (expr.GetExpressionType() == ExpressionType::COMPARE_BETWEEN) { + auto &between = expr.Cast(); + if (!is_non_null_constant(BoundBetweenExpression::LowerBound(between)) || + !is_non_null_constant(BoundBetweenExpression::UpperBound(between))) { + continue; + } + column = BoundBetweenExpression::Input(between); + } else { + if (!BoundComparisonExpression::IsComparison(expr) || + expr.GetExpressionType() == ExpressionType::COMPARE_DISTINCT_FROM || + expr.GetExpressionType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + continue; + } + auto &comparison = expr.Cast(); + auto &left = BoundComparisonExpression::Left(comparison); + auto &right = BoundComparisonExpression::Right(comparison); + const auto left_is_column = left.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF; + column = left_is_column ? left : right; + if (!is_non_null_constant(left_is_column ? right : left)) { + continue; + } + } + if (column->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + continue; + } + auto &colref = column->Cast(); + if (colref.Depth() != 0 || !bindings.count(colref.Binding().table_index)) { + continue; + } + child_filters.push_back(std::move(filter.filter)); + // Removing a match can create an unmatched row on the other side: reject its NULL-extended column. + filter.filter = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN, + column->Copy()); + filter.ExtractBindings(); + } } unique_ptr FilterPushdown::PushdownOuterJoin(unique_ptr op, unordered_set &left_bindings, unordered_set &right_bindings) { - if (op->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + if (filters.empty() || (op->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + op->type != LogicalOperatorType::LOGICAL_ANY_JOIN)) { return FinishPushdown(std::move(op)); } - auto &join = op->Cast(); - D_ASSERT(join.join_type == JoinType::OUTER); - - FilterPushdown left_pushdown(optimizer, projection_mode); - FilterPushdown right_pushdown(optimizer, projection_mode); - auto has_applied_pushdown = PushDownFiltersOnCoalescedEqualJoinKeys( - filters, join.conditions, [&](unique_ptr filter) { left_pushdown.AddFilter(std::move(filter)); }, - [&](unique_ptr filter) { right_pushdown.AddFilter(std::move(filter)); }); + D_ASSERT(op->Cast().join_type == JoinType::OUTER); - if (!has_applied_pushdown) { - return FinishPushdown(std::move(op)); + const bool can_split = CanSplitOuterJoinFilters(*op, filters); + vector> left_filters, right_filters; + if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &join = op->Cast(); + PushDownFiltersOnCoalescedEqualJoinKeys( + filters, join.conditions, [&](unique_ptr filter) { left_filters.push_back(std::move(filter)); }, + [&](unique_ptr filter) { right_filters.push_back(std::move(filter)); }); } - - left_pushdown.GenerateFilters(); - right_pushdown.GenerateFilters(); - left_pushdown.RewriteChild(*op, 0); - right_pushdown.RewriteChild(*op, 1); - return PushFinalFilters(std::move(op)); + if (can_split) { + PushDownComparisonFilters(filters, left_bindings, left_filters); + PushDownComparisonFilters(filters, right_bindings, right_filters); + } + op->children[0] = AddLogicalFilter(std::move(op->children[0]), std::move(left_filters)); + op->children[1] = AddLogicalFilter(std::move(op->children[1]), std::move(right_filters)); + return FinishPushdown(std::move(op)); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp index baa70344c..20eae1a73 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp @@ -10,16 +10,20 @@ namespace duckdb { -static bool IsVolatile(LogicalProjection &proj, const Expression &expr) { - bool is_volatile = false; - ExpressionIterator::VisitExpression(expr, [&](const BoundColumnRefExpression &colref) { - D_ASSERT(colref.Depth() == 0); - auto &proj_expr = proj.GetExpression(colref.Binding()); - if (proj_expr.IsVolatile()) { - is_volatile = true; - } - }); - return is_volatile; +static bool CanPushProjectionFilter(LogicalProjection &proj, const FilterPushdown::Filter &filter) { + if (filter.filter->CanThrow() && !filter.has_barrier) { + return false; + } + bool can_push = true; + ExpressionIterator::VisitExpression( + *filter.filter, [&](const BoundColumnRefExpression &colref) { + D_ASSERT(colref.Depth() == 0); + auto &proj_expr = proj.GetExpression(colref.Binding()); + if (proj_expr.IsVolatile()) { + can_push = false; + } + }); + return can_push; } // A compress expression only holds where it was placed, so a filter must not inline it into a position below @@ -34,16 +38,20 @@ static bool ReferencesCompressExpression(LogicalProjection &proj, const Expressi return references_compress_expression; } -static bool ReferencesComputedExpression(LogicalProjection &proj, const Expression &expr) { - bool references_computed_expression = false; - ExpressionIterator::VisitExpression(expr, [&](const BoundColumnRefExpression &colref) { - D_ASSERT(colref.Depth() == 0); - auto &proj_expr = proj.GetExpression(colref.Binding()); - if (proj_expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - references_computed_expression = true; - } - }); - return references_computed_expression; +static bool NeedsProjectionSplit(LogicalProjection &proj, const FilterPushdown::Filter &filter, + FilterPushdown::ProjectionMode projection_mode) { + bool needs_split = false; + ExpressionIterator::VisitExpression( + *filter.filter, [&](const BoundColumnRefExpression &colref) { + D_ASSERT(colref.Depth() == 0); + auto &proj_expr = proj.GetExpression(colref.Binding()); + if ((!filter.has_barrier && proj_expr.CanThrow()) || + (projection_mode == FilterPushdown::ProjectionMode::PRESERVE_COMPUTED_EXPRESSIONS && + proj_expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF)) { + needs_split = true; + } + }); + return needs_split; } static unique_ptr CreateColumnReference(const Expression &expr, ColumnBinding binding) { @@ -168,12 +176,10 @@ unique_ptr FilterPushdown::PushdownProjection(unique_ptr> remain_expressions; vector> split_expressions; auto stays_on_top = [&](const Filter &f) { - return IsVolatile(proj, *f.filter) || ReferencesCompressExpression(proj, *f.filter) || - (f.filter->CanThrow() && !f.has_barrier); + return !CanPushProjectionFilter(proj, f) || ReferencesCompressExpression(proj, *f.filter); }; auto splits_off = [&](const Filter &f) { - return projection_mode == ProjectionMode::PRESERVE_COMPUTED_EXPRESSIONS && - ReferencesComputedExpression(proj, *f.filter); + return NeedsProjectionSplit(proj, f, projection_mode); }; // barred expressions may only cross the projection if every other filter does: a filter kept on top of the // projection, or split off below it, would otherwise be evaluated after them @@ -187,7 +193,7 @@ unique_ptr FilterPushdown::PushdownProjection(unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v } } -string DateTruncSimplificationRule::DatePartToFunc(const DatePartSpecifier &date_part) { - switch (date_part) { - // These specifiers can be used as intervals. - case DatePartSpecifier::YEAR: - return "to_years"; - case DatePartSpecifier::MONTH: - return "to_months"; - case DatePartSpecifier::DAY: - return "to_days"; - case DatePartSpecifier::DECADE: - return "to_decades"; - case DatePartSpecifier::CENTURY: - return "to_centuries"; - case DatePartSpecifier::MILLENNIUM: - return "to_millennia"; - case DatePartSpecifier::MICROSECONDS: - return "to_microseconds"; - case DatePartSpecifier::MILLISECONDS: - return "to_milliseconds"; - case DatePartSpecifier::SECOND: - return "to_seconds"; - case DatePartSpecifier::MINUTE: - return "to_minutes"; - case DatePartSpecifier::HOUR: - return "to_hours"; - case DatePartSpecifier::WEEK: - return "to_weeks"; - case DatePartSpecifier::QUARTER: - return "to_quarters"; - - // These specifiers cannot be used as intervals and can only be used as - // date parts. - case DatePartSpecifier::DOW: - case DatePartSpecifier::ISODOW: - case DatePartSpecifier::DOY: - case DatePartSpecifier::ISOYEAR: - case DatePartSpecifier::YEARWEEK: - case DatePartSpecifier::ERA: - case DatePartSpecifier::TIMEZONE: - case DatePartSpecifier::TIMEZONE_HOUR: - case DatePartSpecifier::TIMEZONE_MINUTE: - default: - return ""; - } -} - unique_ptr DateTruncSimplificationRule::CreateTrunc(const BoundConstantExpression &date_part, const BoundConstantExpression &rhs, const LogicalType &return_type) { diff --git a/src/duckdb/src/parser/peg/grammar_change.cpp b/src/duckdb/src/parser/peg/grammar_change.cpp index 40b2e4361..e54e2f915 100644 --- a/src/duckdb/src/parser/peg/grammar_change.cpp +++ b/src/duckdb/src/parser/peg/grammar_change.cpp @@ -57,6 +57,29 @@ GrammarChange GrammarChange::AddTerminalRuleOverride(const string &rule_name, std::move(matcher_factory)); } +string GrammarChange::TypeName() const { + switch (type) { + case GrammarChangeType::ADD_RULE: + return "ADD_RULE"; + case GrammarChangeType::ADD_CHOICE: + return "ADD_CHOICE"; + case GrammarChangeType::PREPEND_CHOICE: + return "PREPEND_CHOICE"; + case GrammarChangeType::REMOVE_CHOICE: + return "REMOVE_CHOICE"; + case GrammarChangeType::REPLACE_CHOICE: + return "REPLACE_CHOICE"; + case GrammarChangeType::REPLACE_RULE: + return "REPLACE_RULE"; + case GrammarChangeType::SET_TRANSFORM: + return "SET_TRANSFORM"; + case GrammarChangeType::ADD_TERMINAL_RULE_OVERRIDE: + return "ADD_TERMINAL_RULE_OVERRIDE"; + default: + throw InternalException("Unsupported grammar change type"); + } +} + void GrammarChange::Apply(ParsedGrammar &grammar) const { switch (type) { case GrammarChangeType::ADD_RULE: diff --git a/src/duckdb/src/parser/peg/matcher.cpp b/src/duckdb/src/parser/peg/matcher.cpp index 19f6f5615..4547793d6 100644 --- a/src/duckdb/src/parser/peg/matcher.cpp +++ b/src/duckdb/src/parser/peg/matcher.cpp @@ -217,8 +217,11 @@ void MatcherAllocator::InitializeListChains() { } } -ParseResultAllocator::ParseResultAllocator() - : arena(Allocator::DefaultAllocator(), PARSER_ARENA_INITIAL_CAPACITY), pending_destructors(arena) { +ParseResultAllocator::ParseResultAllocator() : ParseResultAllocator(Allocator::DefaultAllocator()) { +} + +ParseResultAllocator::ParseResultAllocator(Allocator &allocator) + : arena(allocator, PARSER_ARENA_INITIAL_CAPACITY), pending_destructors(arena) { } ParseResultAllocator::~ParseResultAllocator() = default; diff --git a/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp b/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp index 83cb3a979..9415c9cda 100644 --- a/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp +++ b/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp @@ -19,6 +19,7 @@ #include "duckdb/parser/query_node/set_operation_node.hpp" #include "duckdb/parser/statement/merge_into_statement.hpp" #include "duckdb/parser/constraints/foreign_key_constraint.hpp" +#include "duckdb/common/error_data.hpp" namespace duckdb { @@ -51,30 +52,36 @@ static unique_ptr ExtractAndTransformStatement(PEGTransformer &tra unique_ptr PEGTransformerFactory::TransformTopLevelStatement(TokenIterator &token_iterator, ParserOptions &options, const CompiledGrammar &grammar, - optional_idx &failure_index) { + optional_idx &failure_index) try { if (!token_iterator.Current()) { return nullptr; } vector suggestions; - ParseResultAllocator parse_result_allocator; + // Parsing is query work too: count its arenas against the database memory + // limit instead of letting a complex statement grow the process unchecked. + auto &allocator = options.context ? BufferAllocator::Get(*options.context) : Allocator::DefaultAllocator(); + ParseResultAllocator parse_result_allocator(allocator); idx_t max_token_index = token_iterator.Position(); - // the packrat cache outlives the match processes, so they need separate arenas - ArenaAllocator process_allocator(Allocator::DefaultAllocator(), PARSER_ARENA_INITIAL_CAPACITY); - ArenaAllocator packrat_allocator(Allocator::DefaultAllocator(), PARSER_ARENA_INITIAL_CAPACITY); - ParserPackratCache packrat_cache(packrat_allocator, token_iterator.Position(), token_iterator.Size()); - MatchContext match_context(suggestions, parse_result_allocator, process_allocator, max_token_index, - MatchMode::BUILD_PARSE_RESULT, options.identifier_case_mode, &packrat_cache); - MatchState state(token_iterator, match_context); - auto match_result = grammar.TopLevelStatementMatcher().MatchParseResult(state); - process_allocator.FreeAll(); - if (!match_result.IsSuccess()) { - failure_index = state.GetMaxTokenIndex(); - return nullptr; - } - D_ASSERT(match_result.HasParseResult()); + auto match_result = MatcherResult::Failure(); + { + // Match processes and packrat entries are no longer needed once the parse result is built. + // the packrat cache outlives the match processes, so they need separate arenas + ArenaAllocator process_allocator(allocator, PARSER_ARENA_INITIAL_CAPACITY); + ArenaAllocator packrat_allocator(allocator, PARSER_ARENA_INITIAL_CAPACITY); + ParserPackratCache packrat_cache(packrat_allocator, token_iterator.Position(), token_iterator.Size()); + MatchContext match_context(suggestions, parse_result_allocator, process_allocator, max_token_index, + MatchMode::BUILD_PARSE_RESULT, options.identifier_case_mode, &packrat_cache); + MatchState state(token_iterator, match_context); + match_result = grammar.TopLevelStatementMatcher().MatchParseResult(state); + if (!match_result.IsSuccess()) { + failure_index = state.GetMaxTokenIndex(); + return nullptr; + } + D_ASSERT(match_result.HasParseResult()); - // Advance the caller's cursor past the consumed tokens. - token_iterator.SetPosition(state.token_iterator); + // Advance the caller's cursor past the consumed tokens. + token_iterator.SetPosition(state.token_iterator); + } // TopLevelStatement <- Statement? (';'+ / EndOfInput) // child 0: Optional @@ -95,10 +102,15 @@ unique_ptr PEGTransformerFactory::TransformTopLevelStatement(Token } } - ArenaAllocator transformer_allocator(Allocator::DefaultAllocator(), PARSER_ARENA_INITIAL_CAPACITY); + ArenaAllocator transformer_allocator(allocator, PARSER_ARENA_INITIAL_CAPACITY); PEGTransformer transformer(transformer_allocator, token_iterator, options, grammar); return ExtractAndTransformStatement(transformer, token_iterator, stmt_opt.GetResult(), terminator_offset); +} catch (const OutOfMemoryException &ex) { + if (!options.context) { + throw; + } + throw OutOfMemoryException("While parsing SQL: %s", ErrorData(ex).RawMessage()); } PEGTransformerFactory::PEGTransformerFactory(ParsedGrammar &grammar_p) : grammar(grammar_p) { diff --git a/src/duckdb/src/storage/local_storage.cpp b/src/duckdb/src/storage/local_storage.cpp index 815d583c9..95e5599aa 100644 --- a/src/duckdb/src/storage/local_storage.cpp +++ b/src/duckdb/src/storage/local_storage.cpp @@ -452,6 +452,7 @@ void LocalStorage::InitializeAppend(Context &context, LocalAppendState &state, D DuckTableEntry &table_entry) { state.context = &context; state.storage = &table_manager.GetOrCreateStorage(context, table); + state.append_lock = state.storage->append_lock.GetExclusiveLock(); state.storage->table_entry = &table_entry; state.storage->GetCollection().InitializeAppend(TransactionData(transaction), state.append_state); } @@ -520,11 +521,13 @@ void LocalStorage::Append(LocalAppendState &state, DuckTableEntry &table_entry, void LocalStorage::FinalizeAppend(LocalAppendState &state) { state.storage->GetCollection().FinalizeAppend(state.append_state.transaction, state.append_state); + state.append_lock.reset(); } void LocalStorage::LocalMerge(Context &context, DataTable &table, DuckTableEntry &table_entry, OptimisticWriteCollection &collection) { auto &storage = table_manager.GetOrCreateStorage(context, table); + auto append_lock = storage.append_lock.GetExclusiveLock(); storage.table_entry = &table_entry; if (!storage.append_indexes.Empty()) { // append data to indexes if required diff --git a/src/duckdb/src/storage/table/chunk_info.cpp b/src/duckdb/src/storage/table/chunk_info.cpp index f0a6c17c2..784968a77 100644 --- a/src/duckdb/src/storage/table/chunk_info.cpp +++ b/src/duckdb/src/storage/table/chunk_info.cpp @@ -77,6 +77,10 @@ static bool IsConflictingId(TransactionData transaction, transaction_t id, trans return true; } if (IsDeleteId(id)) { + if (GetWriter(id) == GetWriter(new_id)) { + // a concurrent statement of this transaction deleted the row after this write found it + return true; + } // a transaction cannot see a row whose delete it sees, so it never writes it throw InternalException("ChunkVectorInfo: write of a row whose delete the transaction sees"); } diff --git a/src/duckdb/src/transaction/duck_transaction.cpp b/src/duckdb/src/transaction/duck_transaction.cpp index 7b4ec753a..ee4257579 100644 --- a/src/duckdb/src/transaction/duck_transaction.cpp +++ b/src/duckdb/src/transaction/duck_transaction.cpp @@ -354,6 +354,7 @@ void DuckTransaction::Cleanup(VisibilityBound lowest_visibility_bound) { } unique_ptr DuckTransaction::GetCheckpointLockForStatement() { + lock_guard guard(lock_keys_lock); if (checkpoint_lock) { return nullptr; } @@ -361,6 +362,7 @@ unique_ptr DuckTransaction::GetCheckpointLockForStatement() { } void DuckTransaction::SetModifications(DatabaseModificationType type) { + lock_guard guard(lock_keys_lock); if (!checkpoint_lock) { bool require_write_lock = false; require_write_lock = require_write_lock || type.UpdateData(); @@ -387,6 +389,7 @@ void DuckTransaction::SetModifications(DatabaseModificationType type) { } unique_ptr DuckTransaction::TryGetCheckpointLock() { + lock_guard guard(lock_keys_lock); if (!checkpoint_lock) { return GetTransactionManager().TryGetCheckpointLock(); } else { diff --git a/src/duckdb/src/transaction/meta_transaction.cpp b/src/duckdb/src/transaction/meta_transaction.cpp index 84c3d7118..4c544bb73 100644 --- a/src/duckdb/src/transaction/meta_transaction.cpp +++ b/src/duckdb/src/transaction/meta_transaction.cpp @@ -98,6 +98,7 @@ void MetaTransaction::RemoveTransaction(AttachedDatabase &db) { } void MetaTransaction::SetReadOnly() { + lock_guard guard(modification_lock); if (modified_database) { throw InternalException("Cannot set MetaTransaction to read only - modifications have already been made"); } @@ -242,6 +243,7 @@ AttachedDatabase &MetaTransaction::UseDatabase(shared_ptr &dat void MetaTransaction::ModifyDatabase(ClientContext &context, AttachedDatabase &db, DatabaseModificationType modification) { + lock_guard guard(modification_lock); // Temporary objects are private to the connection, so a read-only transaction may still write them if (IsReadOnly() && !db.IsTemporary()) { throw TransactionException("Cannot write to database %s - transaction is launched in read-only mode", diff --git a/src/duckdb/ub_src_main_capi_v2.cpp b/src/duckdb/ub_src_main_capi_v2.cpp index 84ce08ce6..ee9017386 100644 --- a/src/duckdb/ub_src_main_capi_v2.cpp +++ b/src/duckdb/ub_src_main_capi_v2.cpp @@ -78,6 +78,8 @@ #include "src/main/capi/v2/capi_v2_schema.cpp" +#include "src/main/capi/v2/capi_v2_secret.cpp" + #include "src/main/capi/v2/capi_v2_statement.cpp" #include "src/main/capi/v2/capi_v2_stats.cpp" diff --git a/src/duckdb/ub_src_optimizer_rule.cpp b/src/duckdb/ub_src_optimizer_rule.cpp index d3b9a32b0..85b784452 100644 --- a/src/duckdb/ub_src_optimizer_rule.cpp +++ b/src/duckdb/ub_src_optimizer_rule.cpp @@ -14,6 +14,8 @@ #include "src/optimizer/rule/date_part_simplification.cpp" +#include "src/optimizer/rule/date_part_to_func.cpp" + #include "src/optimizer/rule/date_trunc_simplification.cpp" #include "src/optimizer/rule/distinct_aggregate_optimizer.cpp"