diff --git a/CMakeLists.txt b/CMakeLists.txt index 1a7d205b4..7d6d3e186 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -456,7 +456,6 @@ set(DUCKDB_SRC_FILES src/duckdb/ub_src_main_capi_v2.cpp src/duckdb/ub_src_main_http.cpp src/duckdb/ub_src_main_profiler.cpp - src/duckdb/ub_src_main_relation.cpp src/duckdb/ub_src_main_secret.cpp src/duckdb/ub_src_main_settings.cpp src/duckdb/ub_src_optimizer.cpp diff --git a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp index bdae27032..5989e6dc7 100644 --- a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp +++ b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp @@ -92,7 +92,7 @@ struct AverageSetOperation { }; template -static T GetAverageDivident(uint64_t count, optional_ptr bind_data) { +static T GetAverageDivident(uint64_t count, optional_ptr bind_data) { T divident = T(count); if (bind_data) { auto &avg_bind_data = bind_data->Cast(); diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp index d1a4454dd..11bb741d0 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp @@ -410,6 +410,8 @@ AggregateFunction GetGenericArgMinMaxFunction(const ArgMinMaxNullHandling null_h function.GetSignature().AddParameter("arg", LogicalType::ANY).AddParameter("val", LogicalType::ANY); AggregateFunction::WireStructStateType(function); function.SetStatisticsCallback(AggregateFunction::PropagateInputValueStats); + function.GetProperties().SetProperty(BoundAggregateExpression::NON_NULL_SELECTOR_DOMAIN_PROPERTY, + Value::BOOLEAN(true)); return function; } @@ -426,6 +428,8 @@ AggregateFunction GetVectorArgMinMaxFunctionInternal(const LogicalType &by_type, function.GetSignature().AddParameter("arg", type).AddParameter("val", by_type); AggregateFunction::WireStructStateType(function); function.SetStatisticsCallback(AggregateFunction::PropagateInputValueStats); + function.GetProperties().SetProperty(BoundAggregateExpression::NON_NULL_SELECTOR_DOMAIN_PROPERTY, + Value::BOOLEAN(true)); return function; #else auto function = GetGenericArgMinMaxFunction(null_handling); @@ -487,6 +491,8 @@ AggregateFunction GetArgMinMaxFunctionInternal(const LogicalType &by_type, const function.GetSignature().GetParameter(1).SetName("val"); function.SetBindCallback(GetBindFunction(null_handling)); function.SetStatisticsCallback(AggregateFunction::PropagateInputValueStats); + function.GetProperties().SetProperty(BoundAggregateExpression::NON_NULL_SELECTOR_DOMAIN_PROPERTY, + Value::BOOLEAN(true)); #else auto function = GetGenericArgMinMaxFunction(null_handling); function.GetSignature().GetParameter(0).SetType(type); diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/bitstring_agg.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/bitstring_agg.cpp index 0ad9f3c16..cbae70a6a 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/bitstring_agg.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/bitstring_agg.cpp @@ -48,7 +48,7 @@ struct BitstringAggBindData : public FunctionData { return false; } - static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, + static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundAggregateFunction &) { auto &bind_data = bind_data_p->Cast(); serializer.WriteProperty(100, "min", bind_data.min); @@ -227,7 +227,7 @@ idx_t BitStringAggOperation::GetRange(uhugeint_t min, uhugeint_t max) { unique_ptr BitstringPropagateStats(ClientContext &context, BoundAggregateExpression &expr, AggregateStatisticsInput &input) { if (NumericStats::HasMinMax(input.child_stats[0])) { - auto &bind_agg_data = input.bind_data->Cast(); + auto &bind_agg_data = input.bind_data.write().Cast(); bind_agg_data.min = NumericStats::Min(input.child_stats[0]); bind_agg_data.max = NumericStats::Max(input.child_stats[0]); } diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/string_agg.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/string_agg.cpp index 4838e659b..22bef06fb 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/string_agg.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/string_agg.cpp @@ -89,7 +89,7 @@ struct StringAggFunction { } static inline void PerformOperation(StringAggState &state, ArenaAllocator &allocator, string_t str, - optional_ptr data_p) { + optional_ptr data_p) { auto &data = data_p->Cast(); PerformOperation(state, allocator, str.GetData(), data.sep.c_str(), str.GetSize(), data.sep.size()); } @@ -142,7 +142,7 @@ unique_ptr StringAggBind(BindAggregateFunctionInput &input) { return make_uniq(std::move(separator_string)); } -void StringAggSerialize(Serializer &serializer, const optional_ptr bind_data_p, +void StringAggSerialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundAggregateFunction &function) { auto bind_data = bind_data_p->Cast(); serializer.WriteProperty(100, "separator", bind_data.sep); diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp index c7914a941..d4f1f2a13 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp @@ -248,6 +248,67 @@ struct IntegerSumOperation } }; +//! Adds to an int64 accumulator, throwing instead of wrapping when the sum does not fit +struct CheckedInt64Add { + static void Add(int64_t &target, int64_t input) { + if (!TryAddOperator::Operation(target, input, target)) { + throw OutOfRangeException("Overflow in sum_no_overflow: the sum does not fit in a 64-bit accumulator"); + } + } + + template + static void AddNumber(STATE &state, T input) { + Add(state.value, int64_t(input)); + } + + template + static void AddConstant(STATE &state, T input, idx_t count) { + int64_t total; + if (!TryMultiplyOperator::Operation(int64_t(input), Cast::Operation(count), total)) { + throw OutOfRangeException("Overflow in sum_no_overflow: the sum does not fit in a 64-bit accumulator"); + } + Add(state.value, total); + } +}; + +struct CheckedSumSetOperation : public SumSetOperation { + template + static void Combine(const STATE &source, STATE &target, AggregateInputData &) { + if (!source.is_set) { + return; + } + if (!target.is_set) { + target.value = source.value; + target.is_set = true; + } else { + CheckedInt64Add::Add(target.value, source.value); + } + } +}; + +//! The int64 sum of sum_no_overflow without a statistics proof that it fits (e.g. bound by name) +struct CheckedIntegerSumOperation + : public ClusteredSumOperation, + ClusteredAddOp> { + template + static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &, idx_t count) { + if (!source.is_set) { + return; + } + target.is_set = true; + CheckedInt64Add::AddConstant(target, source.value, count); + } + + template + static void Finalize(STATE &state, T &target, AggregateFinalizeData &finalize_data) { + if (!state.is_set) { + finalize_data.ReturnNull(); + } else { + target = Hugeint::Convert(state.value); + } + } +}; + struct SumToHugeintOperation : public ClusteredSumOperation, ClusteredAddOp> { template @@ -315,13 +376,15 @@ pair> BindLogicalSum(FunctionBi return binder.ResolveAggregateFunction(selection.GetBinding(), arguments, keyword_args); } -void SumNoOverflowSerialize(Serializer &serializer, const optional_ptr bind_data, +void SumNoOverflowSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundAggregateFunction &function) { // record whether the implementation was installed without a statistics proof (bound by name) serializer.WritePropertyWithDefault(100, "fallible", function.GetErrorMode() == FunctionErrors::CAN_THROW_RUNTIME_ERROR); } +bool TryUseNoOverflowSum(BoundAggregateFunction &function, bool checked); + unique_ptr SumNoOverflowDeserialize(Deserializer &deserializer, BoundAggregateFunction &function) { bool fallible = false; deserializer.ReadPropertyWithExplicitDefault(100, "fallible", fallible, false); @@ -339,46 +402,61 @@ unique_ptr SumNoOverflowDeserialize(Deserializer &deserializer, Bo if (logical.second || (!return_type.IsAggregateState() && logical.first.GetReturnType() != return_type)) { throw SerializationException("Cannot reconstruct the logical sum signature"); } - logical.first.ReplaceImplementation(function); + if (!TryUseNoOverflowSum(logical.first, fallible)) { + throw SerializationException("Cannot reconstruct the no-overflow sum implementation"); + } function = std::move(logical.first); function.SetReturnType(return_type); - if (fallible) { - function.SetFallible(); - } return nullptr; } unique_ptr SumNoOverflowBind(BindAggregateFunctionInput &input); -AggregateFunction GetSumAggregateNoOverflow(PhysicalType type) { - switch (type) { - case PhysicalType::INT32: { - auto function = AggregateFunction::UnaryAggregate, int32_t, hugeint_t, IntegerSumOperation>( - LogicalType::INTEGER, LogicalType::HUGEINT); - function.GetSignature().GetParameter(0).SetName("arg"); - function.SetName("sum_no_overflow"); - function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); - function.SetBindCallback(SumNoOverflowBind); - function.SetSerializeCallback(SumNoOverflowSerialize); - function.SetDeserializeCallback(SumNoOverflowDeserialize); - return function; - } - case PhysicalType::INT64: { - auto function = AggregateFunction::UnaryAggregate, int64_t, hugeint_t, IntegerSumOperation>( - LogicalType::BIGINT, LogicalType::HUGEINT); - function.GetSignature().GetParameter(0).SetName("arg"); - function.SetName("sum_no_overflow"); - function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); - function.SetBindCallback(SumNoOverflowBind); - function.SetSerializeCallback(SumNoOverflowSerialize); - function.SetDeserializeCallback(SumNoOverflowDeserialize); - return function; +template +AggregateFunction GetSumAggregateNoOverflow(const LogicalType &input_type) { + auto function = AggregateFunction::UnaryAggregate, INPUT_TYPE, hugeint_t, OP>( + input_type, LogicalType::HUGEINT); + function.GetSignature().GetParameter(0).SetName("arg"); + function.SetName("sum_no_overflow"); + function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); + function.SetBindCallback(SumNoOverflowBind); + function.SetSerializeCallback(SumNoOverflowSerialize); + function.SetDeserializeCallback(SumNoOverflowDeserialize); + if constexpr (std::is_same::value) { + function.SetFallible(); } + return function; +} + +//! The checked variant throws when the sum overflows the int64 accumulator, it shares the state layout +AggregateFunction GetSumAggregateNoOverflow(PhysicalType type, bool checked = false) { + switch (type) { + case PhysicalType::INT32: + return checked ? GetSumAggregateNoOverflow(LogicalType::INTEGER) + : GetSumAggregateNoOverflow(LogicalType::INTEGER); + case PhysicalType::INT64: + return checked ? GetSumAggregateNoOverflow(LogicalType::BIGINT) + : GetSumAggregateNoOverflow(LogicalType::BIGINT); default: throw BinderException("Unsupported internal type for sum_no_overflow"); } } +//! Swaps in the int64 accumulator but keeps the bound signature (e.g. DECIMAL(15,2) -> DECIMAL(38,2)), so that binding +//! sum_no_overflow by that signature (e.g. to finalize an exported state) yields the same state layout +bool TryUseNoOverflowSum(BoundAggregateFunction &function, bool checked) { + const auto internal_type = function.GetArguments()[0].InternalType(); + if (internal_type != PhysicalType::INT32 && internal_type != PhysicalType::INT64) { + return false; + } + auto arguments = function.GetArguments(); + auto return_type = function.GetReturnType(); + function.ReplaceImplementation(GetSumAggregateNoOverflow(internal_type, checked)); + function.GetArguments() = std::move(arguments); + function.SetReturnType(std::move(return_type)); + return true; +} + AggregateFunction GetSumAggregateNoOverflowDecimal() { AggregateFunction aggr({}, LogicalTypeId::DECIMAL, nullptr, nullptr, nullptr, nullptr, nullptr, FunctionNullHandling::DEFAULT_NULL_HANDLING, AggregateFunction::NoClusterUpdate(), @@ -392,17 +470,11 @@ AggregateFunction GetSumAggregateNoOverflowDecimal() { //! Binding sum_no_overflow by name (e.g. when re-binding an exported aggregate state) delegates to the regular sum, //! with the no-overflow implementation swapped in as statistics propagation does unique_ptr SumNoOverflowBind(BindAggregateFunctionInput &input) { - auto &function = input.GetBoundFunction(); - auto &arguments = input.GetArguments(); - const auto parameter_type = function.GetArguments()[0]; auto binder = input.NestedFunctionBinder(); - auto logical = BindLogicalSum(binder, arguments); - if (parameter_type.id() != LogicalTypeId::DECIMAL) { - logical.first.ReplaceImplementation(GetSumAggregateNoOverflow(parameter_type.InternalType())); - // bound by name there is no statistics proof that the int64 accumulator cannot overflow - logical.first.SetFallible(); - } - function = std::move(logical.first); + auto logical = BindLogicalSum(binder, input.GetArguments()); + // bound by name there is no statistics proof that the int64 accumulator cannot overflow + TryUseNoOverflowSum(logical.first, true); + input.GetBoundFunction() = std::move(logical.first); return std::move(logical.second); } @@ -424,13 +496,9 @@ unique_ptr SumPropagateStats(ClientContext &context, BoundAggreg return nullptr; } - // Replace with fast implementation when possible: only INT32/INT64 have a narrower no-overflow implementation to - // swap in. - const bool has_no_overflow_variant = internal_type == PhysicalType::INT32 || internal_type == PhysicalType::INT64; - const bool sum_fits_in_int64 = - bounds->min > NumericLimits::Minimum() && bounds->max < NumericLimits::Maximum(); - if (has_no_overflow_variant && sum_fits_in_int64) { - expr.FunctionMutable().ReplaceImplementation(GetSumAggregateNoOverflow(internal_type)); + // Replace with fast implementation when possible + if (bounds->min > NumericLimits::Minimum() && bounds->max < NumericLimits::Maximum()) { + TryUseNoOverflowSum(expr.FunctionMutable(), false); } // Propagate stats. diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/approx_top_k.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/approx_top_k.cpp index e2ba4422f..c5115fcd0 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/approx_top_k.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/approx_top_k.cpp @@ -4,6 +4,7 @@ #include "duckdb/common/vector/struct_vector.hpp" #include "core_functions/aggregate/histogram_helpers.hpp" #include "core_functions/aggregate/holistic_functions.hpp" +#include "duckdb/common/arena_containers/arena_vector.hpp" namespace duckdb { @@ -21,21 +22,6 @@ struct ApproxTopKString { hash_t hash; }; -struct ApproxTopKHash { - std::size_t operator()(const ApproxTopKString &k) const { - return k.hash; - } -}; - -struct ApproxTopKEquality { - bool operator()(const ApproxTopKString &a, const ApproxTopKString &b) const { - return Equals::Operation(a.str, b.str); - } -}; - -template -using approx_topk_map_t = unordered_map; - // approx top k algorithm based on "A parallel space saving algorithm for frequent items and the Hurwitz zeta // distribution" arxiv link - https://arxiv.org/pdf/1401.0702 // together with the filter extension (Filtered Space-Saving) from "Estimating Top-k Destinations in Data Streams" @@ -53,37 +39,111 @@ struct ApproxTopKValue { }; struct InternalApproxTopKState { + explicit InternalApproxTopKState(ArenaAllocator &allocator) : values(allocator), filter(allocator) { + } + // the top-k data structure has two components // a list of k values sorted on "count" (i.e. values[0] has the lowest count) - // a lookup map: string_t -> idx in "values" array - unsafe_unique_array stored_values; - unsafe_vector> values; - approx_topk_map_t> lookup_map; - unsafe_vector filter; + // a lookup table: open addressing over the stored values, 0 = empty, otherwise the stored_values index + 1 + ApproxTopKValue *stored_values = nullptr; + unsafe_arena_vector> values; + unsafe_arena_vector filter; + uint32_t *lookup = nullptr; + idx_t lookup_mask = 0; + idx_t lookup_count = 0; idx_t k = 0; idx_t capacity = 0; - idx_t filter_mask; + idx_t filter_mask = 0; - void Initialize(idx_t kval) { + void Initialize(ArenaAllocator &allocator, idx_t kval) { static constexpr idx_t MONITORED_VALUES_RATIO = 3; static constexpr idx_t FILTER_RATIO = 8; D_ASSERT(values.empty()); - D_ASSERT(lookup_map.empty()); k = kval; if (k > MAX_APPROX_K) { throw InvalidInputException("Requested 'k' (%d) is bigger than accepted max (%d)", kval, MAX_APPROX_K); } capacity = kval * MONITORED_VALUES_RATIO; - stored_values = make_unsafe_uniq_array_uninitialized(capacity); + // the stored values are constructed when they are first used + stored_values = reinterpret_cast( + allocator.AllocateAligned(MaxValue(capacity, 1) * sizeof(ApproxTopKValue))); values.reserve(capacity); + // at most half of the lookup table is ever used, so probing always ends at an empty slot + const idx_t lookup_size = NextPowerOfTwo(capacity * 2); + lookup_mask = lookup_size - 1; + lookup = reinterpret_cast(allocator.AllocateAligned(lookup_size * sizeof(uint32_t))); + memset(lookup, 0, lookup_size * sizeof(uint32_t)); + // we scale the filter based on the amount of values we are monitoring idx_t filter_size = NextPowerOfTwo(capacity * FILTER_RATIO); filter_mask = filter_size - 1; filter.resize(filter_size); } + uint32_t SlotId(const ApproxTopKValue &value) const { + D_ASSERT(&value >= stored_values && &value < stored_values + capacity); + return UnsafeNumericCast(&value - stored_values); + } + + ApproxTopKValue *Find(const ApproxTopKString &key) const { + for (idx_t pos = key.hash & lookup_mask; lookup[pos] != 0; pos = (pos + 1) & lookup_mask) { + auto &entry = stored_values[lookup[pos] - 1]; + if (entry.str_val.hash == key.hash && Equals::Operation(entry.str_val.str, key.str)) { + return &entry; + } + } + return nullptr; + } + + //! Insert a value whose key is known to be absent + void Insert(ApproxTopKValue &value) { + D_ASSERT(lookup_count < capacity); + idx_t pos = value.str_val.hash & lookup_mask; + while (lookup[pos] != 0) { + pos = (pos + 1) & lookup_mask; + } + lookup[pos] = SlotId(value) + 1; + lookup_count++; + } + + //! Insert a value, returns false if its key is already present + bool TryInsert(ApproxTopKValue &value) { + idx_t pos = value.str_val.hash & lookup_mask; + for (; lookup[pos] != 0; pos = (pos + 1) & lookup_mask) { + auto &entry = stored_values[lookup[pos] - 1]; + if (entry.str_val.hash == value.str_val.hash && Equals::Operation(entry.str_val.str, value.str_val.str)) { + return false; + } + } + lookup[pos] = SlotId(value) + 1; + lookup_count++; + return true; + } + + //! Remove a value (by identity) from the lookup table, backward-shifting the entries after it + void Erase(const ApproxTopKValue &value) { + const auto id = SlotId(value) + 1; + idx_t pos = value.str_val.hash & lookup_mask; + while (lookup[pos] != id) { + if (lookup[pos] == 0) { + throw InternalException("approx_top_k: erased value is not in the lookup table"); + } + pos = (pos + 1) & lookup_mask; + } + lookup[pos] = 0; + lookup_count--; + for (idx_t next = (pos + 1) & lookup_mask; lookup[next] != 0; next = (next + 1) & lookup_mask) { + const idx_t home = stored_values[lookup[next] - 1].str_val.hash & lookup_mask; + if (((next - home) & lookup_mask) >= ((next - pos) & lookup_mask)) { + lookup[pos] = lookup[next]; + lookup[next] = 0; + pos = next; + } + } + } + static void CopyValue(ApproxTopKValue &value, const ApproxTopKString &input, ArenaAllocator &allocator) { value.str_val.hash = input.hash; if (input.str.IsInlined()) { @@ -106,7 +166,7 @@ struct InternalApproxTopKState { if (values.size() < capacity) { D_ASSERT(increment > 0); // we can always add this entry - auto &val = stored_values[values.size()]; + auto &val = *new (stored_values + values.size()) ApproxTopKValue(); val.index = values.size(); values.push_back(val); } @@ -127,13 +187,13 @@ struct InternalApproxTopKState { return; } // the filter exceeds the min value - start monitoring this value - // erase the existing entry from the map + // erase the existing entry from the lookup table (before CopyValue overwrites its hash and data) // and set the filter for the minimum value back to the current minimum value filter[value.str_val.hash & filter_mask] = value.count; - lookup_map.erase(value.str_val); + Erase(value); } CopyValue(value, input, aggr_input.allocator); - lookup_map.insert(make_pair(value.str_val, reference(value))); + Insert(value); IncrementCount(value, increment); } @@ -152,17 +212,13 @@ struct InternalApproxTopKState { void Verify() const { #ifdef DEBUG - if (values.empty()) { - D_ASSERT(lookup_map.empty()); - return; - } + D_ASSERT(lookup_count == values.size()); D_ASSERT(values.size() <= capacity); for (idx_t k = 0; k < values.size(); k++) { auto &val = values[k].get(); D_ASSERT(val.count > 0); - // verify map exists - auto entry = lookup_map.find(val.str_val); - D_ASSERT(entry != lookup_map.end()); + // verify the lookup table finds exactly this value + D_ASSERT(Find(val.str_val) == &val); // verify the index is correct D_ASSERT(val.index == k); if (k > 0) { @@ -170,35 +226,20 @@ struct InternalApproxTopKState { D_ASSERT(val.count <= values[k - 1].get().count); } } - D_ASSERT(lookup_map.size() == values.size()); #endif } }; struct ApproxTopKState { + //! nullptr if no value has been added yet InternalApproxTopKState *state; - - InternalApproxTopKState &GetState() { - if (!state) { - state = new InternalApproxTopKState(); - } - return *state; - } - - const InternalApproxTopKState &GetState() const { - if (!state) { - throw InternalException("No state available"); - } - return *state; - } }; struct ApproxTopKOperation { template static void Operation(STATE &aggr_state, const TYPE &input, AggregateInputData &aggr_input, const Vector &top_k_vector, idx_t offset, idx_t count) { - auto &state = aggr_state.GetState(); - if (state.values.empty()) { + if (!aggr_state.state || aggr_state.state->values.empty()) { static constexpr int64_t MAX_APPROX_K = 1000000; // not initialized yet - initialize the K value and set all counters to 0 auto top_k_format = top_k_vector.Values(); @@ -213,13 +254,18 @@ struct ApproxTopKOperation { if (kval >= MAX_APPROX_K) { throw InvalidInputException("Invalid input for approx_top_k: k value must be < %d", MAX_APPROX_K); } - state.Initialize(UnsafeNumericCast(kval)); + // an existing empty state is only reused if its k matches + if (!aggr_state.state || aggr_state.state->k != UnsafeNumericCast(kval)) { + aggr_state.state = aggr_input.allocator.Make(aggr_input.allocator); + aggr_state.state->Initialize(aggr_input.allocator, UnsafeNumericCast(kval)); + } } + auto &state = *aggr_state.state; ApproxTopKString topk_string(input, Hash(input)); - auto entry = state.lookup_map.find(topk_string); - if (entry != state.lookup_map.end()) { + auto entry = state.Find(topk_string); + if (entry) { // the input is monitored - increment the count - state.IncrementCount(entry->second.get()); + state.IncrementCount(*entry); } else { // the input is not monitored - replace the first entry with the current entry and increment state.InsertOrReplaceEntry(topk_string, aggr_input); @@ -228,39 +274,37 @@ struct ApproxTopKOperation { template static void Combine(const STATE &aggr_source, STATE &aggr_target, AggregateInputData &aggr_input) { - if (!aggr_source.state) { + if (!aggr_source.state || aggr_source.state->values.empty()) { // source state is empty return; } - auto &source = aggr_source.GetState(); - auto &target = aggr_target.GetState(); - if (source.values.empty()) { - // source is empty - return; - } + auto &source = *aggr_source.state; source.Verify(); auto min_source = source.values.size() < source.capacity ? 0 : source.values.back().get().count; idx_t min_target; - if (target.values.empty()) { + if (!aggr_target.state || aggr_target.state->values.empty()) { min_target = 0; - target.Initialize(source.k); + aggr_target.state = aggr_input.allocator.Make(aggr_input.allocator); + aggr_target.state->Initialize(aggr_input.allocator, source.k); } else { - if (source.k != target.k) { + if (source.k != aggr_target.state->k) { throw NotImplementedException("Approx Top K - cannot combine approx_top_K with different k values. " "K values must be the same for all entries within the same group"); } - min_target = target.values.size() < target.capacity ? 0 : target.values.back().get().count; + auto &target_values = aggr_target.state->values; + min_target = target_values.size() < aggr_target.state->capacity ? 0 : target_values.back().get().count; } + auto &target = *aggr_target.state; // for all entries in target // check if they are tracked in source // if they do - add the tracked count // if they do not - add the minimum count for (idx_t target_idx = 0; target_idx < target.values.size(); target_idx++) { auto &val = target.values[target_idx].get(); - auto source_entry = source.lookup_map.find(val.str_val); + auto source_entry = source.Find(val.str_val); idx_t increment = min_source; - if (source_entry != source.lookup_map.end()) { - increment = source_entry->second.get().count; + if (source_entry) { + increment = source_entry->count; } if (increment == 0) { continue; @@ -270,8 +314,7 @@ struct ApproxTopKOperation { // now for each entry in source, if it is not tracked by the target, at the target minimum for (auto &source_entry : source.values) { auto &source_val = source_entry.get(); - auto target_entry = target.lookup_map.find(source_val.str_val); - if (target_entry != target.lookup_map.end()) { + if (target.Find(source_val.str_val)) { // already tracked - no need to add anything continue; } @@ -302,11 +345,6 @@ struct ApproxTopKOperation { target.Verify(); } - template - static void Destroy(STATE &state, AggregateInputData &aggr_input_data) { - delete state.state; - } - static bool IgnoreNull() { return true; } @@ -344,10 +382,11 @@ void ApproxTopKFinalize(Vector &state_vector, AggregateFinalizeInputData &, Vect idx_t new_entries = 0; // figure out how much space we need for (idx_t i = 0; i < count; i++) { - auto &state = states[i].GetValue()->GetState(); - if (state.values.empty()) { + auto state_ptr = states[i].GetValue()->state; + if (!state_ptr || state_ptr->values.empty()) { continue; } + auto &state = *state_ptr; // get up to k values for each state // this can be less of fewer unique values were found new_entries += MinValue(state.values.size(), state.k); @@ -359,11 +398,12 @@ void ApproxTopKFinalize(Vector &state_vector, AggregateFinalizeInputData &, Vect idx_t current_offset = old_len; for (idx_t i = 0; i < count; i++) { - auto &state = states[i].GetValue()->GetState(); - if (state.values.empty()) { + auto state_ptr = states[i].GetValue()->state; + if (!state_ptr || state_ptr->values.empty()) { list_entries.WriteNull(); continue; } + auto &state = *state_ptr; list_entry_t list_entry; list_entry.offset = current_offset; for (idx_t val_idx = 0; val_idx < MinValue(state.values.size(), state.k); val_idx++) { @@ -514,9 +554,8 @@ void ApproxTopKImportState(AggregateImportInputData &input) { FlatVector::IsNull(filter_lists, i)) { throw InvalidInputException("Invalid approx_top_k state - the k, values and filter cannot be NULL"); } - auto internal_state = make_uniq(); - auto &target = *internal_state; - target.Initialize(k_data[i]); + auto &target = *allocator.Make(allocator); + target.Initialize(allocator, k_data[i]); if (value_entries[i].length > target.capacity || filter_entries[i].length != target.filter.size()) { throw InvalidInputException("Invalid approx_top_k state - " "the values/filter sizes do not match the k value"); @@ -529,16 +568,14 @@ void ApproxTopKImportState(AggregateImportInputData &input) { throw InvalidInputException("Invalid approx_top_k state - the state values cannot be NULL"); } - auto &val = target.stored_values[target.values.size()]; + auto &val = *new (target.stored_values + target.values.size()) ApproxTopKValue(); val.index = target.values.size(); target.values.push_back(val); const auto &str_val = value_strings[sel_idx]; ApproxTopKString topk_string(str_val, Hash(str_val)); InternalApproxTopKState::CopyValue(val, topk_string, allocator); - const bool inserted = - target.lookup_map.insert(make_pair(val.str_val, reference(val))).second; - if (!inserted) { + if (!target.TryInsert(val)) { throw InvalidInputException("Invalid approx_top_k state - the state values must be unique"); } if (FlatVector::IsNull(value_fields[1], idx)) { @@ -565,7 +602,7 @@ void ApproxTopKImportState(AggregateImportInputData &input) { } } target.Verify(); - state.state = internal_state.release(); + state.state = ⌖ } } @@ -599,11 +636,13 @@ AggregateFunction ApproxTopKFun::GetFunction() { auto fun = AggregateFunction("approx_top_k", {}, LogicalType::LIST(LogicalType::ANY), AggregateFunction::StateSize, AggregateFunction::StateInitialize, ApproxTopKUpdate, AggregateFunction::StateCombine, ApproxTopKFinalize, - nullptr, ApproxTopKBind, AggregateFunction::StateDestroy); + nullptr, ApproxTopKBind, nullptr); fun.GetSignature().AddParameter("val", LogicalTypeId::ANY).AddParameter("k", LogicalType::BIGINT); fun.SetStateExportCallbacks(ApproxTopKGetStateType, ApproxTopKExportState, ApproxTopKImportState); fun.SetFallible(); // the update callback rejects NULL and out-of-range k values at runtime + // combine copies the source values into the caller's arena + fun.SetCombineSourceRetention(AggregateCombineSourceRetention::NEVER_RETAINS); return fun; } diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp index bd1389a2c..3e21637ff 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp @@ -141,7 +141,7 @@ struct ApproximateQuantileBindData : public FunctionData { return true; } - static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, + static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundAggregateFunction &function) { auto &bind_data = bind_data_p->Cast(); serializer.WriteProperty(100, "quantiles", bind_data.quantiles); diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/lttb.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/lttb.cpp index d1941d600..ccb0a15b2 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/lttb.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/lttb.cpp @@ -365,7 +365,8 @@ auto LTTBBind(BindAggregateFunctionInput &input) -> unique_ptr { return make_uniq(NumericCast(n)); } -auto LTTBSerialize(Serializer &ser, const optional_ptr bdata, const BoundAggregateFunction &) -> void { +auto LTTBSerialize(Serializer &ser, const optional_ptr bdata, const BoundAggregateFunction &) + -> void { auto &bind_data = bdata->Cast(); ser.WriteProperty(100, "n", bind_data.n); } diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp index 1a92a758d..363fcfe68 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/mode.cpp @@ -2,6 +2,7 @@ #include "core_functions/aggregate/holistic_functions.hpp" #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry/aggregate_function_catalog_entry.hpp" +#include "duckdb/common/arena_containers/arena_sql_value_map.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/operator/comparison_operators.hpp" #include "duckdb/common/owning_string_map.hpp" @@ -105,13 +106,10 @@ struct ModeAttr { template struct ModeStandard { - using MAP_TYPE = sql_value_map_t; + using MAP_TYPE = arena_sql_value_map_t; - static MAP_TYPE *CreateEmpty(ArenaAllocator &) { - return new MAP_TYPE(); - } - static MAP_TYPE *CreateEmpty(Allocator &) { - return new MAP_TYPE(); + static MAP_TYPE *CreateEmpty(ArenaAllocator &allocator) { + return allocator.Make(typename MAP_TYPE::allocator_type(allocator)); } static ModeAttr &GetOrCreate(MAP_TYPE &map, const T &key, ArenaAllocator &) { @@ -127,9 +125,9 @@ struct ModeStandard { return Equals::Operation(left, right); } - static T *Update(T *mode, idx_t &, const T &key, AggregateInputData &) { + static T *Update(T *mode, idx_t &, const T &key, AggregateInputData &aggr_input_data) { if (!mode) { - mode = new T(key); + mode = aggr_input_data.allocator.Make(key); } *mode = key; @@ -138,13 +136,10 @@ struct ModeStandard { }; struct ModeString { - using MAP_TYPE = OwningStringMap; + using MAP_TYPE = ArenaOwningStringMap; - static MAP_TYPE *CreateEmpty(ArenaAllocator &) { - return new MAP_TYPE(); - } - static MAP_TYPE *CreateEmpty(Allocator &allocator) { - return new MAP_TYPE(allocator); + static MAP_TYPE *CreateEmpty(ArenaAllocator &allocator) { + return allocator.Make(allocator); } static ModeAttr &GetOrCreate(MAP_TYPE &map, const string_t &key, ArenaAllocator &allocator) { @@ -164,7 +159,7 @@ struct ModeString { AggregateInputData &aggr_input_data) { if (key.IsInlined()) { if (!mode) { - mode = new string_t(nullptr, 0); + mode = aggr_input_data.allocator.Make(nullptr, 0); } *mode = key; alloc_size = 0; @@ -182,7 +177,7 @@ struct ModeString { alloc_size = NextPowerOfTwo(len); ptr = char_ptr_cast(aggr_input_data.allocator.Allocate(alloc_size)); if (!mode) { - mode = new string_t(nullptr, 0); + mode = aggr_input_data.allocator.Make(nullptr, 0); } } memcpy(ptr, key.GetData(), len); @@ -210,25 +205,17 @@ struct ModeState { //! The collection being read const ColumnDataCollection *inputs; //! The state used for reading the collection on this thread - ColumnDataScanState *scan = nullptr; + unique_ptr scan; + //! The arena of the frequency map in the window path, reset when the frames are recomputed + unique_ptr window_arena; //! The data chunk paged into into DataChunk page; //! Cell access into the page, rebuilt per page load - scans can return constant and dictionary vectors unique_ptr> values; - ~ModeState() { - if (frequency_map) { - delete frequency_map; - } - delete mode; - if (scan) { - delete scan; - } - } - void InitializePage(const WindowPartitionInput &partition) { if (!scan) { - scan = new ColumnDataScanState(); + scan = make_uniq(); } if (page.ColumnCount() == 0) { D_ASSERT(partition.inputs); @@ -269,7 +256,12 @@ struct ModeState { void Reset() { if (frequency_map) { - frequency_map->clear(); + // rebuild the map instead of clearing it, the arena would retain the erased nodes + D_ASSERT(window_arena); + const auto previous_size = frequency_map->size(); + window_arena->Reset(); + frequency_map = TYPE_OP::CreateEmpty(*window_arena); + frequency_map->reserve(previous_size); } nonzero = 0; count = 0; @@ -278,7 +270,7 @@ struct ModeState { void ModeAdd(idx_t row, AggregateInputData &aggr_input_data) { const auto &key = GetCell(row); - auto &attr = (*frequency_map)[key]; + auto &attr = TYPE_OP::GetOrCreate(*frequency_map, key, *window_arena); auto new_count = (attr.count += 1); nonzero += size_t(new_count == 1); if (new_count > count) { @@ -293,7 +285,7 @@ struct ModeState { void ModeRm(idx_t frame) { const auto &key = GetCell(frame); - auto &attr = (*frequency_map)[key]; + auto &attr = TYPE_OP::GetOrCreate(*frequency_map, key, *window_arena); auto old_count = attr.count; nonzero -= size_t(old_count == 1); @@ -400,8 +392,14 @@ struct BaseModeFunction { if (!source.frequency_map) { return; } + auto &allocator = aggr_input_data.allocator; if (!target.frequency_map) { - target.frequency_map = TYPE_OP::CreateEmpty(aggr_input_data.allocator); + target.frequency_map = TYPE_OP::CreateEmpty(allocator); + target.frequency_map->reserve(source.frequency_map->size()); + } else if (&target.frequency_map->get_allocator().GetAllocator() != &allocator) { + // Copied states can share a sink arena across partitions being combined in parallel. + target.frequency_map = allocator.Make(*target.frequency_map, allocator); + target.frequency_map->reserve(target.frequency_map->size() + source.frequency_map->size()); } for (auto &val : *source.frequency_map) { auto &i = TYPE_OP::GetOrCreate(*target.frequency_map, val.first, aggr_input_data.allocator); @@ -505,8 +503,11 @@ struct ModeFunction : TypedModeFunction { using Updater = UpdateWindowState; Updater updater(state, included, aggr_input_data); + if (!state.window_arena) { + state.window_arena = make_uniq(aggr_input_data.allocator.GetUnderlyingAllocator()); + } if (!state.frequency_map) { - state.frequency_map = TYPE_OP::CreateEmpty(Allocator::DefaultAllocator()); + state.frequency_map = TYPE_OP::CreateEmpty(*state.window_arena); } const size_t tau_inverse = 4; // tau==0.25 for (idx_t rid = 0; rid < count; ++rid) { diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp index 4db768ee4..f53fe9761 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp @@ -123,7 +123,7 @@ bool QuantileBindData::Equals(const FunctionData &other_p) const { return desc == other.desc && quantiles == other.quantiles && order == other.order; } -void QuantileBindData::Serialize(Serializer &serializer, const optional_ptr bind_data_p, +void QuantileBindData::Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundAggregateFunction &function) { auto &bind_data = bind_data_p->Cast(); vector raw; diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp index 511dc3790..404fd7725 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp @@ -84,7 +84,7 @@ struct ReservoirQuantileBindData : public FunctionData { return quantiles == other.quantiles && sample_size == other.sample_size && decimal_type == other.decimal_type; } - static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, + static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundAggregateFunction &function) { auto &bind_data = bind_data_p->Cast(); serializer.WriteProperty(100, "quantiles", bind_data.quantiles); diff --git a/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp b/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp index 078ea887c..65c71ce06 100644 --- a/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp +++ b/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp @@ -2,6 +2,7 @@ #include "core_functions/aggregate/nested_functions.hpp" #include "core_functions/scalar/generic_functions.hpp" #include "duckdb/common/algorithm.hpp" +#include "duckdb/common/arena_containers/arena_vector.hpp" #include "duckdb/common/smaller_binary.hpp" #include "duckdb/common/types/vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" @@ -15,23 +16,13 @@ namespace duckdb { namespace { +//! All state memory is allocated from the aggregate's arena, so the state needs no destructor template struct HistogramBinState { using TYPE = T; - unsafe_vector *bin_boundaries; - unsafe_vector *counts; - - void Destroy() { - if (bin_boundaries) { - delete bin_boundaries; - bin_boundaries = nullptr; - } - if (counts) { - delete counts; - counts = nullptr; - } - } + unsafe_arena_vector *bin_boundaries; + unsafe_arena_vector *counts; bool IsSet() { return bin_boundaries; @@ -39,8 +30,9 @@ struct HistogramBinState { template void InitializeBins(Vector &bin_vector, idx_t pos, AggregateInputData &aggr_input) { - bin_boundaries = new unsafe_vector(); - counts = new unsafe_vector(); + auto &allocator = aggr_input.allocator; + auto &new_boundaries = *allocator.Make>(allocator); + auto &new_counts = *allocator.Make>(allocator); auto bin_counts = bin_vector.Values(); auto bin_entry = bin_counts[pos]; if (!bin_entry.IsValid()) { @@ -53,34 +45,31 @@ struct HistogramBinState { auto extra_state = OP::CreateExtraState(); OP::PrepareData(bin_child, extra_state, bin_child_data); - bin_boundaries->reserve(bin_list.length); + new_boundaries.reserve(bin_list.length); for (idx_t i = 0; i < bin_list.length; i++) { auto bin_child_idx = bin_child_data.sel->get_index(bin_list.offset + i); if (!bin_child_data.validity.RowIsValid(bin_child_idx)) { throw BinderException("Histogram bin entry cannot be NULL"); } - bin_boundaries->push_back(OP::template ExtractValue(bin_child_data, bin_list.offset + i, aggr_input)); + new_boundaries.push_back(OP::template ExtractValue(bin_child_data, bin_list.offset + i, aggr_input)); } // sort the bin boundaries - std::sort(bin_boundaries->begin(), bin_boundaries->end()); + std::sort(new_boundaries.begin(), new_boundaries.end()); // ensure there are no duplicate bin boundaries - for (idx_t i = 1; i < bin_boundaries->size(); i++) { - if (Equals::Operation((*bin_boundaries)[i - 1], (*bin_boundaries)[i])) { - bin_boundaries->erase_at(i); + for (idx_t i = 1; i < new_boundaries.size(); i++) { + if (Equals::Operation(new_boundaries[i - 1], new_boundaries[i])) { + new_boundaries.erase_at(i); i--; } } - counts->resize(bin_boundaries->size() + 1); + new_counts.resize(new_boundaries.size() + 1); + bin_boundaries = &new_boundaries; + counts = &new_counts; } }; struct HistogramBinFunction { - template - static void Destroy(STATE &state, AggregateInputData &aggr_input_data) { - state.Destroy(); - } - static bool IgnoreNull() { return true; } @@ -92,11 +81,15 @@ struct HistogramBinFunction { return; } if (!target.bin_boundaries) { - // target does not have bin boundaries - copy everything over - target.bin_boundaries = new unsafe_vector(); - target.counts = new unsafe_vector(); - *target.bin_boundaries = *source.bin_boundaries; - *target.counts = *source.counts; + // target does not have bin boundaries - copy everything over into the caller's arena + // (element-wise: copy-assigning would adopt the source's arena) + auto &allocator = input_data.allocator; + auto &boundaries = *allocator.Make>(allocator); + auto &counts = *allocator.Make>(allocator); + boundaries.insert(boundaries.end(), source.bin_boundaries->begin(), source.bin_boundaries->end()); + counts.insert(counts.end(), source.counts->begin(), source.counts->end()); + target.bin_boundaries = &boundaries; + target.counts = &counts; } else { // both source and target have bin boundaries if (*target.bin_boundaries != *source.bin_boundaries) { @@ -119,7 +112,7 @@ struct HistogramRange { static constexpr bool EXACT = false; template - static idx_t GetBin(T value, const unsafe_vector &bin_boundaries) { + static idx_t GetBin(T value, const unsafe_arena_vector &bin_boundaries) { auto entry = std::lower_bound(bin_boundaries.begin(), bin_boundaries.end(), value); return UnsafeNumericCast(entry - bin_boundaries.begin()); } @@ -129,7 +122,7 @@ struct HistogramExact { static constexpr bool EXACT = true; template - static idx_t GetBin(T value, const unsafe_vector &bin_boundaries) { + static idx_t GetBin(T value, const unsafe_arena_vector &bin_boundaries) { auto entry = std::lower_bound(bin_boundaries.begin(), bin_boundaries.end(), value); if (entry == bin_boundaries.end() || !(*entry == value)) { // entry not found - return last bucket @@ -345,11 +338,11 @@ AggregateFunction GetHistogramBinFunction(const LogicalType &type) { const char *function_name = HIST::EXACT ? "histogram_exact" : "histogram"; auto struct_type = LogicalType::MAP(type, LogicalType::UBIGINT); - AggregateFunction function( - function_name, {}, struct_type, AggregateFunction::StateSize, - AggregateFunction::StateInitialize, HistogramBinUpdateFunction, - AggregateFunction::StateCombine, HistogramBinFinalizeFunction, nullptr, - nullptr, AggregateFunction::StateDestroy); + AggregateFunction function(function_name, {}, struct_type, AggregateFunction::StateSize, + AggregateFunction::StateInitialize, + HistogramBinUpdateFunction, + AggregateFunction::StateCombine, + HistogramBinFinalizeFunction, nullptr, nullptr, nullptr); function.GetSignature().AddParameter("arg", type).AddParameter("bins", LogicalType::LIST(type)); return function; } diff --git a/src/duckdb/extension/core_functions/aggregate/nested/histogram.cpp b/src/duckdb/extension/core_functions/aggregate/nested/histogram.cpp index c0abf5a74..3f17c8612 100644 --- a/src/duckdb/extension/core_functions/aggregate/nested/histogram.cpp +++ b/src/duckdb/extension/core_functions/aggregate/nested/histogram.cpp @@ -2,6 +2,7 @@ #include "core_functions/aggregate/nested_functions.hpp" #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry/aggregate_function_catalog_entry.hpp" +#include "duckdb/common/arena_containers/arena_sql_value_map.hpp" #include "duckdb/common/owning_string_map.hpp" #include "duckdb/common/smaller_binary.hpp" #include "duckdb/common/string_map_set.hpp" @@ -43,13 +44,6 @@ static unique_ptr BindScalar(ClientContext &context, const char *nam template struct HistogramFunction { - template - static void Destroy(STATE &state, AggregateInputData &) { - if (state.hist) { - delete state.hist; - } - } - static bool IgnoreNull() { return true; } @@ -59,8 +53,12 @@ struct HistogramFunction { if (!source.hist) { return; } + auto &allocator = input_data.allocator; if (!target.hist) { - target.hist = MAP_TYPE::CreateEmpty(input_data.allocator); + target.hist = MAP_TYPE::CreateEmpty(allocator); + } else if (&target.hist->get_allocator().GetAllocator() != &allocator) { + // Copied states can share a sink arena across partitions being combined in parallel. + target.hist = allocator.Make(*target.hist, allocator); } for (auto &entry : *source.hist) { MAP_TYPE::GetOrCreate(*target.hist, entry.first, input_data.allocator) += entry.second; @@ -72,8 +70,8 @@ template struct DefaultMapType { using MAP_TYPE = TYPE; - static TYPE *CreateEmpty(ArenaAllocator &) { - return new TYPE(); + static TYPE *CreateEmpty(ArenaAllocator &allocator) { + return allocator.Make(typename TYPE::allocator_type(allocator)); } template @@ -86,8 +84,8 @@ template struct StringMapType { using MAP_TYPE = TYPE; - static TYPE *CreateEmpty(ArenaAllocator &) { - return new TYPE(); + static TYPE *CreateEmpty(ArenaAllocator &allocator) { + return allocator.Make(allocator); } static typename TYPE::mapped_type &GetOrCreate(TYPE &map, const string_t &key, ArenaAllocator &allocator) { @@ -176,11 +174,11 @@ AggregateFunction GetHistogramFunction(const LogicalType &type) { using HIST_FUNC = HistogramFunction; auto struct_type = LogicalType::MAP(type, LogicalType::UBIGINT); - auto function = AggregateFunction( - "histogram", {}, struct_type, AggregateFunction::StateSize, - AggregateFunction::StateInitialize, HistogramUpdateFunction, - AggregateFunction::StateCombine, HistogramFinalizeFunction, nullptr, - nullptr, AggregateFunction::StateDestroy); + auto function = AggregateFunction("histogram", {}, struct_type, AggregateFunction::StateSize, + AggregateFunction::StateInitialize, + HistogramUpdateFunction, + AggregateFunction::StateCombine, + HistogramFinalizeFunction, nullptr, nullptr, nullptr); function.GetSignature().AddParameter("arg", type); function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); return function; @@ -194,17 +192,17 @@ AggregateFunction GetMapTypeInternal(const LogicalType &type) { template AggregateFunction GetMapType(const LogicalType &type) { if (IS_ORDERED) { - return GetMapTypeInternal>>(type); + return GetMapTypeInternal>>(type); } - return GetMapTypeInternal>>(type); + return GetMapTypeInternal>>(type); } template AggregateFunction GetStringMapType(const LogicalType &type) { if (IS_ORDERED) { - return GetMapTypeInternal>>(type); + return GetMapTypeInternal>>(type); } else { - return GetMapTypeInternal>>(type); + return GetMapTypeInternal>>(type); } } diff --git a/src/duckdb/extension/core_functions/function_list.cpp b/src/duckdb/extension/core_functions/function_list.cpp index 06bf269b4..f3a50e279 100644 --- a/src/duckdb/extension/core_functions/function_list.cpp +++ b/src/duckdb/extension/core_functions/function_list.cpp @@ -165,7 +165,7 @@ static const StaticFunctionDefinition core_functions[] = { DUCKDB_SCALAR_FUNCTION(DegreesFun), DUCKDB_SCALAR_FUNCTION_ALIAS(Editdist3Fun), DUCKDB_SCALAR_FUNCTION_ALIAS(ElementAtFun), - DUCKDB_SCALAR_FUNCTION(EncodeFun), + DUCKDB_SCALAR_FUNCTION_SET(EncodeFun), DUCKDB_AGGREGATE_FUNCTION_SET(EntropyFun), DUCKDB_SCALAR_FUNCTION(EnumCodeFun), DUCKDB_SCALAR_FUNCTION(EnumFirstFun), diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/histogram_helpers.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/histogram_helpers.hpp index e92640775..bd5352ede 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/histogram_helpers.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/histogram_helpers.hpp @@ -82,9 +82,14 @@ struct HistogramGenericFunctor : HistogramStringFunctorBase { OrderModifiers modifiers(OrderType::ASCENDING, OrderByNullType::NULLS_LAST); extra_state.Reserve(input.size()); CreateSortKeyHelpers::CreateSortKey(input, modifiers, extra_state); - input.Flatten(); extra_state.Flatten(); - FlatVector::ValidityMutable(extra_state).Initialize(FlatVector::Validity(input)); + auto input_validity = input.Validity(); + auto &validity = FlatVector::ValidityMutable(extra_state); + for (idx_t i = 0; i < input_validity.size(); i++) { + if (!input_validity.IsValid(i)) { + validity.SetInvalid(i); + } + } extra_state.ToUnifiedFormat(result); } }; diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_helpers.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_helpers.hpp index 88752e395..b318377b3 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_helpers.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_helpers.hpp @@ -57,7 +57,7 @@ struct QuantileBindData : public FunctionData { unique_ptr Copy() const override; bool Equals(const FunctionData &other_p) const override; - static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, + static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundAggregateFunction &function); static unique_ptr Deserialize(Deserializer &deserializer, BoundAggregateFunction &function); diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp index a3671d203..e080945cf 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp @@ -28,7 +28,7 @@ struct FlattenedQuantileValues : FunctionLocalState { FlattenedQuantileValues() : capacity(0) { } - static unique_ptr Init(const BoundAggregateFunction &, optional_ptr) { + static unique_ptr Init(const BoundAggregateFunction &, optional_ptr) { return make_uniq(); } diff --git a/src/duckdb/extension/core_functions/include/core_functions/scalar/blob_functions.hpp b/src/duckdb/extension/core_functions/include/core_functions/scalar/blob_functions.hpp index a50a467e4..9ba04c22f 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/scalar/blob_functions.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/scalar/blob_functions.hpp @@ -18,8 +18,8 @@ namespace duckdb { struct DecodeFun { static constexpr const char *Name = "decode"; static constexpr const char *Parameters = "blob,error_option"; - static constexpr const char *Description = "Converts `blob` to `VARCHAR`. Invalid UTF-8 is handled based on the error behavior argument. Can be 'strict' (default, fail), 'replace' to replace invalid characters with '?', or 'ignore' to skip invalid characters."; - static constexpr const char *Example = "decode('\\xC3\\xBC'::BLOB)\002decode('\\xA0'::BLOB, 'replace')\002decode('\\xA0'::BLOB, 'ignore')"; + static constexpr const char *Description = "Converts `blob` to `VARCHAR`. Invalid UTF-8 is handled based on the error behavior argument. Can be 'strict' (default, fail), 'replace' to replace invalid characters with '?', or 'ignore' to skip invalid characters. If the second argument is the name of an encoding (e.g. 'latin-1', see `system.encodings`), `blob` is decoded from that encoding instead."; + static constexpr const char *Example = "decode('\\xC3\\xBC'::BLOB)\002decode('\\xA0'::BLOB, 'replace')\002decode('\\xA0'::BLOB, 'ignore')\002decode('\\xFC'::BLOB, 'latin-1')"; static constexpr const char *Categories = "blob"; static ScalarFunctionSet GetFunctions(); @@ -27,12 +27,12 @@ struct DecodeFun { struct EncodeFun { static constexpr const char *Name = "encode"; - static constexpr const char *Parameters = "string"; - static constexpr const char *Description = "Converts the `string` to `BLOB`. Converts UTF-8 characters into literal encoding."; - static constexpr const char *Example = "encode('my_string_with_ü')"; + static constexpr const char *Parameters = "string,encoding"; + static constexpr const char *Description = "Converts the `string` to `BLOB`. Converts UTF-8 characters into literal encoding, or into the named encoding (e.g. 'latin-1', see `system.encodings`)."; + static constexpr const char *Example = "encode('my_string_with_ü')\002encode('my_string_with_ü', 'latin-1')"; static constexpr const char *Categories = "blob"; - static ScalarFunction GetFunction(); + static ScalarFunctionSet GetFunctions(); }; struct FromBase64Fun { diff --git a/src/duckdb/extension/core_functions/lambda_functions.cpp b/src/duckdb/extension/core_functions/lambda_functions.cpp index af2d4c606..1c964e6e5 100644 --- a/src/duckdb/extension/core_functions/lambda_functions.cpp +++ b/src/duckdb/extension/core_functions/lambda_functions.cpp @@ -225,7 +225,7 @@ static void ExecuteExpression(const idx_t elem_cnt, const LambdaFunctions::Colum // ListLambdaBindData //===--------------------------------------------------------------------===// -void ListLambdaBindData::Serialize(Serializer &serializer, const optional_ptr bind_data_p, +void ListLambdaBindData::Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundScalarFunction &) { auto &bind_data = bind_data_p->Cast(); serializer.WriteProperty(100, "return_type", bind_data.return_type); @@ -327,7 +327,7 @@ static void ExecuteLambda(DataChunk &args, ExpressionState &state, Vector &resul for (idx_t child_idx = 0; child_idx < list_entry.length; child_idx++) { // reached STANDARD_VECTOR_SIZE elements if (elem_cnt == STANDARD_VECTOR_SIZE) { - state.GetContext().InterruptCheck(); + state.GetContext().FastInterruptCheck(); execute_info.lambda_chunk.Reset(); ExecuteExpression(elem_cnt, child_info, info.column_infos, index_vector, execute_info); auto &lambda_vector = execute_info.lambda_chunk.data[0]; diff --git a/src/duckdb/extension/core_functions/scalar/blob/encode.cpp b/src/duckdb/extension/core_functions/scalar/blob/encode.cpp index 9eb915131..3fdc97c92 100644 --- a/src/duckdb/extension/core_functions/scalar/blob/encode.cpp +++ b/src/duckdb/extension/core_functions/scalar/blob/encode.cpp @@ -1,5 +1,6 @@ #include "core_functions/scalar/blob_functions.hpp" #include "utf8proc_wrapper.hpp" +#include "duckdb/function/encoding_function.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/exception/conversion_exception.hpp" @@ -102,12 +103,33 @@ void BinaryDecodeFunction(DataChunk &args, ExpressionState &state, Vector &resul StringVector::AddHeapReference(result, args.data[0]); } +unique_ptr BindEncodeExpression(FunctionBindExpressionInput &input) { + return EncodingFunction::BindCall(input.context, input.children, true); +} + +unique_ptr BindDecodeExpression(FunctionBindExpressionInput &input) { + return EncodingFunction::BindCall(input.context, input.children, false); +} + } // namespace -ScalarFunction EncodeFun::GetFunction() { - ScalarFunction func({}, LogicalType::BLOB, EncodeFunction); - func.GetSignature().AddParameter("string", LogicalType::VARCHAR); - return func; +ScalarFunctionSet EncodeFun::GetFunctions() { + ScalarFunctionSet encode("encode"); + + ScalarFunction unary_function({}, LogicalType::BLOB, EncodeFunction); + unary_function.GetSignature().AddParameter("string", LogicalType::VARCHAR); + + // the encoding is bound to the function of the encoding in system.encodings + ScalarFunction binary_function({}, LogicalType::BLOB, nullptr); + binary_function.GetSignature() + .AddParameter("string", LogicalType::VARCHAR) + .AddParameter("encoding", LogicalType::VARCHAR); + binary_function.SetBindExpressionCallback(BindEncodeExpression); + binary_function.SetFallible(); + + encode.AddFunction(unary_function); + encode.AddFunction(binary_function); + return encode; } ScalarFunctionSet DecodeFun::GetFunctions() { @@ -121,6 +143,8 @@ ScalarFunctionSet DecodeFun::GetFunctions() { .AddParameter("blob", LogicalType::BLOB) .AddParameter("error_option", LogicalType::VARCHAR); + binary_function.SetBindExpressionCallback(BindDecodeExpression); + decode.AddFunction(unary_function); decode.AddFunction(binary_function); decode.SetFallible(); diff --git a/src/duckdb/extension/core_functions/scalar/date/date_part.cpp b/src/duckdb/extension/core_functions/scalar/date/date_part.cpp index 01329407a..b5df76a40 100644 --- a/src/duckdb/extension/core_functions/scalar/date/date_part.cpp +++ b/src/duckdb/extension/core_functions/scalar/date/date_part.cpp @@ -1,5 +1,5 @@ -#include "duckdb/parser/expression/function_expression.hpp" #include "duckdb/common/vector/struct_vector.hpp" +#include "duckdb/function/builtin_function_lookup.hpp" #include "core_functions/scalar/date_functions.hpp" #include "duckdb/common/case_insensitive_map.hpp" #include "duckdb/common/enum_util.hpp" @@ -117,20 +117,6 @@ unique_ptr PropagateSimpleDatePartStatistics(vector -struct DateCacheLocalState : public FunctionLocalState { - explicit DateCacheLocalState() { - } - - DateLookupCache cache; -}; - -template -unique_ptr InitDateCacheLocalState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { - return make_uniq>(); -} - struct DatePart { struct AsTime { template @@ -944,9 +930,8 @@ struct DatePart { template void DatePartCachedFunction(DataChunk &args, ExpressionState &state, Vector &result) { - auto &lstate = ExecuteFunctionState::GetFunctionState(state)->Cast>(); - UnaryExecutor::Execute(args.data[0], result, - [&](T input) { return lstate.cache.ExtractElement(input); }); + auto &cache = DateLookupCache::Get(); + UnaryExecutor::Execute(args.data[0], result, [&](T input) { return cache.ExtractElement(input); }); } template <> @@ -2165,213 +2150,35 @@ void DatePartFunction(DataChunk &args, ExpressionState &state, Vector &result) { }); } -template -static scalar_function_t DatePartUnaryCallback(LogicalTypeId type) { - scalar_function_t result = nullptr; - switch (type) { - case LogicalType::TIMESTAMP: - case LogicalType::TIMESTAMP_S: - case LogicalType::TIMESTAMP_MS: - result = DatePart::UnaryFunction; - break; - case LogicalType::TIMESTAMP_NS: - result = DatePart::UnaryFunction; - break; - case LogicalType::DATE: - result = DatePart::UnaryFunction; - break; - case LogicalType::INTERVAL: - result = DatePart::UnaryFunction; - break; - case LogicalType::TIME: - result = DatePart::UnaryFunction; - break; - case LogicalType::TIME_NS: - result = DatePart::UnaryFunction; - break; - case LogicalType::TIME_TZ: - result = DatePart::UnaryFunction; - break; - default: - throw NotImplementedException("Unsupported temporal type for DATE_PART"); - } - return result; -} - -static scalar_function_t DatePartUnaryCallback(DatePartSpecifier part_code, LogicalTypeId type) { - switch (part_code) { - case DatePartSpecifier::YEAR: - return DatePartUnaryCallback(type); - case DatePartSpecifier::MONTH: - return DatePartUnaryCallback(type); - case DatePartSpecifier::DAY: - return DatePartUnaryCallback(type); - case DatePartSpecifier::DECADE: - return DatePartUnaryCallback(type); - case DatePartSpecifier::CENTURY: - return DatePartUnaryCallback(type); - case DatePartSpecifier::MILLENNIUM: - return DatePartUnaryCallback(type); - case DatePartSpecifier::QUARTER: - return DatePartUnaryCallback(type); - case DatePartSpecifier::DOW: - return DatePartUnaryCallback(type); - case DatePartSpecifier::ISODOW: - return DatePartUnaryCallback(type); - case DatePartSpecifier::DOY: - return DatePartUnaryCallback(type); - case DatePartSpecifier::WEEK: - return DatePartUnaryCallback(type); - case DatePartSpecifier::ISOYEAR: - return DatePartUnaryCallback(type); - case DatePartSpecifier::YEARWEEK: - return DatePartUnaryCallback(type); - case DatePartSpecifier::MICROSECONDS: - return DatePartUnaryCallback(type); - case DatePartSpecifier::MILLISECONDS: - return DatePartUnaryCallback(type); - case DatePartSpecifier::SECOND: - return DatePartUnaryCallback(type); - case DatePartSpecifier::MINUTE: - return DatePartUnaryCallback(type); - case DatePartSpecifier::HOUR: - return DatePartUnaryCallback(type); - case DatePartSpecifier::ERA: - return DatePartUnaryCallback(type); - case DatePartSpecifier::TIMEZONE: - return DatePartUnaryCallback(type); - case DatePartSpecifier::TIMEZONE_HOUR: - return DatePartUnaryCallback(type); - case DatePartSpecifier::TIMEZONE_MINUTE: - return DatePartUnaryCallback(type); - case DatePartSpecifier::JULIAN_DAY: - return DatePartUnaryCallback(type); - case DatePartSpecifier::EPOCH: - return DatePartUnaryCallback(type); - case DatePartSpecifier::INVALID: - throw NotImplementedException("Specifier type not implemented for DATEPART"); - } - throw InternalException("Unrecognized DatePartSpecifier in DatePartUnaryCallback"); -} - -template -static function_statistics_t DatePartUnaryStatistics(LogicalTypeId type) { - switch (type) { - case LogicalType::TIMESTAMP: - case LogicalType::TIMESTAMP_S: - case LogicalType::TIMESTAMP_MS: - case LogicalType::TIMESTAMP_NS: - return OP::template PropagateStatistics; - case LogicalType::DATE: - return OP::template PropagateStatistics; - case LogicalType::INTERVAL: - // Interval part statistics are not supported. +//! With a constant part, date_part is the unary part function (year, month, ...) +unique_ptr DatePartBindExpression(FunctionBindExpressionInput &input) { + auto &part = *input.children[0]; + Value part_value; + if (!part.IsFoldable() || !ExpressionExecutor::TryEvaluateScalar(input.context, part, part_value) || + part_value.IsNull()) { return nullptr; - case LogicalType::TIME: - return OP::template PropagateStatistics; - case LogicalType::TIME_NS: - return OP::template PropagateStatistics; - case LogicalType::TIME_TZ: - return OP::template PropagateStatistics; - default: - throw NotImplementedException("Unsupported temporal type for DATE_PART"); } + const auto part_code = GetDateTypePartSpecifier(part_value.ToString(), input.children[1]->GetReturnType()); + vector> children; + children.push_back(std::move(input.children[1])); + return BindBuiltinScalarFunction(input.context, Identifier(StringUtil::Lower(DatePartUnaryFunctionName(part_code))), + std::move(children)); } -static function_statistics_t DatePartUnaryStatistics(DatePartSpecifier part_code, LogicalTypeId type) { - switch (part_code) { - case DatePartSpecifier::YEAR: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::MONTH: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::DAY: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::DECADE: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::CENTURY: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::MILLENNIUM: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::QUARTER: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::DOW: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::ISODOW: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::DOY: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::WEEK: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::ISOYEAR: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::YEARWEEK: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::MICROSECONDS: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::MILLISECONDS: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::SECOND: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::MINUTE: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::HOUR: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::ERA: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::TIMEZONE: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::TIMEZONE_HOUR: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::TIMEZONE_MINUTE: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::JULIAN_DAY: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::EPOCH: - return DatePartUnaryStatistics(type); - case DatePartSpecifier::INVALID: - throw NotImplementedException("Specifier type not implemented for DATEPART"); - } - throw InternalException("Unrecognized DatePartSpecifier in DatePartUnaryStatistics"); -} - -unique_ptr DatePartBind(BindScalarFunctionInput &input) { - auto &bound_function = input.GetBoundFunction(); - auto &arguments = input.GetArguments(); - auto part_constant = input.TryGetConstant(0); - if (!part_constant) { - return nullptr; - } - - // Replace constant parts with unary function equivalents. - const auto part_name = part_constant->ToString(); - arguments.erase(arguments.begin()); - bound_function.GetArguments().erase(bound_function.GetArguments().begin()); - const auto type = (arguments[0]->GetReturnType().id()); - const auto part_code = GetDateTypePartSpecifier(part_name, type); - bound_function.SetName(Identifier(StringUtil::Lower(DatePartUnaryFunctionName(part_code)))); - - if (IsBigintDatepart(part_code)) { - bound_function.SetReturnType(LogicalType::BIGINT); - } else { - bound_function.SetReturnType(LogicalType::DOUBLE); - } - bound_function.SetFunctionCallback(DatePartUnaryCallback(part_code, type)); - bound_function.SetStatisticsCallback(DatePartUnaryStatistics(part_code, type)); - - return nullptr; -} - -template ScalarFunctionSet GetGenericDatePartFunction(scalar_function_t date_func, scalar_function_t ts_func, - scalar_function_t interval_func, function_statistics_t date_stats, - function_statistics_t ts_stats) { + scalar_function_t ts_ns_func, scalar_function_t interval_func, + function_statistics_t date_stats, function_statistics_t ts_stats, + function_statistics_t ts_ns_stats) { ScalarFunctionSet operator_set; - ScalarFunction date_fun({}, LogicalType::BIGINT, std::move(date_func), nullptr, date_stats, DATE_CACHE); + ScalarFunction date_fun({}, LogicalType::BIGINT, std::move(date_func), nullptr, date_stats); date_fun.GetSignature().AddParameter("ts", LogicalType::DATE); operator_set.AddFunction(date_fun); - ScalarFunction ts_fun({}, LogicalType::BIGINT, std::move(ts_func), nullptr, ts_stats, DATE_CACHE); + ScalarFunction ts_fun({}, LogicalType::BIGINT, std::move(ts_func), nullptr, ts_stats); ts_fun.GetSignature().AddParameter("ts", LogicalType::TIMESTAMP); operator_set.AddFunction(ts_fun); + ScalarFunction ts_ns_fun({}, LogicalType::BIGINT, std::move(ts_ns_func), nullptr, ts_ns_stats); + ts_ns_fun.GetSignature().AddParameter("ts", LogicalType::TIMESTAMP_NS); + operator_set.AddFunction(ts_ns_fun); ScalarFunction interval_fun({}, LogicalType::BIGINT, std::move(interval_func)); interval_fun.GetSignature().AddParameter("ts", LogicalType::INTERVAL); operator_set.AddFunction(interval_fun); @@ -2383,8 +2190,9 @@ template ScalarFunctionSet GetDatePartFunction() { return GetGenericDatePartFunction( DatePart::UnaryFunction, DatePart::UnaryFunction, - ScalarFunction::UnaryFunction, OP::template PropagateStatistics, - OP::template PropagateStatistics); + DatePart::UnaryFunction, ScalarFunction::UnaryFunction, + OP::template PropagateStatistics, OP::template PropagateStatistics, + OP::template PropagateStatistics); } ScalarFunctionSet GetGenericTimePartFunction(const LogicalType &result_type, scalar_function_t date_func, @@ -2606,7 +2414,7 @@ struct StructDatePart { result.Verify(); } - static void SerializeFunction(Serializer &serializer, const optional_ptr bind_data_p, + static void SerializeFunction(Serializer &serializer, const optional_ptr bind_data_p, const BoundScalarFunction &function) { D_ASSERT(bind_data_p); auto &info = bind_data_p->Cast(); @@ -2634,10 +2442,11 @@ struct StructDatePart { }; template ScalarFunctionSet GetCachedDatepartFunction() { - return GetGenericDatePartFunction>( + return GetGenericDatePartFunction( DatePartCachedFunction, DatePartCachedFunction, - ScalarFunction::UnaryFunction, OP::template PropagateStatistics, - OP::template PropagateStatistics); + DatePart::UnaryFunction, ScalarFunction::UnaryFunction, + OP::template PropagateStatistics, OP::template PropagateStatistics, + OP::template PropagateStatistics); } void SetNonDecreasingExceptInterval(ScalarFunctionSet &functions) { @@ -2939,47 +2748,38 @@ ScalarFunctionSet JulianDayFun::GetFunctions() { ScalarFunction ts_fun({}, LogicalType::DOUBLE, ts_func, nullptr, ts_stats); ts_fun.GetSignature().AddParameter("ts", LogicalType::TIMESTAMP); operator_set.AddFunction(ts_fun); + auto ts_ns_func = DatePart::UnaryFunction; + auto ts_ns_stats = OP::template PropagateStatistics; + ScalarFunction ts_ns_fun({}, LogicalType::DOUBLE, ts_ns_func, nullptr, ts_ns_stats); + ts_ns_fun.GetSignature().AddParameter("ts", LogicalType::TIMESTAMP_NS); + operator_set.AddFunction(ts_ns_fun); return operator_set; } -//! Binding date_part with a constant part replaces it with the unary part function (year, month, ...), so the bound -//! call has one argument and must be rendered under the replacement's own name -static unique_ptr DatePartUnbind(FunctionUnbindInput &input) { - auto &function = input.expression.Function(); - if (input.children.size() == 1) { - return make_uniq(function.GetQualifiedName(), std::move(input.children)); - } - if (input.children.size() != 2) { - return nullptr; - } - return make_uniq(function.GetDefinition()->GetQualifiedName(), std::move(input.children)); -} - // Names the "part,ts" pair shared by date_part's per-type overloads. static ScalarFunction NamePartTsArguments(ScalarFunction fun, const LogicalType &type) { fun.GetSignature().AddParameter("part", LogicalType::VARCHAR).AddParameter("ts", type); - fun.SetUnbindCallback(DatePartUnbind); + fun.SetBindExpressionCallback(DatePartBindExpression); return fun; } ScalarFunctionSet DatePartFun::GetFunctions() { ScalarFunctionSet date_part; - date_part.AddFunction(NamePartTsArguments( - ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), LogicalType::DATE)); - date_part.AddFunction(NamePartTsArguments( - ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), LogicalType::TIMESTAMP)); date_part.AddFunction( - NamePartTsArguments(ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), - LogicalType::TIMESTAMP_NS)); - date_part.AddFunction(NamePartTsArguments( - ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), LogicalType::TIME)); - date_part.AddFunction(NamePartTsArguments( - ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), LogicalType::TIME_NS)); - date_part.AddFunction(NamePartTsArguments( - ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), LogicalType::INTERVAL)); - date_part.AddFunction(NamePartTsArguments( - ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction, DatePartBind), LogicalType::TIME_TZ)); + NamePartTsArguments(ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction), LogicalType::DATE)); + date_part.AddFunction(NamePartTsArguments(ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction), + LogicalType::TIMESTAMP)); + date_part.AddFunction(NamePartTsArguments(ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction), + LogicalType::TIMESTAMP_NS)); + date_part.AddFunction( + NamePartTsArguments(ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction), LogicalType::TIME)); + date_part.AddFunction(NamePartTsArguments(ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction), + LogicalType::TIME_NS)); + date_part.AddFunction(NamePartTsArguments(ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction), + LogicalType::INTERVAL)); + date_part.AddFunction(NamePartTsArguments(ScalarFunction({}, LogicalType::DOUBLE, DatePartFunction), + LogicalType::TIME_TZ)); // struct variants date_part.AddFunction(StructDatePart::GetFunction(LogicalType::DATE)); diff --git a/src/duckdb/extension/core_functions/scalar/generic/alias.cpp b/src/duckdb/extension/core_functions/scalar/generic/alias.cpp index 9ea3fc3f9..c5a3c1ac3 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/alias.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/alias.cpp @@ -30,7 +30,7 @@ unique_ptr AliasBind(BindScalarFunctionInput &input) { return make_uniq(input.GetArguments()[0]->GetName()); } -void AliasSerialize(Serializer &serializer, const optional_ptr data, const BoundScalarFunction &) { +void AliasSerialize(Serializer &serializer, const optional_ptr data, const BoundScalarFunction &) { serializer.WriteProperty(100, "alias", data->Cast().alias); } diff --git a/src/duckdb/extension/core_functions/scalar/generic/binning.cpp b/src/duckdb/extension/core_functions/scalar/generic/binning.cpp index d35ee31b5..271333e56 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/binning.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/binning.cpp @@ -482,7 +482,7 @@ void UnsupportedEquiWidth(DataChunk &args, ExpressionState &state, Vector &) { throw BinderException(state.expr, "Unsupported type \"%s\" for equi_width_bins", args.data[0].GetType()); } -void EquiWidthBinSerialize(Serializer &, const optional_ptr, const BoundScalarFunction &) { +void EquiWidthBinSerialize(Serializer &, const optional_ptr, const BoundScalarFunction &) { return; } diff --git a/src/duckdb/extension/core_functions/scalar/generic/least.cpp b/src/duckdb/extension/core_functions/scalar/generic/least.cpp index cf211f449..d8058d523 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/least.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/least.cpp @@ -53,7 +53,7 @@ struct LeastGreatestSortKeyState : public FunctionLocalState { template unique_ptr LeastGreatestSortKeyInit(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { return make_uniq(expr.GetChildren().size(), OP::NullOrdering()); } @@ -284,6 +284,24 @@ void LeastGreatestResolveTypes(ResolveScalarFunctionTypesInput &input) { case PhysicalType::INT128: bound_function.SetFunctionCallback(LeastGreatestFunction); break; + case PhysicalType::UINT8: + bound_function.SetFunctionCallback(LeastGreatestFunction); + break; + case PhysicalType::UINT16: + bound_function.SetFunctionCallback(LeastGreatestFunction); + break; + case PhysicalType::UINT32: + bound_function.SetFunctionCallback(LeastGreatestFunction); + break; + case PhysicalType::UINT64: + bound_function.SetFunctionCallback(LeastGreatestFunction); + break; + case PhysicalType::UINT128: + bound_function.SetFunctionCallback(LeastGreatestFunction); + break; + case PhysicalType::FLOAT: + bound_function.SetFunctionCallback(LeastGreatestFunction); + break; case PhysicalType::DOUBLE: bound_function.SetFunctionCallback(LeastGreatestFunction); break; diff --git a/src/duckdb/extension/core_functions/scalar/generic/stats.cpp b/src/duckdb/extension/core_functions/scalar/generic/stats.cpp index d141e8903..ca287f544 100644 --- a/src/duckdb/extension/core_functions/scalar/generic/stats.cpp +++ b/src/duckdb/extension/core_functions/scalar/generic/stats.cpp @@ -33,8 +33,7 @@ unique_ptr StatsBind(BindScalarFunctionInput &input) { unique_ptr StatsPropagateStats(ClientContext &context, FunctionStatisticsInput &input) { auto &child_stats = input.child_stats; - auto &bind_data = input.bind_data; - auto &info = bind_data->Cast(); + auto &info = input.bind_data.write().Cast(); info.stats = child_stats[0].ToStruct().CastAs(context, LogicalType::VARIANT()); return nullptr; } diff --git a/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp b/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp index 2750518a7..92744e70c 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_aggregates.cpp @@ -5,7 +5,7 @@ #include "duckdb/catalog/catalog_entry/aggregate_function_catalog_entry.hpp" #include "duckdb/common/owning_string_map.hpp" #include "duckdb/common/smaller_binary.hpp" -#include "duckdb/common/types/sql_value_map.hpp" +#include "duckdb/common/arena_containers/arena_sql_value_map.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/function/create_sort_key.hpp" #include "duckdb/function/function_binder.hpp" @@ -57,7 +57,7 @@ struct ListAggregatesBindData : public FunctionData { return result; } - static void SerializeFunction(Serializer &serializer, const optional_ptr bind_data_p, + static void SerializeFunction(Serializer &serializer, const optional_ptr bind_data_p, const BoundScalarFunction &function) { const ListAggregatesBindData *bind_data = nullptr; if (bind_data_p) { @@ -85,7 +85,7 @@ ListAggregatesBindData::~ListAggregatesBindData() { } struct ListAggregatesLocalState : public FunctionLocalState { - ListAggregatesLocalState(Context &context, optional_ptr bind_data) + ListAggregatesLocalState(Context &context, optional_ptr bind_data) : arena_allocator(BufferAllocator::Get(context)) { if (!bind_data) { return; @@ -110,7 +110,7 @@ struct ListAggregatesLocalState : public FunctionLocalState { }; unique_ptr ListAggregatesInitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { return make_uniq(state.GetContext(), bind_data); } @@ -160,13 +160,13 @@ struct FinalizeGenericValueFunctor { }; struct AggregateFunctor { - template > + template > static void ListExecuteFunction(Vector &result, const Vector &state_vector, idx_t count) { } }; struct DistinctFunctor { - template > + template > static void ListExecuteFunction(Vector &result, const Vector &state_vector, idx_t count) { UnifiedVectorFormat sdata; state_vector.ToUnifiedFormat(sdata); @@ -209,7 +209,7 @@ struct DistinctFunctor { }; struct UniqueFunctor { - template > + template > static void ListExecuteFunction(Vector &result, const Vector &state_vector, idx_t count) { UnifiedVectorFormat sdata; state_vector.ToUnifiedFormat(sdata); @@ -417,14 +417,14 @@ void ListAggregatesFunction(DataChunk &args, ExpressionState &state, Vector &res break; case PhysicalType::VARCHAR: FUNCTION_FUNCTOR::template ListExecuteFunction>(result, state_vector.state_vector, - count); + ArenaOwningStringMap>( + result, state_vector.state_vector, count); break; #endif default: FUNCTION_FUNCTOR::template ListExecuteFunction>(result, state_vector.state_vector, - count); + ArenaOwningStringMap>( + result, state_vector.state_vector, count); break; } } diff --git a/src/duckdb/extension/core_functions/scalar/list/list_reduce.cpp b/src/duckdb/extension/core_functions/scalar/list/list_reduce.cpp index 2e8f9887e..c085337ea 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_reduce.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_reduce.cpp @@ -323,7 +323,7 @@ void LambdaFunctions::ListReduceFunction(DataChunk &args, ExpressionState &state idx_t loops = 0; bool end = false; while (!end) { - state.GetContext().InterruptCheck(); + state.GetContext().FastInterruptCheck(); auto &result_chunk = loops % 2 ? odd_result_chunk : even_result_chunk; auto &spare_result_chunk = loops % 2 ? even_result_chunk : odd_result_chunk; diff --git a/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp b/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp index 6313dac67..cf06772d0 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp @@ -46,7 +46,7 @@ struct ListSortBindData : public FunctionData { public: bool Equals(const FunctionData &other_p) const override; unique_ptr Copy() const override; - static void Serialize(Serializer &serializer, const optional_ptr bind_data, + static void Serialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &); static unique_ptr Deserialize(Deserializer &deserializer, BoundScalarFunction &); }; @@ -106,7 +106,7 @@ bool ListSortBindData::Equals(const FunctionData &other_p) const { Expression::Equals(sort_key, other.sort_key) && default_collation == other.default_collation; } -void ListSortBindData::Serialize(Serializer &serializer, const optional_ptr bind_data, +void ListSortBindData::Serialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &) { auto &data = bind_data->Cast(); serializer.WriteProperty(100, "order_type", data.order_type); @@ -137,7 +137,7 @@ ListSortBindData::~ListSortBindData() { // create the key_chunk and the payload_chunk and sink them into the local_sort_state static void SinkDataChunk(const Sort &sort, ExecutionContext &context, OperatorSinkInput &sink_input, Vector *child_vector, SelectionVector &sel, idx_t offset_lists_indices, - vector &types, Vector &payload_vector, bool &data_to_sort, + const vector &types, Vector &payload_vector, bool &data_to_sort, Vector &lists_indices) { // slice the child vector Vector slice(*child_vector, sel, offset_lists_indices); diff --git a/src/duckdb/extension/core_functions/scalar/random/random.cpp b/src/duckdb/extension/core_functions/scalar/random/random.cpp index cc7065a2a..6a82facf1 100644 --- a/src/duckdb/extension/core_functions/scalar/random/random.cpp +++ b/src/duckdb/extension/core_functions/scalar/random/random.cpp @@ -76,7 +76,7 @@ void RandomFunction(DataChunk &args, ExpressionState &state, Vector &result) { } unique_ptr RandomInitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { auto &random_engine = RandomEngine::Get(state.GetClientContext()); lock_guard guard(random_engine.lock); return make_uniq(random_engine.NextSeed()); diff --git a/src/duckdb/extension/core_functions/scalar/string/damerau_levenshtein.cpp b/src/duckdb/extension/core_functions/scalar/string/damerau_levenshtein.cpp index 265af59fd..d9a5d47ac 100644 --- a/src/duckdb/extension/core_functions/scalar/string/damerau_levenshtein.cpp +++ b/src/duckdb/extension/core_functions/scalar/string/damerau_levenshtein.cpp @@ -47,7 +47,7 @@ static idx_t DamerauLevenshteinDistance(Context &context, const T *source_str, i } // loop through string indices - these are offset by 2 from distance indices for (idx_t source_idx = 0; source_idx < source_len; source_idx++) { - context.InterruptCheck(); + context.FastInterruptCheck(); // keeps track of the largest string indices of target string matching current source character // same as DB in LW paper idx_t largest_target_chr_matching; diff --git a/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp b/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp index dab42aebf..d9df5816a 100644 --- a/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp +++ b/src/duckdb/extension/core_functions/scalar/string/levenshtein.cpp @@ -38,7 +38,7 @@ static idx_t LevenshteinDistance(Context &context, const T *txt_str, idx_t txt_l } for (idx_t pos_txt = 0; pos_txt < txt_len; pos_txt++) { - context.InterruptCheck(); + context.FastInterruptCheck(); // calculate distances1 (current raw distances) from the previous row distances1[0] = pos_txt + 1; diff --git a/src/duckdb/extension/core_functions/scalar/string/parse_path.cpp b/src/duckdb/extension/core_functions/scalar/string/parse_path.cpp index 4abc7d07c..eb782c9ec 100644 --- a/src/duckdb/extension/core_functions/scalar/string/parse_path.cpp +++ b/src/duckdb/extension/core_functions/scalar/string/parse_path.cpp @@ -3,7 +3,6 @@ #include "duckdb/common/vector/vector_writer.hpp" #include "core_functions/scalar/string_functions.hpp" #include "duckdb/function/scalar/string_common.hpp" -#include "duckdb/common/local_file_system.hpp" #include namespace duckdb { @@ -12,8 +11,11 @@ static string GetSeparator(const string_t &input) { string option = input.GetString(); // system's path separator - auto fs = FileSystem::CreateLocal(); - auto system_sep = fs->PathSeparator(option); +#ifdef _WIN32 + string system_sep = "\\"; +#else + string system_sep = "/"; +#endif string separator; if (option == "system") { diff --git a/src/duckdb/extension/core_functions/scalar/string/repeat.cpp b/src/duckdb/extension/core_functions/scalar/string/repeat.cpp index 23ddfcaba..c6cdaa017 100644 --- a/src/duckdb/extension/core_functions/scalar/string/repeat.cpp +++ b/src/duckdb/extension/core_functions/scalar/string/repeat.cpp @@ -9,6 +9,28 @@ namespace duckdb { +// Doubles the repeated prefix until it reaches a cache-resident block, then copies that block forward. +static void RepeatInto(char *result, const char *input, idx_t input_size, idx_t total_size) { + static constexpr idx_t REPEAT_BLOCK_SIZE = 16384; + if (input_size == 1) { + memset(result, input[0], total_size); + return; + } + memcpy(result, input, input_size); + idx_t filled = input_size; + while (filled < total_size && filled < REPEAT_BLOCK_SIZE) { + const auto next = MinValue(filled, total_size - filled); + memcpy(result + filled, result, next); + filled += next; + } + const auto block_size = filled; + while (filled < total_size) { + const auto next = MinValue(block_size, total_size - filled); + memcpy(result + filled, result, next); + filled += next; + } +} + static void RepeatFunction(DataChunk &args, ExpressionState &, Vector &result) { const auto &str_vector = args.data[0]; const auto &cnt_vector = args.data[1]; @@ -23,8 +45,8 @@ static void RepeatFunction(DataChunk &args, ExpressionState &, Vector &result) { if (TryMultiplyOperator::Operation(size_str, copy_count, copy_size)) { auto result_str = StringVector::EmptyString(result, copy_size); auto result_data = result_str.GetDataWriteable(); - for (idx_t i = 0; i < copy_count; i++) { - memcpy(result_data + i * size_str, input_str, size_str); + if (copy_size > 0) { + RepeatInto(result_data, input_str, size_str, copy_size); } result_str.Finalize(); return result_str; diff --git a/src/duckdb/extension/core_functions/scalar/struct/struct_update.cpp b/src/duckdb/extension/core_functions/scalar/struct/struct_update.cpp index c8b8ec467..fd4c3bcd4 100644 --- a/src/duckdb/extension/core_functions/scalar/struct/struct_update.cpp +++ b/src/duckdb/extension/core_functions/scalar/struct/struct_update.cpp @@ -30,7 +30,7 @@ struct StructUpdateBindData : public FunctionData { return stype == other.stype && field_indexes == other.field_indexes; } - static void Serialize(Serializer &serializer, const optional_ptr bind_data, + static void Serialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { auto &info = bind_data->Cast(); serializer.WriteProperty(100, "variable_return_type", info.stype); diff --git a/src/duckdb/extension/icu/icu-datefunc.cpp b/src/duckdb/extension/icu/icu-datefunc.cpp index 06f30eeac..4bdacfd05 100644 --- a/src/duckdb/extension/icu/icu-datefunc.cpp +++ b/src/duckdb/extension/icu/icu-datefunc.cpp @@ -119,8 +119,9 @@ bool ICUDateFunc::CalendarCacheState::TrySetTimeZone(Calendar *calendar, const s return true; } -unique_ptr -ICUDateFunc::InitCalendarCache(ExpressionState &state, const BoundFunctionExpression &expr, FunctionData *bind_data) { +unique_ptr ICUDateFunc::InitCalendarCache(ExpressionState &state, + const BoundFunctionExpression &expr, + optional_ptr bind_data) { auto &info = bind_data->Cast(); return make_uniq(*info.calendar); } diff --git a/src/duckdb/extension/icu/icu-datepart.cpp b/src/duckdb/extension/icu/icu-datepart.cpp index 1d5c9fd56..fc4ca9a6e 100644 --- a/src/duckdb/extension/icu/icu-datepart.cpp +++ b/src/duckdb/extension/icu/icu-datepart.cpp @@ -495,7 +495,7 @@ struct ICUDatePart : public ICUDateFunc { auto &unary = unary_expression->Cast(); bound_function = std::move(unary.FunctionMutable()); arguments = std::move(unary.GetChildrenMutable()); - return std::move(unary.BindInfoMutable()); + return unary.BindInfo() ? unary.BindInfo()->Copy() : nullptr; } while (false); using data_t = BindAdapterData; @@ -563,7 +563,7 @@ struct ICUDatePart : public ICUDateFunc { return make_uniq(context, std::move(part_codes)); } - static void SerializeStructFunction(Serializer &serializer, const optional_ptr bind_data, + static void SerializeStructFunction(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { D_ASSERT(bind_data); auto &info = bind_data->Cast(); diff --git a/src/duckdb/extension/icu/icu-datetrunc.cpp b/src/duckdb/extension/icu/icu-datetrunc.cpp index 84f1dd2e8..06417b2f4 100644 --- a/src/duckdb/extension/icu/icu-datetrunc.cpp +++ b/src/duckdb/extension/icu/icu-datetrunc.cpp @@ -10,14 +10,24 @@ namespace duckdb { struct ICUDateTrunc : public ICUDateFunc { + static bool TruncatesToSecondOrFiner(DatePartSpecifier part) { + switch (part) { + case DatePartSpecifier::SECOND: + case DatePartSpecifier::EPOCH: + case DatePartSpecifier::MILLISECONDS: + case DatePartSpecifier::MICROSECONDS: + return true; + default: + return false; + } + } + static unique_ptr Bind(BindScalarFunctionInput &input) { auto part_value = input.TryGetConstant(0); if (part_value && !part_value->IsNull()) { DatePartSpecifier part; - if (TryGetDatePartSpecifier(part_value->GetValue(), part) && - (part == DatePartSpecifier::DECADE || part == DatePartSpecifier::CENTURY || - part == DatePartSpecifier::MILLENNIUM || part == DatePartSpecifier::ERA)) { - // date_trunc is not monotone for these parts because ICU years skip year 0 at the BC/AD boundary + if (!TryGetDatePartSpecifier(part_value->GetValue(), part) || !TruncatesToSecondOrFiner(part)) { + // coarser parts follow the local time, which repeats or moves backwards when the UTC offset changes input.GetBoundFunction().SetArgProperties({}); } } diff --git a/src/duckdb/extension/icu/icu-strptime.cpp b/src/duckdb/extension/icu/icu-strptime.cpp index 23c9851de..9f71710ea 100644 --- a/src/duckdb/extension/icu/icu-strptime.cpp +++ b/src/duckdb/extension/icu/icu-strptime.cpp @@ -135,7 +135,7 @@ struct ICUStrptime : public ICUDateFunc { } static inline void ParseOne(Calendar *calendar, CalendarCacheState &cache, string_t input, - vector &formats, timestamp_tz_t &result) { + const vector &formats, timestamp_tz_t &result) { ParseResult parsed; for (auto &format : formats) { if (format.Parse(input, parsed)) { @@ -155,7 +155,7 @@ struct ICUStrptime : public ICUDateFunc { } static inline void ParseOne(Calendar *calendar, CalendarCacheState &cache, string_t input, - vector &formats, timestamp_tz_ns_t &result) { + const vector &formats, timestamp_tz_ns_t &result) { ParseResult parsed; for (auto &format : formats) { if (format.Parse(input, parsed)) { @@ -195,7 +195,7 @@ struct ICUStrptime : public ICUDateFunc { } static inline bool TryParseOne(Calendar *calendar, CalendarCacheState &cache, string_t input, - vector &formats, timestamp_tz_t &result) { + const vector &formats, timestamp_tz_t &result) { ParseResult parsed; for (auto &format : formats) { if (format.Parse(input, parsed)) { @@ -215,7 +215,7 @@ struct ICUStrptime : public ICUDateFunc { } static inline bool TryParseOne(Calendar *calendar, CalendarCacheState &cache, string_t input, - vector &formats, timestamp_tz_ns_t &result) { + const vector &formats, timestamp_tz_ns_t &result) { ParseResult parsed; for (auto &format : formats) { if (format.Parse(input, parsed)) { diff --git a/src/duckdb/extension/icu/icu_extension.cpp b/src/duckdb/extension/icu/icu_extension.cpp index 3fb65567a..26a656c85 100644 --- a/src/duckdb/extension/icu/icu_extension.cpp +++ b/src/duckdb/extension/icu/icu_extension.cpp @@ -1,3 +1,4 @@ +#include "duckdb/parser/parsed_data/create_scalar_function_info.hpp" #include "duckdb/catalog/catalog.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/vector_operations/unary_executor.hpp" @@ -6,7 +7,7 @@ #include "duckdb/main/config.hpp" #include "duckdb/main/connection.hpp" #include "duckdb/main/extension/extension_loader.hpp" -#include "duckdb/parser/parsed_data/create_collation_info.hpp" +#include "duckdb/planner/collation_binding.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "include/icu-current.hpp" #include "include/icu-dateadd.hpp" @@ -63,7 +64,7 @@ struct IcuBindData : public FunctionData { return language == other.language && country == other.country && tag == other.tag; } - static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, + static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundScalarFunction &function) { auto &bind_data = bind_data_p->Cast(); serializer.WriteProperty(100, "language", bind_data.language); @@ -81,25 +82,22 @@ struct IcuBindData : public FunctionData { return CreateInstance(language, country, tag); } - //! The prefix of the collation functions, and of the ones that are kept for backwards - //! compatibility, which return the sort key in hexadecimal instead of as a blob - static const string FUNCTION_PREFIX; + //! The prefix of the collation functions that are kept for backwards compatibility, which return the sort key in + //! hexadecimal instead of as a blob. The collation functions themselves are named after the collation. static const string HEX_FUNCTION_PREFIX; - static string EncodeFunctionName(const string &collation) { - return FUNCTION_PREFIX + collation; - } static string EncodeHexFunctionName(const string &collation) { return HEX_FUNCTION_PREFIX + collation; } static string DecodeFunctionName(const Identifier &fname) { auto &name = fname.GetIdentifierName(); - auto prefix = StringUtil::StartsWith(name, HEX_FUNCTION_PREFIX) ? HEX_FUNCTION_PREFIX : FUNCTION_PREFIX; - return name.substr(prefix.size()); + if (StringUtil::StartsWith(name, HEX_FUNCTION_PREFIX)) { + return name.substr(HEX_FUNCTION_PREFIX.size()); + } + return name; } }; -const string IcuBindData::FUNCTION_PREFIX = "collate_"; const string IcuBindData::HEX_FUNCTION_PREFIX = "icu_collate_"; //! The two hexadecimal characters of every byte value @@ -123,7 +121,8 @@ static const uint16_t &HexDigits(uint8_t byte) { struct CollatorLocalState : public FunctionLocalState { collation::CollationBuffer buffer; - static unique_ptr Init(ExpressionState &, const BoundFunctionExpression &, FunctionData *) { + static unique_ptr Init(ExpressionState &, const BoundFunctionExpression &, + optional_ptr) { return make_uniq(); } }; @@ -196,8 +195,7 @@ static duckdb::unique_ptr ICUSortKeyBind(BindScalarFunctionInput & //! The function a collation pushes into a query, it writes the sort key as a blob static ScalarFunction GetCollateFunction(const string &collation, const string &tag) { - string fname = IcuBindData::EncodeFunctionName(collation); - ScalarFunction result(Identifier(fname), {}, LogicalType::BLOB, ICUCollateFunction, ICUCollateBind); + ScalarFunction result(Identifier(collation), {}, LogicalType::BLOB, ICUCollateFunction, ICUCollateBind); result.GetSignature().AddParameter("str", LogicalType::VARCHAR); //! collation tag is added into the Function extra info result.extra_info = tag; @@ -403,11 +401,19 @@ static void SetICUCalendar(ClientContext &context, SetScope scope, Value ¶me throw NotImplementedException("Unknown Calendar '%s'!\n%s", name, candidate_str); } +//! Registers a collation function in the collation schema of the system catalog +static void RegisterCollation(ExtensionLoader &loader, ScalarFunction function) { + CreateScalarFunctionInfo info(std::move(function)); + info.SetQualifiedName( + QualifiedName(info.GetQualifiedName().Catalog(), CollationFunctions::GetSchema(), info.GetFunctionName())); + info.on_conflict = OnCreateConflict::ALTER_ON_CONFLICT; + loader.RegisterFunction(std::move(info)); +} + static void LoadInternal(ExtensionLoader &loader) { // iterate over all the collations for (auto &collation : collation::Collator::GetCollations()) { - CreateCollationInfo info(Identifier(collation), GetCollateFunction(collation, ""), false, false); - loader.RegisterCollation(info); + RegisterCollation(loader, GetCollateFunction(collation, "")); loader.RegisterFunction(GetICUCollateFunction(collation, "")); } @@ -421,8 +427,7 @@ static void LoadInternal(ExtensionLoader &loader) { * e.g. "und@colcaselevel=yes;colstrength=primary" * */ - CreateCollationInfo info("icu_noaccent", GetCollateFunction("noaccent", "und-u-ks-level1-kc-true"), false, false); - loader.RegisterCollation(info); + RegisterCollation(loader, GetCollateFunction("icu_noaccent", "und-u-ks-level1-kc-true")); loader.RegisterFunction(GetICUCollateFunction("noaccent", "und-u-ks-level1-kc-true")); ScalarFunction sort_key("icu_sort_key", {}, LogicalType::VARCHAR, ICUCollateFunction, ICUSortKeyBind); diff --git a/src/duckdb/extension/icu/include/icu-datefunc.hpp b/src/duckdb/extension/icu/include/icu-datefunc.hpp index 77b511c4a..6d9968a62 100644 --- a/src/duckdb/extension/icu/include/icu-datefunc.hpp +++ b/src/duckdb/extension/icu/include/icu-datefunc.hpp @@ -104,8 +104,9 @@ struct ICUDateFunc { //! Binds the calendar of the TimeZone and Calendar settings for a cast, whose result then depends on them static duckdb::unique_ptr BindCastData(BindCastInput &input); //! Initializes a CalendarCacheState from the function's BindData - static duckdb::unique_ptr - InitCalendarCache(ExpressionState &state, const BoundFunctionExpression &expr, FunctionData *bind_data); + static duckdb::unique_ptr InitCalendarCache(ExpressionState &state, + const BoundFunctionExpression &expr, + optional_ptr bind_data); //! Initializes a CalendarCacheState from a cast's CastData static duckdb::unique_ptr InitCastCalendarCache(CastLocalStateParameters ¶meters); diff --git a/src/duckdb/extension/json/include/json_common.hpp b/src/duckdb/extension/json/include/json_common.hpp index ea4a5990b..076b5b227 100644 --- a/src/duckdb/extension/json/include/json_common.hpp +++ b/src/duckdb/extension/json/include/json_common.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/operator/cast_operators.hpp" +#include "duckdb/common/string_util.hpp" #include "yyjson.hpp" using namespace duckdb_yyjson; // NOLINT @@ -267,7 +268,7 @@ struct JSONCommon { static string FormatParseError(const char *data, idx_t length, yyjson_read_err &error, const string &extra = "") { D_ASSERT(error.code != YYJSON_READ_SUCCESS); // Truncate, so we don't print megabytes worth of JSON - auto input = length > 50 ? string(data, 47) + "..." : string(data, length); + auto input = length > 50 ? StringUtil::TruncateUTF8TOByteLength(data, length, 47) : string(data, length); // Have to replace \r, otherwise output is unreadable input = StringUtil::Replace(input, "\r", "\\r"); return StringUtil::Format("Malformed JSON at byte %lld of input: %s. %s Input: \"%s\"", error.pos, error.msg, diff --git a/src/duckdb/extension/json/include/json_functions.hpp b/src/duckdb/extension/json/include/json_functions.hpp index 400794052..3c4dc3b8b 100644 --- a/src/duckdb/extension/json/include/json_functions.hpp +++ b/src/duckdb/extension/json/include/json_functions.hpp @@ -68,7 +68,7 @@ struct JSONFunctionLocalState : public FunctionLocalState { explicit JSONFunctionLocalState(Allocator &allocator); explicit JSONFunctionLocalState(Context &context); static unique_ptr Init(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data); + optional_ptr bind_data); static unique_ptr InitCastLocalState(CastLocalStateParameters ¶meters); static JSONFunctionLocalState &ResetAndGet(ExpressionState &state); diff --git a/src/duckdb/extension/json/include/json_scan.hpp b/src/duckdb/extension/json/include/json_scan.hpp index 7f3aafe80..d35fb04bc 100644 --- a/src/duckdb/extension/json/include/json_scan.hpp +++ b/src/duckdb/extension/json/include/json_scan.hpp @@ -185,7 +185,7 @@ struct JSONScan { vector &feature_columns, vector &return_types, vector &names); - static void Serialize(Serializer &serializer, const optional_ptr bind_data, + static void Serialize(Serializer &serializer, const optional_ptr bind_data, const BoundTableFunction &function); static unique_ptr Deserialize(Deserializer &deserializer, BoundTableFunction &function); diff --git a/src/duckdb/extension/json/json_functions.cpp b/src/duckdb/extension/json/json_functions.cpp index f2d8d1b62..741d02547 100644 --- a/src/duckdb/extension/json/json_functions.cpp +++ b/src/duckdb/extension/json/json_functions.cpp @@ -14,6 +14,7 @@ #include "duckdb/parser/expression/function_expression.hpp" #include "duckdb/parser/parsed_data/create_pragma_function_info.hpp" #include "duckdb/parser/tableref/table_function_ref.hpp" +#include "json_common.hpp" namespace duckdb { @@ -148,7 +149,7 @@ JSONFunctionLocalState::JSONFunctionLocalState(Context &context) } unique_ptr JSONFunctionLocalState::Init(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { return make_uniq(state.GetContext()); } @@ -364,7 +365,9 @@ static bool CastVarcharToJSONList(Vector &source, Vector &result, idx_t count, C JSONCommon::FormatParseError(input.GetDataWriteable(), input.GetSize(), error), parameters); } else if (!unsafe_yyjson_is_arr(doc->root)) { auto truncated_input = - input.GetSize() > 50 ? string(input.GetData(), 47) + "..." : input.GetString(); + input.GetSize() > 50 + ? StringUtil::TruncateUTF8TOByteLength(input.GetData(), input.GetSize(), 47) + : input.GetString(); HandleCastError::AssignError( StringUtil::Format("Cannot cast to list of JSON. Input \"%s\"", truncated_input), parameters); diff --git a/src/duckdb/extension/json/json_functions/json_create.cpp b/src/duckdb/extension/json/json_functions/json_create.cpp index 5fd18508c..7fd83ab11 100644 --- a/src/duckdb/extension/json/json_functions/json_create.cpp +++ b/src/duckdb/extension/json/json_functions/json_create.cpp @@ -81,8 +81,8 @@ enum class JSONGeometryFormat : uint8_t { WKT, GEOJSON }; struct JSONCopyFormatOptions { JSONGeometryFormat geometry_format = JSONGeometryFormat::WKT; - mutable optional_ptr date_format; - mutable optional_ptr timestamp_format; + mutable optional_ptr date_format; + mutable optional_ptr timestamp_format; mutable optional_ptr context; optional_ptr timestamptz_format_expression; optional_ptr timestamptz_ns_format_expression; @@ -155,11 +155,12 @@ struct JSONCopyToJSONFunctionData : public FunctionData { const_struct_names.Equals(other.const_struct_names); } - JSONCopyFormatOptions GetFormatOptions(Context &context) { + JSONCopyFormatOptions GetFormatOptions(Context &context) const { JSONCopyFormatOptions result; result.geometry_format = ClientGeometryFormat(context); - result.date_format = has_date_format ? optional_ptr(&date_format) : nullptr; - result.timestamp_format = has_timestamp_format ? optional_ptr(×tamp_format) : nullptr; + result.date_format = has_date_format ? optional_ptr(&date_format) : nullptr; + result.timestamp_format = + has_timestamp_format ? optional_ptr(×tamp_format) : nullptr; result.context = context; result.timestamptz_format_expression = timestamptz_format_expression ? optional_ptr(timestamptz_format_expression.get()) @@ -256,6 +257,7 @@ static LogicalType GetJSONType(StructNames &const_struct_names, const LogicalTyp case LogicalTypeId::DECIMAL: // GEOMETRY is emitted as either WKT or GeoJSON, so it must reach CreateValues untouched case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: return type; case LogicalTypeId::VARIANT: return LogicalType::JSON(); @@ -615,6 +617,33 @@ static void CreateRawValues(yyjson_mut_doc *doc, yyjson_mut_val *vals[], const V } } +// DECIMAL(w, s) with w == s has no digits before the decimal point, so its VARCHAR form has no leading zero +// (e.g., ".5" or "-.5"). That is not a valid JSON number, so we add the zero before inserting it as a raw value. +static void CreateRawDecimalValues(yyjson_mut_doc *doc, yyjson_mut_val *vals[], const Vector &value_v, idx_t count) { + const auto values = value_v.Values(); + string buffer; + for (idx_t i = 0; i < count; i++) { + const auto entry = values[i]; + if (!entry.IsValid()) { + vals[i] = yyjson_mut_null(doc); + continue; + } + const auto &str = entry.GetValue(); + const auto data = str.GetData(); + const auto size = str.GetSize(); + const idx_t point_pos = (size > 0 && data[0] == '-') ? 1 : 0; + if (point_pos < size && data[point_pos] == '.') { + buffer.assign(data, point_pos); + buffer += '0'; + buffer.append(data + point_pos, size - point_pos); + vals[i] = yyjson_mut_rawncpy(doc, buffer.c_str(), buffer.size()); + } else { + vals[i] = yyjson_mut_rawncpy(doc, data, size); + } + D_ASSERT(vals[i] != nullptr); + } +} + static void CreateValuesStruct(const StructNames &names, yyjson_mut_doc *doc, yyjson_mut_val *vals[], Vector &value_v, idx_t count, const JSONCopyFormatOptions &options) { // Structs become values, therefore we initialize vals to JSON values @@ -1034,7 +1063,8 @@ static void CreateValues(const StructNames &names, yyjson_mut_doc *doc, yyjson_m CreateValuesFromDefaultCast(doc, vals, value_v, count); break; } - case LogicalTypeId::GEOMETRY: { + case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: { if (options.geometry_format == JSONGeometryFormat::GEOJSON) { CreateValuesGeometry(doc, vals, value_v, count); } else { @@ -1058,7 +1088,11 @@ static void CreateValues(const StructNames &names, yyjson_mut_doc *doc, yyjson_m if (DecimalType::GetWidth(type) > 15) { Vector string_vector(LogicalTypeId::VARCHAR, count); VectorOperations::DefaultCast(value_v, string_vector, count); - CreateRawValues(doc, vals, string_vector, count); + if (DecimalType::GetWidth(type) == DecimalType::GetScale(type)) { + CreateRawDecimalValues(doc, vals, string_vector, count); + } else { + CreateRawValues(doc, vals, string_vector, count); + } } else { Vector double_vector(LogicalType::DOUBLE, count); VectorOperations::DefaultCast(value_v, double_vector, count); @@ -1428,7 +1462,7 @@ static unique_ptr JSONCopyToGeoJSONBind(INPUT &input) { std::move(property_indices), write_bbox); } -static void JSONCopyToJSONSerialize(Serializer &serializer, optional_ptr bind_data, +static void JSONCopyToJSONSerialize(Serializer &serializer, optional_ptr bind_data, const BoundScalarFunction &) { if (!bind_data) { throw InternalException("%s is missing bind data during serialization", JSON_COPY_TO_JSON_INTERNAL_NAME); 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 22e372c6b..4acd351aa 100644 --- a/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp +++ b/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp @@ -287,7 +287,10 @@ PragmaFunctionSet JSONFunctions::GetExecuteJsonSerializedSqlPragmaFunction() { //---------------------------------------------------------------------- struct ExecuteSqlTableFunction { struct BindData : public TableFunctionData { - shared_ptr plan; + unique_ptr node; + string query; + vector names; + vector types; unique_ptr con; bool SupportStatementCache() const override { @@ -321,12 +324,24 @@ struct ExecuteSqlTableFunction { if (stmts.size() != 1) { throw BinderException("json_execute_serialized_sql expects exactly one statement"); } - result->plan = result->con->RelationFromQuery(std::move(stmts[0])); - - for (auto &col : result->plan->Columns()) { - return_types.emplace_back(col.Type()); - names.emplace_back(col.Name()); + result->query = stmts[0]->ToString(); + result->node = std::move(stmts[0]->node); + + // without query text, a prepare error keeps its position for the outer query to report + auto statement = make_uniq(); + statement->node = result->node->Copy(); + auto prepared = result->con->Prepare(std::move(statement)); + if (prepared->HasError()) { + prepared->GetErrorObject().Throw(); + } + // a parameter whose type stays open leaves the result unknown, one with a type shows as an expected type + if (!prepared->MetadataAvailable() || !prepared->GetExpectedParameterTypes().empty()) { + throw BinderException("json_execute_serialized_sql cannot execute a statement with parameters"); } + result->names = prepared->GetNames(); + result->types = prepared->GetTypes(); + return_types = result->types; + names = result->names; return std::move(result); } @@ -334,7 +349,31 @@ struct ExecuteSqlTableFunction { auto &data = data_p.bind_data->Cast(); auto &state = data_p.global_state->Cast(); if (!state.result) { - state.result = data.plan->ExecuteOrThrow(); + auto statement = make_uniq(); + statement->node = data.node->Copy(); + statement->query = data.query; + auto result = data.con->context->RunInternalStatement(std::move(statement), QueryParameters()); + result->ThrowIfError(); + if (result->GetTypes() != data.types || result->GetNames() != data.names) { + string error = "Result mismatch in query!\nExpected the following columns: ["; + for (idx_t i = 0; i < data.types.size(); i++) { + error += i == 0 ? "" : ", "; + error += data.names[i] + " " + data.types[i].ToString(); + } + error += "]\nBut result contained the following: "; + for (idx_t i = 0; i < result->GetTypes().size(); i++) { + error += i == 0 ? "[" : ", "; + error += result->ColumnName(i) + " " + result->GetTypes()[i].ToString(); + } + error += "]"; + if (result->GetNames() != data.names) { + error += + "\nIf no table or view the statement reads changed since it was bound, an unaliased expression " + "may have been named differently at bind and at run; an alias keeps its name stable."; + } + ErrorData(error).Throw(); + } + state.result = std::move(result); } auto result_chunk = state.result->Fetch(); if (!result_chunk) { diff --git a/src/duckdb/extension/json/json_functions/json_transform.cpp b/src/duckdb/extension/json/json_functions/json_transform.cpp index 0c1d1a2f7..b78d0dff1 100644 --- a/src/duckdb/extension/json/json_functions/json_transform.cpp +++ b/src/duckdb/extension/json/json_functions/json_transform.cpp @@ -1207,6 +1207,7 @@ bool JSONTransform::Transform(yyjson_val *vals[], yyjson_alc *alc, Vector &resul case LogicalTypeId::TIMESTAMP_MS: case LogicalTypeId::TIMESTAMP_SEC: case LogicalTypeId::UUID: + case LogicalTypeId::GEOGRAPHY: return TransformFromString(vals, result, count, options); case LogicalTypeId::GEOMETRY: return TransformGeometry(vals, result, count, options); diff --git a/src/duckdb/extension/json/json_scan.cpp b/src/duckdb/extension/json/json_scan.cpp index 961600c1b..217beb911 100644 --- a/src/duckdb/extension/json/json_scan.cpp +++ b/src/duckdb/extension/json/json_scan.cpp @@ -111,7 +111,7 @@ void JSONScanLocalState::AddTransformError(idx_t object_index, const string &err scan_state.current_reader->AddTransformError(scan_state, object_index, error_message); } -void JSONScan::Serialize(Serializer &serializer, const optional_ptr bind_data_p, +void JSONScan::Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundTableFunction &) { throw NotImplementedException("JSONScan Serialize not implemented"); } diff --git a/src/duckdb/extension/parquet/column_reader.cpp b/src/duckdb/extension/parquet/column_reader.cpp index 73c973458..20242dabc 100644 --- a/src/duckdb/extension/parquet/column_reader.cpp +++ b/src/duckdb/extension/parquet/column_reader.cpp @@ -447,6 +447,7 @@ void ColumnReader::InitializeRead(idx_t row_group_idx_p, idx_t row_group_num_row chunk_read_offset = NumericCast(chunk->meta_data.dictionary_page_offset); } ValidateColumnMetadata(row_group_num_rows, *chunk); + Schema().ValidateNullCount(*chunk, Reader().GetFileName().c_str()); group_rows_available = NumericCast(chunk->meta_data.num_values); } @@ -1209,13 +1210,14 @@ void ColumnReader::DirectFilter(ColumnReaderInput &input, Vector &result, const auto &repeat_out = input.repeat_out; auto to_read = num_values; + dictionary_decoder.ResetFilter(filter_state); // prepare the first read if we haven't yet BeginRead(define_out, repeat_out); auto read_now = ReadPageHeaders(to_read, &filter, &filter_state); // we can only push the filter into the decoder if we are reading the ENTIRE vector in one go - if (encoding == ColumnEncoding::DICTIONARY && read_now == to_read && dictionary_decoder.HasFilter()) { + if (encoding == ColumnEncoding::DICTIONARY && read_now == to_read && dictionary_decoder.HasFilter(filter_state)) { BlockPinGuard pin_guard(*this); if (page_is_filtered_out) { // the page has been filtered out entirely - skip diff --git a/src/duckdb/extension/parquet/column_writer.cpp b/src/duckdb/extension/parquet/column_writer.cpp index 3bf31c8e8..7eef06c22 100644 --- a/src/duckdb/extension/parquet/column_writer.cpp +++ b/src/duckdb/extension/parquet/column_writer.cpp @@ -566,6 +566,9 @@ unique_ptr ColumnWriter::CreateWriterRecursive(ClientContext &cont case LogicalTypeId::GEOMETRY: return make_uniq>(writer, std::move(schema), path_in_schema); + case LogicalTypeId::GEOGRAPHY: + return make_uniq>(writer, std::move(schema), + path_in_schema); case LogicalTypeId::VARCHAR: return make_uniq>(writer, std::move(schema), path_in_schema); diff --git a/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp b/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp index b27ceb417..8cbfeb1d3 100644 --- a/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp +++ b/src/duckdb/extension/parquet/decoder/dictionary_decoder.cpp @@ -34,8 +34,8 @@ DictionaryDecoder::DictionaryDecoder(ColumnReader &reader) void DictionaryDecoder::InitializeDictionary(idx_t new_dictionary_size, optional_ptr filter, optional_ptr filter_state, bool has_defines) { dictionary_size = new_dictionary_size; - filter_result.reset(); - filter_count = 0; + filter_cache.reset(); + filter_rejects_null = false; can_have_nulls = has_defines; // we use the last entry as a NULL, dictionary vectors don't have a separate validity mask @@ -53,22 +53,8 @@ void DictionaryDecoder::InitializeDictionary(idx_t new_dictionary_size, optional reader.Plain(reader.block, nullptr, dictionary_size, 0, dictionary_data); } - // immediately filter the dictionary, if applicable - if (filter && CanFilter(*filter, *filter_state)) { - // no filter result yet - apply filter to the dictionary - // initialize the filter result - setting everything to false - filter_result = make_unsafe_uniq_array(duckdb_dictionary_size); - - // apply the filter - SelectionVector dict_sel; - filter_count = duckdb_dictionary_size; - ColumnSegment::FilterSelection(dict_sel, dictionary_data, *filter_state, duckdb_dictionary_size, filter_count); - - // now set all matching tuples to true - for (idx_t i = 0; i < filter_count; i++) { - auto idx = dict_sel.get_index(i); - filter_result[idx] = true; - } + if (filter && CanFilter(*filter_state)) { + CreateFilterCache(*filter_state); } } @@ -103,10 +89,27 @@ idx_t DictionaryDecoder::GetValidValues(uint8_t *defines, idx_t read_count, idx_ if (defines) { D_ASSERT(can_have_nulls); valid_count = 0; - for (idx_t i = 0; i < read_count; i++) { + const auto max_define = reader.MaxDefine(); + const uint64_t valid_defines = max_define * UINT64_C(0x0101010101010101); + idx_t i = 0; + for (; max_define <= NumericLimits::Maximum() && i + 8 <= read_count; i += 8) { + if (Load(defines + result_offset + i) == valid_defines) { + for (idx_t j = 0; j < 8; j++) { + valid_sel.set_index(valid_count + j, i + j); + } + valid_count += 8; + } else { + for (idx_t j = 0; j < 8; j++) { + valid_sel.set_index(valid_count, i + j); + dictionary_selection_vector.set_index(i + j, dictionary_size); + valid_count += defines[result_offset + i + j] == max_define; + } + } + } + for (; i < read_count; i++) { valid_sel.set_index(valid_count, i); dictionary_selection_vector.set_index(i, dictionary_size); - valid_count += defines[result_offset + i] == reader.MaxDefine(); + valid_count += defines[result_offset + i] == max_define; } } return valid_count; @@ -157,26 +160,36 @@ void DictionaryDecoder::Skip(uint8_t *defines, idx_t skip_count) { dict_decoder->Skip(NumericCast(valid_count)); } -bool DictionaryDecoder::DictionarySupportsFilter(const TableFilter &filter, TableFilterState &filter_state) { - auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter, "DictionaryDecoder::DictionarySupportsFilter"); - auto &state = filter_state.Cast(); - auto emits_nulls = expr_filter.EvaluateWithConstant(*state.executor, Value(reader.Type())); - return !emits_nulls; +bool DictionaryDecoder::CanFilter(const TableFilterState &filter_state) { + return dictionary_size > 0 && filter_state.can_cache; } -bool DictionaryDecoder::CanFilter(const TableFilter &filter, TableFilterState &filter_state) { - if (dictionary_size == 0) { - return false; +void DictionaryDecoder::CreateFilterCache(TableFilterState &state) { + filter_cache = state.CreateCache(dictionary->data, dictionary_size + can_have_nulls); + filter_rejects_null = false; + if (filter_cache->CanSkipAll()) { + // Skipped pages materialize NULL placeholders on the ordinary-read path. + Vector null_value(Value(reader.Type()), count_t(1)); + auto null_cache = state.CreateCache(null_value, 1); + filter_rejects_null = null_cache->CanSkipAll(); } - if (filter_state.can_throw) { - // the dictionary holds the values of every row in the page - evaluating a filter that can throw over it - // would raise errors for rows that are never returned - return false; +} + +void DictionaryDecoder::ResetFilter(const TableFilterState &state) { + if (filter_cache && !filter_cache->IsValidFor(state)) { + filter_cache.reset(); + filter_rejects_null = false; } - // We can only push the filter if the filter removes NULL values - if (!DictionarySupportsFilter(filter, filter_state)) { +} + +bool DictionaryDecoder::HasFilter(TableFilterState &state) { + ResetFilter(state); + if (!dictionary || dictionary_size == 0 || !state.can_cache) { return false; } + if (!filter_cache) { + CreateFilterCache(state); + } return true; } @@ -185,36 +198,9 @@ void DictionaryDecoder::Filter(uint8_t *defines, const idx_t read_count, Vector if (!dictionary) { throw std::runtime_error("Parquet file is likely corrupted, missing dictionary"); } - D_ASSERT(filter_count > 0); - // read the dictionary values - const auto valid_count = Read(defines, read_count, result, 0); - if (valid_count == 0) { - // all values are NULL - approved_tuple_count = 0; - return; - } - - // apply the filter by checking the dictionary offsets directly - SelectionVector new_sel(valid_count); - if (valid_count == read_count) { - approved_tuple_count = - SelectionVector::SelectFromBoolean(filter_result.get(), &dictionary_selection_vector, read_count, - array_ptr(new_sel.data(), new_sel.Capacity())); - } else { - auto offsets = reinterpret_cast(offset_buffer.GetCurrentLoc()); - D_ASSERT(offsets); - approved_tuple_count = 0; - for (idx_t idx = 0; idx < valid_count; idx++) { - auto row_idx = valid_sel.get_index(idx); - auto offset = offsets[idx]; - // avoid a branch per row: always write, advance only on a match - new_sel.set_index(approved_tuple_count, row_idx); - approved_tuple_count += filter_result[offset]; - } - } - if (approved_tuple_count < read_count) { - sel.Initialize(new_sel); - } + D_ASSERT(filter_cache); + Read(defines, read_count, result, 0); + filter_cache->Filter(dictionary_selection_vector, sel, approved_tuple_count); } } // namespace duckdb diff --git a/src/duckdb/extension/parquet/include/decode_utils.hpp b/src/duckdb/extension/parquet/include/decode_utils.hpp index 6b4c46337..40b08cd19 100644 --- a/src/duckdb/extension/parquet/include/decode_utils.hpp +++ b/src/duckdb/extension/parquet/include/decode_utils.hpp @@ -101,6 +101,27 @@ class ParquetDecodeUtils { width, sizeof(T) * BITPACK_DLEN); } + if constexpr (std::is_unsigned::value && (sizeof(T) == 4 || sizeof(T) == 8)) { + if (count >= 128) { + if (cast_pointer_to_uint64(src.GetCurrentLoc()) % sizeof(uint32_t) == 0) { + BitpackingPrimitives::UnPackBufferWithFrame(data_ptr_cast(dst), src.GetCurrentLoc(), count, + width, 0); + src.UnsafeInc(count * width / BITPACK_DLEN); + return; + } + T aligned_data[1024]; + for (idx_t i = 0; i < count; i += 1024) { + const auto batch_count = MinValue(count - i, 1024); + const auto read_size = batch_count * width / BITPACK_DLEN; + memcpy(aligned_data, src.GetCurrentLoc(), read_size); + BitpackingPrimitives::UnPackBufferWithFrame(data_ptr_cast(dst + i), data_ptr_cast(aligned_data), + batch_count, width, 0); + src.UnsafeInc(read_size); + } + return; + } + } + if (cast_pointer_to_uint64(src.GetCurrentLoc()) % sizeof(T) == 0) { // Fast path: aligned BitpackingPrimitives::UnPackBuffer(data_ptr_cast(dst), src.GetCurrentLoc(), count, width); diff --git a/src/duckdb/extension/parquet/include/decoder/dictionary_decoder.hpp b/src/duckdb/extension/parquet/include/decoder/dictionary_decoder.hpp index ea3477cea..7926dc40c 100644 --- a/src/duckdb/extension/parquet/include/decoder/dictionary_decoder.hpp +++ b/src/duckdb/extension/parquet/include/decoder/dictionary_decoder.hpp @@ -19,10 +19,12 @@ #include "duckdb/common/types/selection_vector.hpp" #include "duckdb/common/unique_ptr.hpp" #include "duckdb/planner/table_filter.hpp" +#include "duckdb/planner/table_filter_state.hpp" namespace duckdb { class ColumnReader; struct TableFilterState; +class TableFilterCache; class DictionaryEntry; class ResizeableBuffer; class Vector; @@ -38,17 +40,16 @@ class DictionaryDecoder { void Rebase(); idx_t Read(uint8_t *defines, idx_t read_count, Vector &result, idx_t result_offset); void Skip(uint8_t *defines, idx_t skip_count); - bool CanFilter(const TableFilter &filter, TableFilterState &filter_state); - bool DictionarySupportsFilter(const TableFilter &filter, TableFilterState &filter_state); + bool CanFilter(const TableFilterState &filter_state); void Filter(uint8_t *defines, idx_t read_count, Vector &result, SelectionVector &sel, idx_t &approved_tuple_count); - bool HasFilter() const { - return filter_result.get(); - } + void ResetFilter(const TableFilterState &state); + bool HasFilter(TableFilterState &state); bool HasFilteredOutAllValues() const { - return HasFilter() && filter_count == 0; + return filter_rejects_null && filter_cache && filter_cache->CanSkipAll(); } private: + void CreateFilterCache(TableFilterState &state); idx_t GetValidValues(uint8_t *defines, idx_t read_count, idx_t result_offset); void ConvertDictToSelVec(uint32_t *offsets, const SelectionVector &rows, idx_t count); @@ -61,8 +62,8 @@ class DictionaryDecoder { SelectionVector dictionary_selection_vector; idx_t dictionary_size; buffer_ptr dictionary; - unsafe_unique_array filter_result; - idx_t filter_count; + unique_ptr filter_cache; + bool filter_rejects_null = false; bool can_have_nulls; }; diff --git a/src/duckdb/extension/parquet/include/parquet_bss_decoder.hpp b/src/duckdb/extension/parquet/include/parquet_bss_decoder.hpp index cb45ab97a..25f1343cd 100644 --- a/src/duckdb/extension/parquet/include/parquet_bss_decoder.hpp +++ b/src/duckdb/extension/parquet/include/parquet_bss_decoder.hpp @@ -31,7 +31,16 @@ class BssDecoder { /// Writes batch_size values in the PLAIN layout (consecutive type_size-byte values) to values_target_ptr void GetBatch(data_ptr_t values_target_ptr, uint32_t batch_size) { buffer_.Available((value_offset_ + batch_size) * type_size_); - + if (type_size_ == 4) { + GetBatchFixed<4>(values_target_ptr, batch_size); + value_offset_ += batch_size; + return; + } + if (type_size_ == 8) { + GetBatchFixed<8>(values_target_ptr, batch_size); + value_offset_ += batch_size; + return; + } for (idx_t byte_offset = 0; byte_offset < type_size_; ++byte_offset) { data_ptr_t input_bytes = buffer_.GetCurrentLoc() + byte_offset * num_buffer_values_ + value_offset_; for (uint32_t i = 0; i < batch_size; ++i) { @@ -51,6 +60,16 @@ class BssDecoder { } private: + template + void GetBatchFixed(data_ptr_t __restrict target, idx_t count) { + const auto source = buffer_.GetCurrentLoc() + value_offset_; + for (idx_t i = 0; i < count; i++) { + for (idx_t byte = 0; byte < BYTE_COUNT; byte++) { + target[i * BYTE_COUNT + byte] = source[byte * num_buffer_values_ + i]; + } + } + } + ByteBuffer buffer_; idx_t type_size_; uint32_t num_buffer_values_; diff --git a/src/duckdb/extension/parquet/include/parquet_column_schema.hpp b/src/duckdb/extension/parquet/include/parquet_column_schema.hpp index cf8e3bed4..e05a6bb76 100644 --- a/src/duckdb/extension/parquet/include/parquet_column_schema.hpp +++ b/src/duckdb/extension/parquet/include/parquet_column_schema.hpp @@ -127,6 +127,8 @@ struct ParquetColumnSchema { idx_t row_group_idx_p, const duckdb_parquet::ColumnChunkList &columns) const; void ValidateColumnMetadata(const duckdb_parquet::ColumnChunk &column, int64_t row_group_num_rows, bool validate_row_count, const char *file_name = nullptr) const; + //! Validates the null count of the statistics of the column chunk that this schema reads its values from + void ValidateNullCount(const duckdb_parquet::ColumnChunk &column, const char *file_name = nullptr) const; public: optional_idx GetChildIndexByName(const string &name) const; diff --git a/src/duckdb/extension/parquet/include/parquet_dbp_decoder.hpp b/src/duckdb/extension/parquet/include/parquet_dbp_decoder.hpp index 8b31ef006..8c4b0fbae 100644 --- a/src/duckdb/extension/parquet/include/parquet_dbp_decoder.hpp +++ b/src/duckdb/extension/parquet/include/parquet_dbp_decoder.hpp @@ -109,15 +109,17 @@ class DbpDecoder { const idx_t next = MinValue(batch_size - target_values_offset, BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE - unpacked_data_offset); if (next != 0) { + auto previous = previous_value; for (idx_t i = 0; i < next; i++) { const auto &unpacked_value = unpacked_data[unpacked_data_offset + i]; - auto current_value = static_cast(static_cast(previous_value) + + auto current_value = static_cast(static_cast(previous) + static_cast(min_delta) + unpacked_value); if (!SKIP_READ) { target_values[target_values_offset + i] = current_value; } - previous_value = static_cast(current_value); + previous = static_cast(current_value); } + previous_value = previous; target_values_offset += next; unpacked_data_offset += next; continue; diff --git a/src/duckdb/extension/parquet/include/parquet_geometry.hpp b/src/duckdb/extension/parquet/include/parquet_geometry.hpp index 4c2953eaf..a1619eb15 100644 --- a/src/duckdb/extension/parquet/include/parquet_geometry.hpp +++ b/src/duckdb/extension/parquet/include/parquet_geometry.hpp @@ -87,6 +87,9 @@ struct GeoParquetColumnMetadata { // The crs of the geometry column (if any) in PROJJSON format string projjson; + // The edge interpretation of the column: GEODETIC ("edges": "spherical") columns are GEOGRAPHY + GeometryModel geometry_model = GeometryModel::PLANAR; + // Used to track the "primary" geometry column (if any) idx_t insertion_index = 0; diff --git a/src/duckdb/extension/parquet/include/parquet_reader.hpp b/src/duckdb/extension/parquet/include/parquet_reader.hpp index 9113bf6f2..7962ca4b4 100644 --- a/src/duckdb/extension/parquet/include/parquet_reader.hpp +++ b/src/duckdb/extension/parquet/include/parquet_reader.hpp @@ -155,7 +155,7 @@ StringColumnReader::Utf8ValidationOption EnumUtil::FromString(const char *value); struct ParquetScanFilter { - ParquetScanFilter(ClientContext &context, ProjectionIndex filter_idx, TableFilter &filter); + ParquetScanFilter(ProjectionIndex filter_idx, TableFilter &filter); ~ParquetScanFilter(); ParquetScanFilter(ParquetScanFilter &&) = default; diff --git a/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp b/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp index a4f6b1a74..7197f3524 100644 --- a/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp +++ b/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp @@ -258,7 +258,14 @@ struct ParquetBaseGeoOperator : public BaseParquetOperator { struct ParquetGeometryOperator : public ParquetBaseGeoOperator { template static unique_ptr InitializeStats() { - return make_uniq(); + return make_uniq(GeometryModel::PLANAR); + } +}; + +struct ParquetGeographyOperator : public ParquetBaseGeoOperator { + template + static unique_ptr InitializeStats() { + return make_uniq(GeometryModel::GEODETIC); } }; diff --git a/src/duckdb/extension/parquet/include/writer/parquet_write_stats.hpp b/src/duckdb/extension/parquet/include/writer/parquet_write_stats.hpp index a4f02c3d8..ad474e325 100644 --- a/src/duckdb/extension/parquet/include/writer/parquet_write_stats.hpp +++ b/src/duckdb/extension/parquet/include/writer/parquet_write_stats.hpp @@ -353,16 +353,17 @@ class UUIDStatisticsState : public ColumnWriterStatistics { class GeoStatisticsState final : public ColumnWriterStatistics { public: - explicit GeoStatisticsState() : has_stats(false) { + explicit GeoStatisticsState(GeometryModel geometry_model) : has_stats(false), geometry_model(geometry_model) { geo_stats.SetEmpty(); } bool has_stats; + GeometryModel geometry_model; GeometryStatsData geo_stats; public: void Update(const string_t &val) { - geo_stats.Update(val); + geo_stats.Update(val, geometry_model); has_stats = true; } bool HasGeoStats() override { @@ -376,7 +377,8 @@ class GeoStatisticsState final : public ColumnWriterStatistics { if (!other.has_stats) { return; } - geo_stats.Merge(other.geo_stats); + D_ASSERT(geometry_model == other.geometry_model); + geo_stats.Merge(other.geo_stats, geometry_model); has_stats = true; } void WriteGeoStats(duckdb_parquet::GeospatialStatistics &stats) override { diff --git a/src/duckdb/extension/parquet/parquet_column_schema.cpp b/src/duckdb/extension/parquet/parquet_column_schema.cpp index f6923febd..a8607c54e 100644 --- a/src/duckdb/extension/parquet/parquet_column_schema.cpp +++ b/src/duckdb/extension/parquet/parquet_column_schema.cpp @@ -71,6 +71,25 @@ void ParquetColumnSchema::ValidateColumnMetadata(const ColumnChunk &column, int6 } } +void ParquetColumnSchema::ValidateNullCount(const ColumnChunk &column, const char *file_name) const { + if (max_define != 0 || !column.__isset.meta_data || !column.meta_data.__isset.statistics) { + return; + } + auto &statistics = column.meta_data.statistics; + if (!statistics.__isset.null_count || statistics.null_count <= 0) { + return; + } + // the column has no definition levels, so its values cannot be NULL + if (file_name) { + throw DataCorruptionException("Failed to read file \"%s\": metadata is corrupt. Column \"%s\" cannot hold " + "NULL values but its statistics count %lld NULL values", + file_name, name, statistics.null_count); + } + throw DataCorruptionException("Parquet metadata is corrupt. Column \"%s\" cannot hold NULL values but its " + "statistics count %lld NULL values", + name, statistics.null_count); +} + //! Writer constructors ParquetColumnSchema ParquetColumnSchema::FromLogicalType(const Identifier &name, const LogicalType &type, diff --git a/src/duckdb/extension/parquet/parquet_extension.cpp b/src/duckdb/extension/parquet/parquet_extension.cpp index cfa5e4650..6be29b46a 100644 --- a/src/duckdb/extension/parquet/parquet_extension.cpp +++ b/src/duckdb/extension/parquet/parquet_extension.cpp @@ -392,7 +392,7 @@ static unique_ptr ParquetWriteBind(ClientContext &context, CopyFun } static void ParquetCopyToPropagateStatistics(CopyToPropagateStatsInput &input) { - auto &parquet_bind = input.bind_data.Cast(); + auto &parquet_bind = input.bind_data.write().Cast(); auto count = parquet_bind.sql_types.size(); if (input.column_stats.size() != count) { return; @@ -405,8 +405,8 @@ static void ParquetCopyToPropagateStatistics(CopyToPropagateStatsInput &input) { } } -static unique_ptr ParquetWriteInitializeGlobal(ClientContext &context, FunctionData &bind_data, - const string &file_path) { +static unique_ptr +ParquetWriteInitializeGlobal(ClientContext &context, const FunctionData &bind_data, const string &file_path) { auto global_state = make_uniq(); auto &parquet_bind = bind_data.Cast(); @@ -449,13 +449,13 @@ static unique_ptr ParquetWriteInitializeGlobal(ClientContext return std::move(global_state); } -static void ParquetWriteGetWrittenStatistics(ClientContext &context, FunctionData &bind_data, +static void ParquetWriteGetWrittenStatistics(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, CopyFunctionFileStatistics &statistics) { auto &global_state = gstate.Cast(); global_state.writer->SetWrittenStatistics(statistics); } -static void ParquetWriteSink(ExecutionContext &context, FunctionData &bind_data_p, GlobalFunctionData &gstate, +static void ParquetWriteSink(ExecutionContext &context, const FunctionData &bind_data_p, GlobalFunctionData &gstate, LocalFunctionData &lstate, DataChunk &input) { auto &bind_data = bind_data_p.Cast(); auto &global_state = gstate.Cast(); @@ -473,7 +473,7 @@ static void ParquetWriteSink(ExecutionContext &context, FunctionData &bind_data_ } } -static void ParquetWriteCombine(ExecutionContext &context, FunctionData &bind_data_p, GlobalFunctionData &gstate, +static void ParquetWriteCombine(ExecutionContext &context, const FunctionData &bind_data_p, GlobalFunctionData &gstate, LocalFunctionData &lstate) { auto &bind_data = bind_data_p.Cast(); auto &global_state = gstate.Cast(); @@ -505,7 +505,7 @@ static void ParquetWriteCombine(ExecutionContext &context, FunctionData &bind_da global_state.combine_buffer->Combine(local_state.buffer); } -static void ParquetWriteFinalize(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate) { +static void ParquetWriteFinalize(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate) { auto &global_state = gstate.Cast(); // flush the combine buffer (if it's there) if (global_state.combine_buffer) { @@ -516,7 +516,8 @@ static void ParquetWriteFinalize(ClientContext &context, FunctionData &bind_data global_state.writer->Finalize(); } -static unique_ptr ParquetWriteInitializeLocal(ExecutionContext &context, FunctionData &bind_data_p) { +static unique_ptr ParquetWriteInitializeLocal(ExecutionContext &context, + const FunctionData &bind_data_p) { auto &bind_data = bind_data_p.Cast(); return make_uniq(context.client, bind_data.sql_types); } @@ -923,7 +924,7 @@ struct ParquetWriteBatchData : public PreparedBatchData { PreparedRowGroup prepared_row_group; }; -static unique_ptr ParquetWritePrepareBatch(ClientContext &context, FunctionData &bind_data, +static unique_ptr ParquetWritePrepareBatch(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, unique_ptr collection) { auto &global_state = gstate.Cast(); @@ -936,7 +937,7 @@ static unique_ptr ParquetWritePrepareBatch(ClientContext &con //===--------------------------------------------------------------------===// // Flush Batch //===--------------------------------------------------------------------===// -static void ParquetWriteFlushBatch(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +static void ParquetWriteFlushBatch(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, PreparedBatchData &batch_p) { auto &global_state = gstate.Cast(); auto &batch = batch_p.Cast(); @@ -946,7 +947,7 @@ static void ParquetWriteFlushBatch(ClientContext &context, FunctionData &bind_da //===--------------------------------------------------------------------===// // Desired Batch Size //===--------------------------------------------------------------------===// -static optional_idx ParquetWriteDesiredBatchSize(ClientContext &context, FunctionData &bind_data_p) { +static optional_idx ParquetWriteDesiredBatchSize(ClientContext &context, const FunctionData &bind_data_p) { auto &bind_data = bind_data_p.Cast(); return bind_data.row_group_size; } diff --git a/src/duckdb/extension/parquet/parquet_geometry.cpp b/src/duckdb/extension/parquet/parquet_geometry.cpp index d2ec6ffb9..f0f8823e7 100644 --- a/src/duckdb/extension/parquet/parquet_geometry.cpp +++ b/src/duckdb/extension/parquet/parquet_geometry.cpp @@ -125,6 +125,17 @@ unique_ptr GeoParquetFileMetadata::TryRead(const duckdb_ throw InvalidInputException("Geoparquet column '%s' does not have geometry types", column_name); } + // Parse the edges: anything but (the default) planar edges is a GEOGRAPHY column + const auto edges_val = yyjson_obj_get(column_val, "edges"); + if (edges_val && !yyjson_is_null(edges_val)) { + if (!yyjson_is_str(edges_val)) { + throw InvalidInputException("Geoparquet column '%s' has invalid edges", column_name); + } + if (strcmp(yyjson_get_str(edges_val), "planar") != 0) { + column.geometry_model = GeometryModel::GEODETIC; + } + } + // Parse the CRS const auto crs_val = yyjson_obj_get(column_val, "crs"); if (crs_val && !yyjson_is_null(crs_val)) { @@ -208,10 +219,14 @@ void GeoParquetFileMetadata::AddGeoParquetStats(ClientContext &context, const st // Lock the metadata lock_guard glock(write_lock); + // GEOGRAPHY columns are described with spherical edges, and merge their extents accordingly + const auto geometry_model = Geometry::GetModel(type); + const auto it = geometry_columns.find(column_name); if (it == geometry_columns.end()) { // Add a new column to the metadata auto &column = geometry_columns[column_name]; + column.geometry_model = geometry_model; // Attempt to convert the CRS to PROJJSON if (GeoType::HasCRS(type)) { @@ -219,11 +234,11 @@ void GeoParquetFileMetadata::AddGeoParquetStats(ClientContext &context, const st } // Merge the stats - column.stats.Merge(stats); + column.stats.Merge(stats, geometry_model); column.insertion_index = geometry_columns.size() - 1; } else { - it->second.stats.Merge(stats); + it->second.stats.Merge(stats, geometry_model); } } @@ -291,6 +306,10 @@ void GeoParquetFileMetadata::Write(duckdb_parquet::FileMetaData &file_meta_data) yyjson_mut_arr_add_strcpy(doc, geometry_types, type_name.c_str()); } + if (column.second.geometry_model == GeometryModel::GEODETIC) { + yyjson_mut_obj_add_str(doc, column_json, "edges", "spherical"); + } + const auto &bbox = column.second.stats.extent; if (bbox.HasXY()) { @@ -375,7 +394,8 @@ optional_ptr GeoParquetFileMetadata::GetColumnMe unique_ptr GeometryColumnReader::Create(const ParquetReader &reader, const ParquetColumnSchema &schema, ClientContext &context) { - D_ASSERT(schema.type.id() == LogicalTypeId::GEOMETRY); + const bool is_geography = schema.type.id() == LogicalTypeId::GEOGRAPHY; + D_ASSERT(schema.type.id() == LogicalTypeId::GEOMETRY || is_geography); D_ASSERT(schema.children.size() == 1 && schema.children[0].type.id() == LogicalTypeId::BLOB); // Make a string reader for the underlying WKB data @@ -386,9 +406,10 @@ unique_ptr GeometryColumnReader::Create(const ParquetReader &reade auto ref = make_uniq_base(LogicalTypeId::BLOB, 0); args.push_back(std::move(ref)); - // TODO: Pass the actual target type here so we get the CRS information too - auto func = StGeomfromwkbFun::GetFunction(); - func.SetName("ST_GeomFromWKB"); + // TODO: Pass the actual target type here so we get the CRS information too. + // GEOGRAPHY uses ST_GeogFromWKB, which additionally validates the canonical coordinate ranges. + auto func = is_geography ? StGeogfromwkbFun::GetFunction() : StGeomfromwkbFun::GetFunction(); + func.SetName(is_geography ? "ST_GeogFromWKB" : "ST_GeomFromWKB"); auto read_expr = func.Bind(context, std::move(args)); auto type_expr = BoundCastExpression::AddCastToType(context, std::move(read_expr), schema.type); vector> expression_children; diff --git a/src/duckdb/extension/parquet/parquet_multi_file_info.cpp b/src/duckdb/extension/parquet/parquet_multi_file_info.cpp index 0c7e75dee..3bc0807a2 100644 --- a/src/duckdb/extension/parquet/parquet_multi_file_info.cpp +++ b/src/duckdb/extension/parquet/parquet_multi_file_info.cpp @@ -125,7 +125,7 @@ static bool ParquetScanSupportPushdownExtract(const FunctionData &bind_data_p, c return StructType::IsStruct(column_type) || column_type.id() == LogicalTypeId::VARIANT; } -static vector ParquetGetRowIdColumns(ClientContext &context, optional_ptr bind_data) { +static vector ParquetGetRowIdColumns(ClientContext &context, optional_ptr bind_data) { vector result; result.emplace_back(MultiFileReader::COLUMN_IDENTIFIER_FILE_INDEX); result.emplace_back(MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER); diff --git a/src/duckdb/extension/parquet/parquet_reader.cpp b/src/duckdb/extension/parquet/parquet_reader.cpp index 4d578eaa8..8e493a0b9 100644 --- a/src/duckdb/extension/parquet/parquet_reader.cpp +++ b/src/duckdb/extension/parquet/parquet_reader.cpp @@ -32,6 +32,9 @@ #include "duckdb/planner/table_filter.hpp" #include "duckdb/storage/object_cache.hpp" #include "duckdb/planner/table_filter_state.hpp" +#include "duckdb/planner/filter/table_filter_functions.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/common/multi_file/multi_file_adaptive_filter_cache.hpp" #include "duckdb/common/multi_file/multi_file_data.hpp" #include "duckdb/common/multi_file/multi_file_reader.hpp" @@ -1039,7 +1042,8 @@ unique_ptr ParquetReader::CreateReaderRecursive(ClientContext &con } static bool IsGeometryType(const SchemaElement &s_ele, const ParquetFileMetadataCache &metadata, idx_t depth, - string &crs) { + string &crs, bool &is_geography) { + is_geography = false; const auto is_blob = s_ele.__isset.type && s_ele.type == Type::BYTE_ARRAY; if (!is_blob) { return false; @@ -1056,6 +1060,8 @@ static bool IsGeometryType(const SchemaElement &s_ele, const ParquetFileMetadata const auto is_native_geog = s_ele.__isset.logicalType && s_ele.logicalType.__isset.GEOGRAPHY; if (is_native_geog) { + // The edge-interpolation algorithm is ignored on read; any GEOGRAPHY logical type maps to GEOGRAPHY. + is_geography = true; if (s_ele.logicalType.GEOGRAPHY.__isset.crs) { crs = s_ele.logicalType.GEOGRAPHY.crs; } @@ -1073,6 +1079,7 @@ static bool IsGeometryType(const SchemaElement &s_ele, const ParquetFileMetadata auto meta_ptr = metadata.geo_metadata->GetColumnMeta(s_ele.name); if (meta_ptr) { crs = meta_ptr->projjson; + is_geography = meta_ptr->geometry_model == GeometryModel::GEODETIC; } return true; } @@ -1115,6 +1122,36 @@ static bool IsVariantType(const SchemaElement &root, const vector FindNonBinaryShreddedValue(const ParquetColumnSchema &typed_value) { + if (typed_value.type.id() != LogicalTypeId::STRUCT && typed_value.type.id() != LogicalTypeId::LIST) { + return nullptr; + } + // the fields of an object and the element of an array are groups of 'value' and 'typed_value' + for (auto &group : typed_value.children) { + for (auto &child : group.children) { + if (child.name == "value" && !IsVariantBinaryColumn(child)) { + return &child; + } + if (child.name == "typed_value") { + auto shredded_value = FindNonBinaryShreddedValue(child); + if (shredded_value) { + return shredded_value; + } + } + } + } + return nullptr; +} + ParquetColumnSchema ParquetReader::ParseSchemaRecursive(idx_t depth, idx_t max_define, idx_t max_repeat, idx_t &next_schema_idx, idx_t &next_file_idx, ClientContext &context) { @@ -1146,7 +1183,8 @@ ParquetColumnSchema ParquetReader::ParseSchemaRecursive(idx_t depth, idx_t max_d // Check for geometry type string crs; - if (IsGeometryType(s_ele, *metadata, depth, crs)) { + bool is_geography = false; + if (IsGeometryType(s_ele, *metadata, depth, crs, is_geography)) { // Geometries in both GeoParquet and native parquet are stored as a WKB-encoded BLOB. // Because we don't just want to validate that the WKB encoding is correct, but also transform it into // little-endian if necessary, we cant just make use of the StringColumnReader without heavily modifying it. @@ -1159,10 +1197,10 @@ ParquetColumnSchema ParquetReader::ParseSchemaRecursive(idx_t depth, idx_t max_d LogicalType target_type; auto lookup = CoordinateReferenceSystem::TryIdentify(context, crs); - if (lookup) { - target_type = LogicalType::GEOMETRY(*lookup); + if (is_geography) { + target_type = lookup ? LogicalType::GEOGRAPHY(*lookup) : LogicalType::GEOGRAPHY(); } else { - target_type = LogicalType::GEOMETRY(); + target_type = lookup ? LogicalType::GEOMETRY(*lookup) : LogicalType::GEOMETRY(); } // Inner BLOB schema @@ -1226,16 +1264,23 @@ ParquetColumnSchema ParquetReader::ParseSchemaRecursive(idx_t depth, idx_t max_d is_variant = true; } if (is_variant) { - // the VARIANT reader reads the 'metadata' and 'value' columns as binary + if (child_schemas.size() < 2) { + throw DataCorruptionException("Failed to read Parquet file \"%s\": VARIANT column \"%s\" must have a " + "'metadata' and a 'value' column", + file.path, string(s_ele.name)); + } for (auto &child_schema : child_schemas) { if (child_schema.name != "metadata" && child_schema.name != "value") { + // the 'value' columns of the groups below 'typed_value' are read as binary as well + if (FindNonBinaryShreddedValue(child_schema)) { + throw DataCorruptionException( + "Failed to read Parquet file \"%s\": the 'value' column of a shredded field of VARIANT " + "column \"%s\" must be a binary BYTE_ARRAY column", + file.path, string(s_ele.name)); + } continue; } - // a logical type annotation (e.g. GEOMETRY) would make the column reader produce another type - const auto is_binary = - child_schema.type.id() == LogicalTypeId::BLOB || child_schema.type.id() == LogicalTypeId::VARCHAR; - if (!child_schema.children.empty() || child_schema.parquet_type != duckdb_parquet::Type::BYTE_ARRAY || - !is_binary || child_schema.schema_type != ParquetColumnSchemaType::COLUMN) { + if (!IsVariantBinaryColumn(child_schema)) { throw DataCorruptionException( "Failed to read Parquet file \"%s\": the '%s' column of VARIANT column \"%s\" " "must be a binary BYTE_ARRAY column", @@ -1937,6 +1982,11 @@ bool ParquetReader::FiltersExcludeRowGroup(ClientContext &context, ParquetReader prune_result == FilterPropagateResult::FILTER_FALSE_OR_NULL) { return true; } + if (prune_result == FilterPropagateResult::FILTER_ALWAYS_TRUE) { + scan_filter.filter_state.reset(); + } else if (!scan_filter.filter_state) { + scan_filter.filter_state = TableFilterState::Initialize(context, scan_filter.filter); + } } return false; } @@ -2458,9 +2508,8 @@ idx_t ParquetReader::GetDataSize() const { return data_size; } -ParquetScanFilter::ParquetScanFilter(ClientContext &context, ProjectionIndex filter_idx, TableFilter &filter) +ParquetScanFilter::ParquetScanFilter(ProjectionIndex filter_idx, TableFilter &filter) : filter_idx(filter_idx), filter(filter) { - filter_state = TableFilterState::Initialize(context, filter); } ParquetScanFilter::~ParquetScanFilter() { @@ -2507,7 +2556,7 @@ void ParquetReader::InitializeScan(ClientContext &context, ParquetReaderScanStat state.adaptive_filter_cache.InitializeAdaptiveFilter(*filters, filter_global_indices, context.GetContext().GetLoggerPtr(), file.path); for (auto &entry : *filters) { - state.scan_filters.emplace_back(context, entry.GetIndex(), entry.Filter()); + state.scan_filters.emplace_back(entry.GetIndex(), entry.Filter()); } } if (state.filter_eliminated_all_rows.size() != state.scan_filters.size()) { @@ -2968,8 +3017,12 @@ idx_t ParquetReader::EvaluateFilters(ParquetReaderScanState &state, DataChunk &r auto &result_vector = result.data[local_idx.GetIndex()]; ColumnReaderInput reader_input(scan_count, define_ptr, repeat_ptr); - child_reader.Filter(reader_input, result_vector, scan_filter.filter, *scan_filter.filter_state, state.sel, - filter_count, is_first_filter); + if (scan_filter.filter_state) { + child_reader.Filter(reader_input, result_vector, scan_filter.filter, *scan_filter.filter_state, state.sel, + filter_count, is_first_filter); + } else { + child_reader.Select(reader_input, result_vector, state.sel, filter_count); + } if (log_prefetch) { auto &filters_used = state.prefetch_metrics.logger.filters_used; if (filters_used.size() != state.scan_filters.size()) { diff --git a/src/duckdb/extension/parquet/parquet_statistics.cpp b/src/duckdb/extension/parquet/parquet_statistics.cpp index 7722ee143..2a4c547c5 100644 --- a/src/duckdb/extension/parquet/parquet_statistics.cpp +++ b/src/duckdb/extension/parquet/parquet_statistics.cpp @@ -406,6 +406,12 @@ Value ParquetStatisticsUtils::ConvertValueInternal(const LogicalType &type, cons auto uuid_val = UUIDValueConversion::ReadParquetUUID(const_data_ptr_cast(stats.c_str())); return Value::UUID(uuid_val); } + case LogicalTypeId::SQLNULL: + // a column without values has no minimum or maximum + return Value(); + case LogicalTypeId::INTERVAL: + // Parquet does not define an order for intervals + return Value(); default: throw InternalException("Unsupported type for stats %s", type.ToString()); } @@ -614,19 +620,32 @@ unique_ptr ParquetStatisticsUtils::TransformParquetStatistics( } return string_stats.ToUnique(); } + case LogicalTypeId::GEOGRAPHY: case LogicalTypeId::GEOMETRY: { if (!column_chunk) { break; } + const bool is_geography = type.id() == LogicalTypeId::GEOGRAPHY; auto geo_stats = GeometryStats::CreateUnknown(type); if (column_chunk->meta_data.__isset.geospatial_statistics) { if (column_chunk->meta_data.geospatial_statistics.__isset.bbox) { auto &bbox = column_chunk->meta_data.geospatial_statistics.bbox; auto &stats_bbox = GeometryStats::GetExtent(geo_stats); - // xmin > xmax is allowed if the geometry crosses the antimeridian, - // but we don't handle this right now - if (bbox.xmin <= bbox.xmax) { + // For GEOGRAPHY the bbox is assumed to be a *coverage* bound: it bounds the geodesic edges + // and polygon interiors, not just the coordinate values (which is what we write ourselves, + // and what other spherical engines write - even though the Parquet spec's definition is + // coordinate-based). A file whose writer stored coordinate-only boxes for line/polygon + // geography data may prune incorrectly under this assumption. + // + // xmin > xmax means the bounding box wraps across the antimeridian. This is only valid for + // GEOGRAPHY (whose extent math is antimeridian-aware); for GEOMETRY we ignore such a box. + // The geodetic arc math requires X within [-180, 180], so a file-provided GEOGRAPHY bbox + // outside that range (or NaN) is ignored rather than trusted. + const bool valid_x = is_geography ? bbox.xmin >= -180.0 && bbox.xmin <= 180.0 && bbox.xmax >= -180.0 && + bbox.xmax <= 180.0 + : bbox.xmin <= bbox.xmax; + if (valid_x) { stats_bbox.x_min = bbox.xmin; stats_bbox.x_max = bbox.xmax; } @@ -751,6 +770,8 @@ ParquetStatisticsUtils::TransformColumnStatistics(const ParquetColumnSchema &sch // no stats present for row group return nullptr; } + // every column whose chunk statistics become statistics of the scan gets here, whatever it is nested in + schema.ValidateNullCount(column_chunk); auto &parquet_stats = column_chunk.meta_data.statistics; row_group_stats = TransformParquetStatistics(type, schema, parquet_stats, parquet_options, parquet_options.can_have_nan, &column_chunk); @@ -857,13 +878,28 @@ static bool HasFilterConstants(const Expression &expr, ParquetBloomFilterHashStr if (expr.GetExpressionClass() != ExpressionClass::BOUND_CONJUNCTION) { return false; } - bool child_has_constant = false; - ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { - if (!child_has_constant) { - child_has_constant = HasFilterConstants(child, hash_strategy); - } - }); - return child_has_constant; + switch (expr.GetExpressionType()) { + case ExpressionType::CONJUNCTION_AND: { + bool any_child_has_constant = false; + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { + if (!any_child_has_constant) { + any_child_has_constant = HasFilterConstants(child, hash_strategy); + } + }); + return any_child_has_constant; + } + case ExpressionType::CONJUNCTION_OR: { + bool all_children_have_constants = true; + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { + if (all_children_have_constants) { + all_children_have_constants = HasFilterConstants(child, hash_strategy); + } + }); + return all_children_have_constants; + } + default: + return false; + } } static bool HasFilterConstants(const TableFilter &duckdb_filter, ParquetBloomFilterHashStrategy hash_strategy) { diff --git a/src/duckdb/extension/parquet/parquet_writer.cpp b/src/duckdb/extension/parquet/parquet_writer.cpp index 8e40d653f..884bece93 100644 --- a/src/duckdb/extension/parquet/parquet_writer.cpp +++ b/src/duckdb/extension/parquet/parquet_writer.cpp @@ -161,6 +161,7 @@ bool ParquetWriter::TryGetParquetType(const LogicalType &duckdb_type, optional_p case LogicalTypeId::BLOB: case LogicalTypeId::VARCHAR: case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: parquet_type = Type::BYTE_ARRAY; break; case LogicalTypeId::TIME: @@ -407,6 +408,31 @@ void ParquetWriter::SetSchemaProperties(const LogicalType &duckdb_type, duckdb_p } } break; + case LogicalTypeId::GEOGRAPHY: + if (allow_geometry) { // Don't set this if we write GeoParquet V1 + schema_ele.__isset.logicalType = true; + schema_ele.logicalType.__isset.GEOGRAPHY = true; + // GEOGRAPHY assumes geodesic (spherical) edge interpolation. + schema_ele.logicalType.GEOGRAPHY.__set_algorithm(duckdb_parquet::EdgeInterpolationAlgorithm::SPHERICAL); + if (GeoType::HasCRS(duckdb_type)) { + const auto &crs = GeoType::GetCRS(duckdb_type); + + if (crs.GetType() != CoordinateReferenceSystemType::PROJJSON) { + // Try to convert to GeoJSON + const auto lookup = + CoordinateReferenceSystem::TryConvert(context, crs, CoordinateReferenceSystemType::PROJJSON); + if (lookup) { + schema_ele.logicalType.GEOGRAPHY.__isset.crs = true; + schema_ele.logicalType.GEOGRAPHY.crs = lookup->GetDefinition(); + break; + } + } + + schema_ele.logicalType.GEOGRAPHY.__isset.crs = true; + schema_ele.logicalType.GEOGRAPHY.crs = crs.GetDefinition(); + } + } + break; case LogicalTypeId::SQLNULL: schema_ele.__isset.logicalType = true; schema_ele.logicalType.__set_UNKNOWN(duckdb_parquet::NullType()); @@ -1101,14 +1127,20 @@ struct BlobStatsUnifier : public BaseStringStatsUnifier { }; struct GeoStatsUnifier : public ColumnStatsUnifier { + explicit GeoStatsUnifier(GeometryModel geometry_model) : geometry_model(geometry_model) { + } + + GeometryModel geometry_model; + void UnifyGeoStats(const GeometryStatsData &other) override { if (geo_stats) { - geo_stats->Merge(other); + geo_stats->Merge(other, geometry_model); } else { - // Make copy + // Make copy (GeometryStatsData is trivially constructible, so copy every member explicitly) geo_stats = make_uniq(); geo_stats->extent = other.extent; geo_stats->types = other.types; + geo_stats->flags = other.flags; } } @@ -1267,7 +1299,8 @@ static unique_ptr GetBaseStatsUnifier(const LogicalType &typ case LogicalTypeId::BLOB: return make_uniq(); case LogicalTypeId::GEOMETRY: - return make_uniq(); + case LogicalTypeId::GEOGRAPHY: + return make_uniq(Geometry::GetModel(type)); case LogicalTypeId::VARCHAR: return make_uniq(); case LogicalTypeId::UUID: diff --git a/src/duckdb/extension/parquet/read_single_parquet_file.cpp b/src/duckdb/extension/parquet/read_single_parquet_file.cpp index b78bece80..1b904ef04 100644 --- a/src/duckdb/extension/parquet/read_single_parquet_file.cpp +++ b/src/duckdb/extension/parquet/read_single_parquet_file.cpp @@ -427,7 +427,7 @@ static virtual_column_map_t ReadSingleParquetFileVirtualColumns(ClientContext &c //! The row number within the file identifies a row of a single file static vector ReadSingleParquetFileRowIdColumns(ClientContext &context, - optional_ptr bind_data) { + optional_ptr bind_data) { return {MultiFileReader::COLUMN_IDENTIFIER_FILE_ROW_NUMBER}; } @@ -484,7 +484,7 @@ bool ParquetScanFunction::ProjectionExpressionPushdown(ClientContext &context, if (const Identifier &name = fn.Function().GetName(); name != "strlen" && name != "octet_length") { return false; } - auto &bind_data = input.get.bind_data->CastNoConst(); + auto &bind_data = input.get.bind_data.write().Cast(); // Don't do pushdown on custom schema users like Ducklake, or when the schemas of several files are unified if (!bind_data.reader_bind.schema.empty() || bind_data.file_options.union_by_name) { return false; diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index e325c4292..9c0b2e913 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-alpha55959"; + descriptor->api_version = "v2.1.0-alpha56986"; 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-alpha55959"; + descriptor->api_version = "v2.1.0-alpha56986"; 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-alpha55959"; + descriptor->api_version = "v2.1.0-alpha56986"; 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-alpha55959"; + descriptor->api_version = "v2.1.0-alpha56986"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/catalog/catalog.cpp b/src/duckdb/src/catalog/catalog.cpp index cc8cb4151..510a089fc 100644 --- a/src/duckdb/src/catalog/catalog.cpp +++ b/src/duckdb/src/catalog/catalog.cpp @@ -17,7 +17,6 @@ #include "duckdb/parser/parsed_data/alter_schema_info.hpp" #include "duckdb/parser/parsed_data/alter_table_info.hpp" #include "duckdb/parser/parsed_data/create_aggregate_function_info.hpp" -#include "duckdb/parser/parsed_data/create_collation_info.hpp" #include "duckdb/parser/parsed_data/create_coordinate_system_info.hpp" #include "duckdb/parser/parsed_data/create_copy_function_info.hpp" #include "duckdb/parser/parsed_data/create_index_info.hpp" @@ -135,10 +134,8 @@ optional_ptr Catalog::CreateSchema(ClientContext &context, CreateS return CreateSchema(GetCatalogTransaction(context), info); } -void Catalog::CheckNestedSchemaSupport(const QualifiedName &name, CatalogType type) const { - if (SupportsNestedSchemas()) { - return; - } +//! The end of the schema path of name if that path is nested, or 0 if it is not +static idx_t NestedSchemaPathEnd(const QualifiedName &name, CatalogType type) { auto &path = name.Path(); auto end = path.size(); if (type != CatalogType::SCHEMA_ENTRY && end > 0) { @@ -150,11 +147,33 @@ void Catalog::CheckNestedSchemaSupport(const QualifiedName &name, CatalogType ty while (path[end - 1].empty()) { end--; } - auto schema_path = - QualifiedName::FromPath(vector(path.begin() + 1, path.begin() + NumericCast(end))); - throw BinderException("Catalog %s does not support nested schemas: %s", GetName(), schema_path.ToString()); + return end; } } + return 0; +} + +bool Catalog::SupportsSchemaPath(const QualifiedName &name, CatalogType type) const { + return SupportsNestedSchemas() || NestedSchemaPathEnd(name, type) == 0; +} + +void Catalog::CheckNestedSchemaSupport(const QualifiedName &name, CatalogType type) const { + if (SupportsSchemaPath(name, type)) { + return; + } + auto end = NestedSchemaPathEnd(name, type); + auto &path = name.Path(); + auto schema_path = + QualifiedName::FromPath(vector(path.begin() + 1, path.begin() + NumericCast(end))); + throw BinderException("Catalog %s does not support nested schemas: %s", GetName(), schema_path.ToString()); +} + +static optional_ptr UnsupportedSchemaPath(const EntryLookupInfo &schema_lookup, + OnEntryNotFound if_not_found) { + if (if_not_found == OnEntryNotFound::THROW_EXCEPTION) { + throw CatalogException::MissingEntry(schema_lookup, string()); + } + return nullptr; } CatalogTransaction Catalog::GetCatalogTransaction(ClientContext &context) { @@ -328,23 +347,6 @@ optional_ptr Catalog::AddFunction(ClientContext &context, CreateFu return CreateFunction(context, info); } -//===--------------------------------------------------------------------===// -// Collation -//===--------------------------------------------------------------------===// -optional_ptr Catalog::CreateCollation(CatalogTransaction transaction, CreateCollationInfo &info) { - auto &schema = GetEntrySchema(transaction, info.GetQualifiedName()); - return CreateCollation(transaction, schema, info); -} - -optional_ptr Catalog::CreateCollation(ClientContext &context, CreateCollationInfo &info) { - return CreateCollation(GetCatalogTransaction(context), info); -} - -optional_ptr Catalog::CreateCollation(CatalogTransaction transaction, SchemaCatalogEntry &schema, - CreateCollationInfo &info) { - return schema.CreateCollation(transaction, info); -} - //===--------------------------------------------------------------------===// // Coordinate System //===--------------------------------------------------------------------===// @@ -461,7 +463,11 @@ struct CatalogLookup { void Catalog::DropEntry(ClientContext &context, DropInfo &info) { if (info.type == CatalogType::SCHEMA_ENTRY) { // DROP SCHEMA - CheckNestedSchemaSupport(info.GetQualifiedName(), CatalogType::SCHEMA_ENTRY); + if (!SupportsSchemaPath(info.GetQualifiedName(), CatalogType::SCHEMA_ENTRY)) { + UnsupportedSchemaPath(EntryLookupInfo(CatalogType::SCHEMA_ENTRY, info.GetQualifiedName()), + info.if_not_found); + return; + } DropSchema(context, info); return; } @@ -507,7 +513,9 @@ optional_ptr Catalog::GetSchema(CatalogTransaction transacti optional_ptr Catalog::GetSchema(ClientContext &context, const EntryLookupInfo &schema_lookup, OnEntryNotFound if_not_found) { - CheckNestedSchemaSupport(schema_lookup.GetQualifiedName(), CatalogType::SCHEMA_ENTRY); + if (!SupportsSchemaPath(schema_lookup.GetQualifiedName(), CatalogType::SCHEMA_ENTRY)) { + return UnsupportedSchemaPath(schema_lookup, if_not_found); + } return LookupSchema(GetCatalogTransaction(context), schema_lookup, if_not_found); } @@ -607,7 +615,9 @@ optional_ptr Catalog::LookupSchemaPath(CatalogTransaction transaction, const EntryLookupInfo &schema_lookup, OnEntryNotFound if_not_found, const std::function(const EntryLookupInfo &)> &lookup_root) { - CheckNestedSchemaSupport(schema_lookup.GetQualifiedName(), CatalogType::SCHEMA_ENTRY); + if (!SupportsSchemaPath(schema_lookup.GetQualifiedName(), CatalogType::SCHEMA_ENTRY)) { + return UnsupportedSchemaPath(schema_lookup, if_not_found); + } auto &path = schema_lookup.GetQualifiedName().Path(); optional_ptr schema; // Bound schema lookups lead with the catalog; bare lookups contain just the schema name. @@ -669,7 +679,9 @@ SchemaCatalogEntry &Catalog::GetSchema(ClientContext &context, const Identifier } SchemaCatalogEntry &Catalog::GetSchema(CatalogTransaction transaction, const EntryLookupInfo &schema_lookup) { - CheckNestedSchemaSupport(schema_lookup.GetQualifiedName(), CatalogType::SCHEMA_ENTRY); + if (!SupportsSchemaPath(schema_lookup.GetQualifiedName(), CatalogType::SCHEMA_ENTRY)) { + return *UnsupportedSchemaPath(schema_lookup, OnEntryNotFound::THROW_EXCEPTION); + } return *LookupSchema(transaction, schema_lookup, OnEntryNotFound::THROW_EXCEPTION); } @@ -1039,7 +1051,9 @@ CatalogException Catalog::CreateMissingEntryException(CatalogEntryRetriever &ret } CatalogEntryLookup Catalog::TryLookupEntry(CatalogTransaction transaction, const EntryLookupInfo &lookup_info) { - CheckNestedSchemaSupport(lookup_info.GetQualifiedName(), lookup_info.GetCatalogType()); + if (!SupportsSchemaPath(lookup_info.GetQualifiedName(), lookup_info.GetCatalogType())) { + return {nullptr, nullptr, ErrorData()}; + } return TryLookupEntryInternal(transaction, lookup_info); } 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 d2df08a3b..70dd8e76e 100644 --- a/src/duckdb/src/catalog/catalog_entry/duck_schema_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/duck_schema_entry.cpp @@ -2,7 +2,6 @@ #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry/aggregate_function_catalog_entry.hpp" -#include "duckdb/catalog/catalog_entry/collate_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/coordinate_system_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/copy_function_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/duck_index_entry.hpp" @@ -27,7 +26,6 @@ #include "duckdb/parser/constraints/foreign_key_constraint.hpp" #include "duckdb/parser/parsed_data/alter_table_info.hpp" #include "duckdb/parser/parsed_data/create_aggregate_function_info.hpp" -#include "duckdb/parser/parsed_data/create_collation_info.hpp" #include "duckdb/parser/parsed_data/create_copy_function_info.hpp" #include "duckdb/parser/parsed_data/create_index_info.hpp" #include "duckdb/parser/parsed_data/create_pragma_function_info.hpp" @@ -79,7 +77,7 @@ DuckSchemaEntry::DuckSchemaEntry(Catalog &catalog, CreateSchemaInfo &info, catalog.IsSystemCatalog() ? make_uniq(catalog, *this) : nullptr), copy_functions(catalog), pragma_functions(catalog), functions(catalog, catalog.IsSystemCatalog() ? make_uniq(catalog, *this) : nullptr), - sequences(catalog), collations(catalog), types(catalog, make_uniq(catalog, *this)), + sequences(catalog), types(catalog, make_uniq(catalog, *this)), coordinate_systems( catalog, catalog.IsSystemCatalog() ? make_uniq(catalog, *this) : nullptr) { } @@ -286,12 +284,6 @@ optional_ptr DuckSchemaEntry::CreateIndex(CatalogTransaction trans return AddEntryInternal(transaction, std::move(index), info.on_conflict, dependencies); } -optional_ptr DuckSchemaEntry::CreateCollation(CatalogTransaction transaction, CreateCollationInfo &info) { - auto collation = make_uniq(catalog, *this, info); - collation->internal = info.internal; - return AddEntry(transaction, std::move(collation), info.on_conflict); -} - optional_ptr DuckSchemaEntry::CreateCoordinateSystem(CatalogTransaction transaction, CreateCoordinateSystemInfo &info) { auto coordinate_system = make_uniq(catalog, *this, info); @@ -431,8 +423,6 @@ CatalogSet &DuckSchemaEntry::GetCatalogSet(CatalogType type) { return functions; case CatalogType::SEQUENCE_ENTRY: return sequences; - case CatalogType::COLLATION_ENTRY: - return collations; case CatalogType::COORDINATE_SYSTEM_ENTRY: return coordinate_systems; case CatalogType::TYPE_ENTRY: @@ -453,7 +443,6 @@ void DuckSchemaEntry::Verify(Catalog &catalog) { pragma_functions.Verify(catalog); functions.Verify(catalog); sequences.Verify(catalog); - collations.Verify(catalog); types.Verify(catalog); } diff --git a/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp b/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp index a3c1d870f..3acaff029 100644 --- a/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp @@ -205,10 +205,6 @@ void ViewCatalogEntry::UpdateBinding(const vector &types_p, const v } string ViewCatalogEntry::ToSQL() const { - if (sql.empty()) { - //! Return empty sql with view name so pragma view_tables don't complain - return sql; - } auto info = GetInfo(); info->StripCatalogQualification(); auto result = info->ToString(); diff --git a/src/duckdb/src/catalog/default/default_types.cpp b/src/duckdb/src/catalog/default/default_types.cpp index abe90a6f0..c7dda71ba 100644 --- a/src/duckdb/src/catalog/default/default_types.cpp +++ b/src/duckdb/src/catalog/default/default_types.cpp @@ -333,48 +333,76 @@ void RegisterVariantConstructors(TypeConstructorSet &set) { } //---------------------------------------------------------------------------------------------------------------------- -// GEOMETRY Type +// GEOMETRY / GEOGRAPHY Types //---------------------------------------------------------------------------------------------------------------------- +static LogicalType BindDefaultGeoType(bool geography) { + return geography ? LogicalType::GEOGRAPHY() : LogicalType::GEOMETRY(); +} + LogicalType BindDefaultGeometryType(BindLogicalTypeInput &input) { - return LogicalType::GEOMETRY(); + return BindDefaultGeoType(false); } -LogicalType BindGeometryType(BindLogicalTypeInput &input) { +LogicalType BindDefaultGeographyType(BindLogicalTypeInput &input) { + return BindDefaultGeoType(true); +} + +static LogicalType BindGeoType(BindLogicalTypeInput &input, bool geography) { + const char *type_name = geography ? "GEOGRAPHY" : "GEOMETRY"; + // FIXME: Use extension/ClientContext to expand incomplete/shorthand CRS definitions auto &crs = StringValue::Get(input.modifiers[0].GetValue()); if (!input.context) { - throw BinderException(input.query_location, - "Cannot create GEOMETRY type with coordinate system without a connection"); + throw BinderException(input.query_location, "Cannot create %s type with coordinate system without a connection", + type_name); } const auto crs_result = CoordinateReferenceSystem::TryIdentify(*input.context, crs); if (!crs_result) { if (Settings::Get(*input.context)) { - // Ignored by user configuration - return generic GEOMETRY type - return LogicalType::GEOMETRY(); + // Ignored by user configuration - return generic GEOMETRY/GEOGRAPHY type + return BindDefaultGeoType(geography); } throw BinderException( input.GetLocation(0), - "Encountered unrecognized coordinate system '%s' when trying to create GEOMETRY type\n" + "Encountered unrecognized coordinate system '%s' when trying to create %s type\n" "The coordinate system definition may be incomplete or invalid. Your options are as follows:\n" "* Load an extension that can identify this coordinate system\n" "* Provide a full coordinate system definition in e.g. \"PROJJSON\" or \"WKT2\" format\n" "* Set the 'ignore_unknown_crs' configuration option to drop the coordinate system from the resulting " - "geometry type and make this error go away", - crs); + "type and make this error go away", + crs, type_name); } - return LogicalType::GEOMETRY(crs_result->GetDefinition()); + return geography ? LogicalType::GEOGRAPHY(crs_result->GetDefinition()) + : LogicalType::GEOMETRY(crs_result->GetDefinition()); } -void RegisterGeometryConstructors(TypeConstructorSet &set) { - set.AddFunction(TypeConstructor(TypeConstructor::Signature(), BindDefaultGeometryType)); +LogicalType BindGeometryType(BindLogicalTypeInput &input) { + return BindGeoType(input, false); +} + +LogicalType BindGeographyType(BindLogicalTypeInput &input) { + return BindGeoType(input, true); +} + +static void RegisterGeoConstructors(TypeConstructorSet &set, bind_logical_type_function_t bind_default, + bind_logical_type_function_t bind_with_crs) { + set.AddFunction(TypeConstructor(TypeConstructor::Signature(), bind_default)); auto signature = TypeConstructor::Signature(); signature.AddParameter("crs", LogicalType::VARCHAR); - set.AddFunction(TypeConstructor(std::move(signature), BindGeometryType)); + set.AddFunction(TypeConstructor(std::move(signature), bind_with_crs)); +} + +void RegisterGeometryConstructors(TypeConstructorSet &set) { + RegisterGeoConstructors(set, BindDefaultGeometryType, BindGeometryType); +} + +void RegisterGeographyConstructors(TypeConstructorSet &set) { + RegisterGeoConstructors(set, BindDefaultGeographyType, BindGeographyType); } //---------------------------------------------------------------------------------------------------------------------- @@ -390,7 +418,7 @@ struct DefaultType { constructor_registration_t register_constructors; }; -using builtin_type_array = std::array; +using builtin_type_array = std::array; const builtin_type_array BUILTIN_TYPES = {{{"decimal", LogicalTypeId::DECIMAL, RegisterDecimalConstructors}, {"dec", LogicalTypeId::DECIMAL, RegisterDecimalConstructors}, @@ -474,6 +502,7 @@ const builtin_type_array BUILTIN_TYPES = {{{"decimal", LogicalTypeId::DECIMAL, R {"double", LogicalTypeId::DOUBLE, nullptr}, {"float8", LogicalTypeId::DOUBLE, nullptr}, {"geometry", LogicalTypeId::GEOMETRY, RegisterGeometryConstructors}, + {"geography", LogicalTypeId::GEOGRAPHY, RegisterGeographyConstructors}, {"type", LogicalTypeId::TYPE, nullptr}}}; TypeConstructorSet GetConstructors(const DefaultType &entry, const Identifier &name) { diff --git a/src/duckdb/src/common/arrow/arrow_type_extension.cpp b/src/duckdb/src/common/arrow/arrow_type_extension.cpp index a41f8dfec..ea9a61e22 100644 --- a/src/duckdb/src/common/arrow/arrow_type_extension.cpp +++ b/src/duckdb/src/common/arrow/arrow_type_extension.cpp @@ -7,9 +7,11 @@ #include "duckdb/common/arrow/arrow_converter.hpp" #include "duckdb/common/arrow/schema_metadata.hpp" #include "duckdb/common/types/vector.hpp" +#include "duckdb/common/types/geometry.hpp" #include "duckdb/common/types/geometry_crs.hpp" #include "duckdb/common/json_document.hpp" #include "duckdb/common/vector/struct_vector.hpp" +#include "duckdb/common/vector/vector_iterator.hpp" #include "duckdb/common/types/variant/parquet_variant_iterator.hpp" namespace duckdb { @@ -392,6 +394,7 @@ struct ArrowGeometry { const auto extension_metadata = schema_metadata.GetOption(ArrowSchemaMetadata::ARROW_METADATA_KEY); unique_ptr duckdb_crs; + bool is_geography = false; if (!extension_metadata.empty()) { JSONParseError error; @@ -405,9 +408,11 @@ struct ArrowGeometry { throw SerializationException("Invalid GeoArrow metadata: not a JSON object"); } + // "edges" selects the interpolation: "planar" (or absent) maps to GEOMETRY, any non-planar + // value (e.g. "spherical") maps to GEOGRAPHY. We don't otherwise interpret the algorithm. auto edges = val.GetMember("edges"); if (edges.IsString() && edges.GetString() != "planar") { - throw NotImplementedException("Can't import non-planar edges"); + is_geography = true; } // Pick out the CRS if present @@ -420,8 +425,13 @@ struct ArrowGeometry { } } - // Create the geometry type, with or without CRS - auto geo_type = duckdb_crs ? LogicalType::GEOMETRY(*duckdb_crs) : LogicalType::GEOMETRY(); + // Create the geometry/geography type, with or without CRS + LogicalType geo_type; + if (is_geography) { + geo_type = duckdb_crs ? LogicalType::GEOGRAPHY(*duckdb_crs) : LogicalType::GEOGRAPHY(); + } else { + geo_type = duckdb_crs ? LogicalType::GEOMETRY(*duckdb_crs) : LogicalType::GEOMETRY(); + } const auto format = string(schema.format); if (format == "z") { @@ -497,6 +507,11 @@ struct ArrowGeometry { auto root = writer.CreateObject(); writer.SetRoot(root); + // GEOGRAPHY assumes geodesic (spherical) edge interpolation; GEOMETRY uses the default planar edges. + if (type.id() == LogicalTypeId::GEOGRAPHY) { + root.AddString("edges", "spherical"); + } + if (GeoType::HasCRS(type)) { WriteCRS(writer, root, GeoType::GetCRS(type), context); } @@ -519,6 +534,18 @@ struct ArrowGeometry { static void ArrowToDuck(ClientContext &, Vector &source, Vector &result, idx_t count) { Geometry::FromBinary(source, result, count, true); + + if (result.GetType().id() != LogicalTypeId::GEOGRAPHY) { + return; + } + // GEOGRAPHY coordinates must lie within the canonical ranges: the geodetic statistics math + // relies on it, so imported data is validated just like ST_GeogFromWKB. + for (auto entry : result.ValidValues()) { + if (!Geometry::IsValidGeography(entry.GetValue())) { + throw InvalidInputException("GEOGRAPHY import: coordinates are outside the canonical ranges " + "(longitude/X must be within [-180, 180], latitude/Y within [-90, 90])"); + } + } } static void DuckToArrow(ClientContext &context, const Vector &source, Vector &result, idx_t count) { @@ -760,6 +787,16 @@ void ArrowTypeExtensionSet::Initialize(const DBConfig &config) { make_shared_ptr(LogicalType::GEOMETRY(), LogicalType::BLOB, ArrowGeometry::ArrowToDuck, ArrowGeometry::DuckToArrow)}); + // GEOGRAPHY shares the geoarrow.wkb encoding with GEOMETRY; the "edges" metadata distinguishes them on import + // (spherical -> GEOGRAPHY). It is registered under a distinct internal key so the registry does not see a + // duplicate extension; ArrowGeometry::PopulateSchema still emits the canonical "geoarrow.wkb" name (with + // edges=spherical) on export, and import always resolves "geoarrow.wkb" to the GEOMETRY entry above whose + // GetType inspects the edges to pick GEOMETRY vs GEOGRAPHY. + config.RegisterArrowExtension( + {"geoarrow.wkb.geography", ArrowGeometry::PopulateSchema, ArrowGeometry::GetType, + make_shared_ptr(LogicalType::GEOGRAPHY(), LogicalType::BLOB, + ArrowGeometry::ArrowToDuck, ArrowGeometry::DuckToArrow)}); + // Types that are 1:n config.RegisterArrowExtension({"arrow.json", &ArrowJson::PopulateSchema, &ArrowJson::GetType, make_shared_ptr(LogicalType::JSON())}); diff --git a/src/duckdb/src/common/bignum.cpp b/src/duckdb/src/common/bignum.cpp index b2ad96404..5845b0442 100644 --- a/src/duckdb/src/common/bignum.cpp +++ b/src/duckdb/src/common/bignum.cpp @@ -905,10 +905,7 @@ void BignumArithmeticState::AccountWork(idx_t work) { if (work_since_interrupt_check >= INTERRUPT_CHECK_INTERVAL) { work_since_interrupt_check = 0; // the calls are already a millisecond of work apart, so the deadline is read on every one of them - auto client_context = context->TryGetClientContext(); - if (client_context) { - client_context->BlockingInterruptCheck(); - } + context->InterruptCheck(); } } @@ -923,9 +920,70 @@ void BignumIntermediate::MultiplyMagnitudes(BignumArithmeticState &state, const TrimMagnitude(result); } +//! The full product of two 128-bit magnitudes fits four limbs. +static string_t MultiplySmall(StringHeap &heap, uhugeint_t lhs, uhugeint_t rhs, bool is_negative) { + uint64_t product[4]; + product[0] = BignumLimb::MultiplyAdd(lhs.lower, rhs.lower, 0, product[1]); + product[2] = 0; + product[3] = 0; + if (lhs.upper) { + product[1] = BignumLimb::MultiplyAdd(lhs.upper, rhs.lower, product[1], product[2]); + } + if (rhs.upper) { + uint64_t carry; + product[1] = BignumLimb::MultiplyAdd(lhs.lower, rhs.upper, product[1], carry); + product[2] = BignumLimb::MultiplyAdd(lhs.upper, rhs.upper, product[2], product[3]); + product[2] += carry; + product[3] += product[2] < carry; + } + idx_t count = 4; + while (count > 1 && product[count - 1] == 0) { + count--; + } + if (count == 1 && product[0] == 0) { + return WriteZero(heap); + } + const auto top_bytes = BignumLimb::ByteCount(product[count - 1]); + const auto byte_count = (count - 1) * BignumLimb::BYTES + top_bytes; + auto target = heap.EmptyString(byte_count + Bignum::BIGNUM_HEADER_SIZE); + auto ptr = target.GetDataWriteable(); + Bignum::SetHeader(ptr, byte_count, is_negative); + auto out = reinterpret_cast(ptr + Bignum::BIGNUM_HEADER_SIZE); + BignumLimb::StoreMagnitudePartial(out, top_bytes, product[--count], is_negative); + out += top_bytes; + while (count > 0) { + BignumLimb::StoreMagnitude(out, product[--count], is_negative); + out += BignumLimb::BYTES; + } + target.Finalize(); + return target; +} + +string_t BignumIntermediate::Multiply(StringHeap &heap, hugeint_t lhs, hugeint_t rhs) { + const bool lhs_negative = lhs.upper < 0; + const bool rhs_negative = rhs.upper < 0; + uhugeint_t lhs_magnitude(static_cast(lhs.upper), lhs.lower); + uhugeint_t rhs_magnitude(static_cast(rhs.upper), rhs.lower); + if (lhs_negative) { + lhs_magnitude = ~lhs_magnitude + uhugeint_t(1); + } + if (rhs_negative) { + rhs_magnitude = ~rhs_magnitude + uhugeint_t(1); + } + return MultiplySmall(heap, lhs_magnitude, rhs_magnitude, lhs_negative != rhs_negative); +} + string_t BignumIntermediate::Multiply(StringHeap &heap, BignumArithmeticState &state, const BignumIntermediate &lhs, const BignumIntermediate &rhs) { const bool is_result_negative = lhs.is_negative != rhs.is_negative; + if (lhs.size <= 2 * BignumLimb::BYTES && rhs.size <= 2 * BignumLimb::BYTES) { + state.AccountWork(4); + const uhugeint_t lhs_magnitude(LoadAbsoluteLimb(lhs, int64_t(lhs.size) - int64_t(BignumLimb::BYTES)), + LoadAbsoluteLimb(lhs, lhs.size)); + const uhugeint_t rhs_magnitude(LoadAbsoluteLimb(rhs, int64_t(rhs.size) - int64_t(BignumLimb::BYTES)), + LoadAbsoluteLimb(rhs, rhs.size)); + return MultiplySmall(heap, lhs_magnitude, rhs_magnitude, is_result_negative); + } auto &lhs_digits = state.lhs_digits; auto &rhs_digits = state.rhs_digits; auto &product = state.result_digits; diff --git a/src/duckdb/src/common/csv_writer.cpp b/src/duckdb/src/common/csv_writer.cpp index 719f694e4..ea7db5ea3 100644 --- a/src/duckdb/src/common/csv_writer.cpp +++ b/src/duckdb/src/common/csv_writer.cpp @@ -42,6 +42,7 @@ CSVWriterOptions::CSVWriterOptions(const string &delim, const char "e, const if (!write_newline.empty()) { newline = TransformNewLine(write_newline); + requires_quotes[static_cast(newline[0])] = true; } } @@ -70,7 +71,7 @@ CSVWriter::CSVWriter(WriteStream &stream, vector name_list, bool sha } } -CSVWriter::CSVWriter(CSVReaderOptions &options_p, AsyncFileWriter &file_writer_p, bool shared) +CSVWriter::CSVWriter(const CSVReaderOptions &options_p, AsyncFileWriter &file_writer_p, bool shared) : options(options_p), writer_options(options.dialect_options.state_machine_options.delimiter.GetValue(), options.dialect_options.state_machine_options.quote.GetValue(), options.write_newline, GetWriteCommentChar(options)), @@ -80,7 +81,7 @@ CSVWriter::CSVWriter(CSVReaderOptions &options_p, AsyncFileWriter &file_writer_p } } -CSVWriter::CSVWriter(CSVReaderOptions &options_p, FileSystem &fs, const string &file_path, +CSVWriter::CSVWriter(const CSVReaderOptions &options_p, FileSystem &fs, const string &file_path, FileCompressionType compression, QueryContext context, bool shared) : options(options_p), writer_options(options.dialect_options.state_machine_options.delimiter.GetValue(), options.dialect_options.state_machine_options.quote.GetValue(), diff --git a/src/duckdb/src/common/enum_util.cpp b/src/duckdb/src/common/enum_util.cpp index 6de99a027..99143a05c 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -63,6 +63,7 @@ #include "duckdb/common/enums/ordinality_request_type.hpp" #include "duckdb/common/enums/output_type.hpp" #include "duckdb/common/enums/physical_operator_type.hpp" +#include "duckdb/common/enums/pipeline_execution_order.hpp" #include "duckdb/common/enums/prepared_statement_mode.hpp" #include "duckdb/common/enums/preserve_order.hpp" #include "duckdb/common/enums/profiling_coverage.hpp" @@ -70,7 +71,6 @@ #include "duckdb/common/enums/query_result_memory_type.hpp" #include "duckdb/common/enums/query_result_state.hpp" #include "duckdb/common/enums/regex_match_operator_semantics.hpp" -#include "duckdb/common/enums/relation_type.hpp" #include "duckdb/common/enums/result_lifetime.hpp" #include "duckdb/common/enums/result_ordering.hpp" #include "duckdb/common/enums/row_group_append_mode.hpp" @@ -176,7 +176,9 @@ #include "duckdb/optimizer/aggregate_rewrite.hpp" #include "duckdb/optimizer/build_probe_side_optimizer.hpp" #include "duckdb/optimizer/compressed_materialization.hpp" +#include "duckdb/optimizer/distinctness.hpp" #include "duckdb/optimizer/join_order/join_order_operator.hpp" +#include "duckdb/optimizer/join_simplification.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics.hpp" #include "duckdb/optimizer/remove_unused_columns.hpp" #include "duckdb/optimizer/rule/like_optimizations.hpp" @@ -217,6 +219,7 @@ #include "duckdb/parser/peg/matcher/operator_matcher.hpp" #include "duckdb/parser/peg/parsed_grammar.hpp" #include "duckdb/parser/peg/sql_formatter.hpp" +#include "duckdb/parser/peg/tokenizer/tokenizer.hpp" #include "duckdb/parser/peg/transformer/parse_result.hpp" #include "duckdb/parser/peg/transformer/peg_transformer.hpp" #include "duckdb/parser/qualified_name.hpp" @@ -388,6 +391,24 @@ AdaptiveFilterSource EnumUtil::FromString(const char *valu return static_cast(StringUtil::StringToEnum(GetAdaptiveFilterSourceValues(), 2, "AdaptiveFilterSource", value)); } +const StringUtil::EnumStringLiteral *GetAggregateCombineSourceRetentionValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(AggregateCombineSourceRetention::MAY_RETAIN), "MAY_RETAIN" }, + { static_cast(AggregateCombineSourceRetention::NEVER_RETAINS), "NEVER_RETAINS" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(AggregateCombineSourceRetention value) { + return StringUtil::EnumToString(GetAggregateCombineSourceRetentionValues(), 2, "AggregateCombineSourceRetention", static_cast(value)); +} + +template<> +AggregateCombineSourceRetention EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetAggregateCombineSourceRetentionValues(), 2, "AggregateCombineSourceRetention", value)); +} + const StringUtil::EnumStringLiteral *GetAggregateCombineTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(AggregateCombineType::PRESERVE_INPUT), "PRESERVE_INPUT" }, @@ -2168,6 +2189,24 @@ DistinctType EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetDistinctTypeValues(), 2, "DistinctType", value)); } +const StringUtil::EnumStringLiteral *GetDistinctnessPropagationValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(DistinctnessPropagation::UNARY_OPERATORS), "UNARY_OPERATORS" }, + { static_cast(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS), "UNARY_OPERATORS_AND_JOINS" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(DistinctnessPropagation value) { + return StringUtil::EnumToString(GetDistinctnessPropagationValues(), 2, "DistinctnessPropagation", static_cast(value)); +} + +template<> +DistinctnessPropagation EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetDistinctnessPropagationValues(), 2, "DistinctnessPropagation", value)); +} + const StringUtil::EnumStringLiteral *GetErrorTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(ErrorType::UNSIGNED_EXTENSION), "UNSIGNED_EXTENSION" }, @@ -2625,6 +2664,9 @@ const StringUtil::EnumStringLiteral *GetExtensionUpdateResultTagValues() { { static_cast(ExtensionUpdateResultTag::NOT_INSTALLED), "NOT_INSTALLED" }, { static_cast(ExtensionUpdateResultTag::STATICALLY_LOADED), "STATICALLY_LOADED" }, { static_cast(ExtensionUpdateResultTag::MISSING_INSTALL_INFO), "MISSING_INSTALL_INFO" }, + { static_cast(ExtensionUpdateResultTag::REPOSITORY_NOT_FOUND), "REPOSITORY_NOT_FOUND" }, + { static_cast(ExtensionUpdateResultTag::REPOSITORY_NOT_TRUSTED), "REPOSITORY_NOT_TRUSTED" }, + { static_cast(ExtensionUpdateResultTag::REPOSITORY_UNREADABLE), "REPOSITORY_UNREADABLE" }, { static_cast(ExtensionUpdateResultTag::REDOWNLOADED), "REDOWNLOADED" }, { static_cast(ExtensionUpdateResultTag::UPDATED), "UPDATED" } }; @@ -2633,12 +2675,12 @@ const StringUtil::EnumStringLiteral *GetExtensionUpdateResultTagValues() { template<> const char* EnumUtil::ToChars(ExtensionUpdateResultTag value) { - return StringUtil::EnumToString(GetExtensionUpdateResultTagValues(), 8, "ExtensionUpdateResultTag", static_cast(value)); + return StringUtil::EnumToString(GetExtensionUpdateResultTagValues(), 11, "ExtensionUpdateResultTag", static_cast(value)); } template<> ExtensionUpdateResultTag EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetExtensionUpdateResultTagValues(), 8, "ExtensionUpdateResultTag", value)); + return static_cast(StringUtil::StringToEnum(GetExtensionUpdateResultTagValues(), 11, "ExtensionUpdateResultTag", value)); } const StringUtil::EnumStringLiteral *GetExternalFileCacheRequestSizingValues() { @@ -3048,6 +3090,24 @@ GateStatus EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetGateStatusValues(), 2, "GateStatus", value)); } +const StringUtil::EnumStringLiteral *GetGeometryModelValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(GeometryModel::PLANAR), "PLANAR" }, + { static_cast(GeometryModel::GEODETIC), "GEODETIC" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(GeometryModel value) { + return StringUtil::EnumToString(GetGeometryModelValues(), 2, "GeometryModel", static_cast(value)); +} + +template<> +GeometryModel EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetGeometryModelValues(), 2, "GeometryModel", value)); +} + const StringUtil::EnumStringLiteral *GetGeometryStorageTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(GeometryStorageType::SPATIAL), "SPATIAL" }, @@ -3527,6 +3587,24 @@ JoinRefType EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetJoinRefTypeValues(), 7, "JoinRefType", value)); } +const StringUtil::EnumStringLiteral *GetJoinSimplificationPhaseValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(JoinSimplificationPhase::BEFORE_FILTER_PUSHDOWN), "BEFORE_FILTER_PUSHDOWN" }, + { static_cast(JoinSimplificationPhase::AFTER_FILTER_PUSHDOWN), "AFTER_FILTER_PUSHDOWN" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(JoinSimplificationPhase value) { + return StringUtil::EnumToString(GetJoinSimplificationPhaseValues(), 2, "JoinSimplificationPhase", static_cast(value)); +} + +template<> +JoinSimplificationPhase EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetJoinSimplificationPhaseValues(), 2, "JoinSimplificationPhase", value)); +} + const StringUtil::EnumStringLiteral *GetJoinTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(JoinType::INVALID), "INVALID" }, @@ -4009,6 +4087,7 @@ const StringUtil::EnumStringLiteral *GetLogicalTypeIdValues() { { static_cast(LogicalTypeId::VALIDITY), "VALIDITY" }, { static_cast(LogicalTypeId::UUID), "UUID" }, { static_cast(LogicalTypeId::GEOMETRY), "GEOMETRY" }, + { static_cast(LogicalTypeId::GEOGRAPHY), "GEOGRAPHY" }, { static_cast(LogicalTypeId::STRUCT), "STRUCT" }, { static_cast(LogicalTypeId::LIST), "LIST" }, { static_cast(LogicalTypeId::MAP), "MAP" }, @@ -4026,12 +4105,12 @@ const StringUtil::EnumStringLiteral *GetLogicalTypeIdValues() { template<> const char* EnumUtil::ToChars(LogicalTypeId value) { - return StringUtil::EnumToString(GetLogicalTypeIdValues(), 54, "LogicalTypeId", static_cast(value)); + return StringUtil::EnumToString(GetLogicalTypeIdValues(), 55, "LogicalTypeId", static_cast(value)); } template<> LogicalTypeId EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetLogicalTypeIdValues(), 54, "LogicalTypeId", value)); + return static_cast(StringUtil::StringToEnum(GetLogicalTypeIdValues(), 55, "LogicalTypeId", value)); } const StringUtil::EnumStringLiteral *GetLogicalTypeInfoTypeValues() { @@ -4690,19 +4769,25 @@ const StringUtil::EnumStringLiteral *GetOptimizerTypeValues() { { static_cast(OptimizerType::WINDOW_JOIN_PUSHDOWN), "WINDOW_JOIN_PUSHDOWN" }, { static_cast(OptimizerType::SELF_JOIN_AGGREGATE), "SELF_JOIN_AGGREGATE" }, { static_cast(OptimizerType::SCALAR_AGGREGATE_MERGE), "SCALAR_AGGREGATE_MERGE" }, - { static_cast(OptimizerType::DUPLICATE_ELIMINATED_DOMAIN), "DUPLICATE_ELIMINATED_DOMAIN" } + { static_cast(OptimizerType::DUPLICATE_ELIMINATED_DOMAIN), "DUPLICATE_ELIMINATED_DOMAIN" }, + { static_cast(OptimizerType::REDUNDANT_DISTINCT), "REDUNDANT_DISTINCT" }, + { static_cast(OptimizerType::CASE_TO_FILTER_AGGREGATE), "CASE_TO_FILTER_AGGREGATE" }, + { static_cast(OptimizerType::WINDOW_FUSION), "WINDOW_FUSION" }, + { static_cast(OptimizerType::SET_OPERATION_AGGREGATE), "SET_OPERATION_AGGREGATE" }, + { static_cast(OptimizerType::JOIN_TO_SEMI_JOIN), "JOIN_TO_SEMI_JOIN" }, + { static_cast(OptimizerType::MARK_JOIN_SIMPLIFIER), "MARK_JOIN_SIMPLIFIER" } }; return values; } template<> const char* EnumUtil::ToChars(OptimizerType value) { - return StringUtil::EnumToString(GetOptimizerTypeValues(), 53, "OptimizerType", static_cast(value)); + return StringUtil::EnumToString(GetOptimizerTypeValues(), 59, "OptimizerType", static_cast(value)); } template<> OptimizerType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetOptimizerTypeValues(), 53, "OptimizerType", value)); + return static_cast(StringUtil::StringToEnum(GetOptimizerTypeValues(), 59, "OptimizerType", value)); } const StringUtil::EnumStringLiteral *GetOrderByColumnTypeValues() { @@ -5242,6 +5327,25 @@ PipelineBroadcastExchangeScanMode EnumUtil::FromString(StringUtil::StringToEnum(GetPipelineBroadcastExchangeScanModeValues(), 2, "PipelineBroadcastExchangeScanMode", value)); } +const StringUtil::EnumStringLiteral *GetPipelineExecutionOrderValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(PipelineExecutionOrder::PARTITIONED), "PARTITIONED" }, + { static_cast(PipelineExecutionOrder::ORDERED), "ORDERED" }, + { static_cast(PipelineExecutionOrder::UNORDERED), "UNORDERED" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(PipelineExecutionOrder value) { + return StringUtil::EnumToString(GetPipelineExecutionOrderValues(), 3, "PipelineExecutionOrder", static_cast(value)); +} + +template<> +PipelineExecutionOrder EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetPipelineExecutionOrderValues(), 3, "PipelineExecutionOrder", value)); +} + const StringUtil::EnumStringLiteral *GetPipelineInputModeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(PipelineInputMode::SCHEDULED_SOURCE), "SCHEDULED_SOURCE" }, @@ -5753,51 +5857,6 @@ RegexMatchOperatorSemantics EnumUtil::FromString(co return static_cast(StringUtil::StringToEnum(GetRegexMatchOperatorSemanticsValues(), 2, "RegexMatchOperatorSemantics", value)); } -const StringUtil::EnumStringLiteral *GetRelationTypeValues() { - static constexpr StringUtil::EnumStringLiteral values[] { - { static_cast(RelationType::INVALID_RELATION), "INVALID_RELATION" }, - { static_cast(RelationType::TABLE_RELATION), "TABLE_RELATION" }, - { static_cast(RelationType::PROJECTION_RELATION), "PROJECTION_RELATION" }, - { static_cast(RelationType::FILTER_RELATION), "FILTER_RELATION" }, - { static_cast(RelationType::EXPLAIN_RELATION), "EXPLAIN_RELATION" }, - { static_cast(RelationType::CROSS_PRODUCT_RELATION), "CROSS_PRODUCT_RELATION" }, - { static_cast(RelationType::JOIN_RELATION), "JOIN_RELATION" }, - { static_cast(RelationType::AGGREGATE_RELATION), "AGGREGATE_RELATION" }, - { static_cast(RelationType::SET_OPERATION_RELATION), "SET_OPERATION_RELATION" }, - { static_cast(RelationType::DISTINCT_RELATION), "DISTINCT_RELATION" }, - { static_cast(RelationType::LIMIT_RELATION), "LIMIT_RELATION" }, - { static_cast(RelationType::ORDER_RELATION), "ORDER_RELATION" }, - { static_cast(RelationType::CREATE_VIEW_RELATION), "CREATE_VIEW_RELATION" }, - { static_cast(RelationType::CREATE_TABLE_RELATION), "CREATE_TABLE_RELATION" }, - { static_cast(RelationType::INSERT_RELATION), "INSERT_RELATION" }, - { static_cast(RelationType::VALUE_LIST_RELATION), "VALUE_LIST_RELATION" }, - { static_cast(RelationType::MATERIALIZED_RELATION), "MATERIALIZED_RELATION" }, - { static_cast(RelationType::DELETE_RELATION), "DELETE_RELATION" }, - { static_cast(RelationType::UPDATE_RELATION), "UPDATE_RELATION" }, - { static_cast(RelationType::WRITE_CSV_RELATION), "WRITE_CSV_RELATION" }, - { static_cast(RelationType::WRITE_PARQUET_RELATION), "WRITE_PARQUET_RELATION" }, - { static_cast(RelationType::READ_CSV_RELATION), "READ_CSV_RELATION" }, - { static_cast(RelationType::SUBQUERY_RELATION), "SUBQUERY_RELATION" }, - { static_cast(RelationType::TABLE_FUNCTION_RELATION), "TABLE_FUNCTION_RELATION" }, - { static_cast(RelationType::VIEW_RELATION), "VIEW_RELATION" }, - { static_cast(RelationType::QUERY_RELATION), "QUERY_RELATION" }, - { static_cast(RelationType::DELIM_JOIN_RELATION), "DELIM_JOIN_RELATION" }, - { static_cast(RelationType::DELIM_GET_RELATION), "DELIM_GET_RELATION" }, - { static_cast(RelationType::EXTENSION_RELATION), "EXTENSION_RELATION" } - }; - return values; -} - -template<> -const char* EnumUtil::ToChars(RelationType value) { - return StringUtil::EnumToString(GetRelationTypeValues(), 29, "RelationType", static_cast(value)); -} - -template<> -RelationType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetRelationTypeValues(), 29, "RelationType", value)); -} - const StringUtil::EnumStringLiteral *GetRemoteCapabilityValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(RemoteCapability::IS_REMOTE), "IS_REMOTE" }, @@ -6047,6 +6106,24 @@ ScanReadAheadAcquire EnumUtil::FromString(const char *valu return static_cast(StringUtil::StringToEnum(GetScanReadAheadAcquireValues(), 3, "ScanReadAheadAcquire", value)); } +const StringUtil::EnumStringLiteral *GetScanReadAheadPolicyValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(ScanReadAheadPolicy::ORDERED), "ORDERED" }, + { static_cast(ScanReadAheadPolicy::AFFINITY), "AFFINITY" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(ScanReadAheadPolicy value) { + return StringUtil::EnumToString(GetScanReadAheadPolicyValues(), 2, "ScanReadAheadPolicy", static_cast(value)); +} + +template<> +ScanReadAheadPolicy EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetScanReadAheadPolicyValues(), 2, "ScanReadAheadPolicy", value)); +} + const StringUtil::EnumStringLiteral *GetScanTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(ScanType::TABLE), "TABLE" }, @@ -6144,19 +6221,20 @@ const StringUtil::EnumStringLiteral *GetSelectivityOptionalFilterTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(SelectivityOptionalFilterType::MIN_MAX), "MIN_MAX" }, { static_cast(SelectivityOptionalFilterType::BF), "BF" }, - { static_cast(SelectivityOptionalFilterType::PRF), "PRF" } + { static_cast(SelectivityOptionalFilterType::PRF), "PRF" }, + { static_cast(SelectivityOptionalFilterType::IN_FILTER), "IN_FILTER" } }; return values; } template<> const char* EnumUtil::ToChars(SelectivityOptionalFilterType value) { - return StringUtil::EnumToString(GetSelectivityOptionalFilterTypeValues(), 3, "SelectivityOptionalFilterType", static_cast(value)); + return StringUtil::EnumToString(GetSelectivityOptionalFilterTypeValues(), 4, "SelectivityOptionalFilterType", static_cast(value)); } template<> SelectivityOptionalFilterType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetSelectivityOptionalFilterTypeValues(), 3, "SelectivityOptionalFilterType", value)); + return static_cast(StringUtil::StringToEnum(GetSelectivityOptionalFilterTypeValues(), 4, "SelectivityOptionalFilterType", value)); } const StringUtil::EnumStringLiteral *GetSequenceInfoValues() { @@ -6512,6 +6590,35 @@ SourceResultType EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetSourceResultTypeValues(), 3, "SourceResultType", value)); } +const StringUtil::EnumStringLiteral *GetStandardByteClassValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(StandardByteClass::STRING_QUOTE), "STRING_QUOTE" }, + { static_cast(StandardByteClass::QUOTED_IDENTIFIER), "QUOTED_IDENTIFIER" }, + { static_cast(StandardByteClass::SEMICOLON), "SEMICOLON" }, + { static_cast(StandardByteClass::DOLLAR), "DOLLAR" }, + { static_cast(StandardByteClass::MINUS), "MINUS" }, + { static_cast(StandardByteClass::SLASH), "SLASH" }, + { static_cast(StandardByteClass::SPACE), "SPACE" }, + { static_cast(StandardByteClass::COLON), "COLON" }, + { static_cast(StandardByteClass::SINGLE_BYTE_OPERATOR), "SINGLE_BYTE_OPERATOR" }, + { static_cast(StandardByteClass::NUMBER), "NUMBER" }, + { static_cast(StandardByteClass::SPECIAL_STRING_PREFIX), "SPECIAL_STRING_PREFIX" }, + { static_cast(StandardByteClass::OPERATOR), "OPERATOR" }, + { static_cast(StandardByteClass::WORD), "WORD" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(StandardByteClass value) { + return StringUtil::EnumToString(GetStandardByteClassValues(), 13, "StandardByteClass", static_cast(value)); +} + +template<> +StandardByteClass EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetStandardByteClassValues(), 13, "StandardByteClass", value)); +} + const StringUtil::EnumStringLiteral *GetStarExpressionTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(StarExpressionType::STAR), "STAR" }, @@ -7487,6 +7594,7 @@ const StringUtil::EnumStringLiteral *GetVariantComparisonTypeValues() { { static_cast(VariantComparisonType::TIME_TZ), "TIME_TZ" }, { static_cast(VariantComparisonType::INTERVAL), "INTERVAL" }, { static_cast(VariantComparisonType::GEOMETRY), "GEOMETRY" }, + { static_cast(VariantComparisonType::GEOGRAPHY), "GEOGRAPHY" }, { static_cast(VariantComparisonType::BITSTRING), "BITSTRING" }, { static_cast(VariantComparisonType::ARRAY), "ARRAY" }, { static_cast(VariantComparisonType::OBJECT), "OBJECT" }, @@ -7497,12 +7605,12 @@ const StringUtil::EnumStringLiteral *GetVariantComparisonTypeValues() { template<> const char* EnumUtil::ToChars(VariantComparisonType value) { - return StringUtil::EnumToString(GetVariantComparisonTypeValues(), 16, "VariantComparisonType", static_cast(value)); + return StringUtil::EnumToString(GetVariantComparisonTypeValues(), 17, "VariantComparisonType", static_cast(value)); } template<> VariantComparisonType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetVariantComparisonTypeValues(), 16, "VariantComparisonType", value)); + return static_cast(StringUtil::StringToEnum(GetVariantComparisonTypeValues(), 17, "VariantComparisonType", value)); } const StringUtil::EnumStringLiteral *GetVariantLogicalTypeValues() { @@ -7542,6 +7650,7 @@ const StringUtil::EnumStringLiteral *GetVariantLogicalTypeValues() { { static_cast(VariantLogicalType::BITSTRING), "BITSTRING" }, { static_cast(VariantLogicalType::GEOMETRY), "GEOMETRY" }, { static_cast(VariantLogicalType::TIMESTAMP_NANOS_TZ), "TIMESTAMP_NANOS_TZ" }, + { static_cast(VariantLogicalType::GEOGRAPHY), "GEOGRAPHY" }, { static_cast(VariantLogicalType::ENUM_SIZE), "ENUM_SIZE" } }; return values; diff --git a/src/duckdb/src/common/enums/optimizer_type.cpp b/src/duckdb/src/common/enums/optimizer_type.cpp index ab72cddb4..ca79ea23f 100644 --- a/src/duckdb/src/common/enums/optimizer_type.cpp +++ b/src/duckdb/src/common/enums/optimizer_type.cpp @@ -32,6 +32,7 @@ static const DefaultOptimizerType internal_optimizer_types[] = { {"row_group_pruner", OptimizerType::ROW_GROUP_PRUNER}, {"top_n", OptimizerType::TOP_N}, {"top_n_window_elimination", OptimizerType::TOP_N_WINDOW_ELIMINATION}, + {"window_fusion", OptimizerType::WINDOW_FUSION}, {"build_side_probe_side", OptimizerType::BUILD_SIDE_PROBE_SIDE}, {"compressed_materialization", OptimizerType::COMPRESSED_MATERIALIZATION}, {"duplicate_groups", OptimizerType::DUPLICATE_GROUPS}, @@ -59,12 +60,17 @@ static const DefaultOptimizerType internal_optimizer_types[] = { {"distinct_aggregate_rewrite", OptimizerType::DISTINCT_AGGREGATE_REWRITE}, {"aggregate_reuse", OptimizerType::AGGREGATE_REUSE}, {"duplicate_eliminated_domain", OptimizerType::DUPLICATE_ELIMINATED_DOMAIN}, + {"case_to_filter_aggregate", OptimizerType::CASE_TO_FILTER_AGGREGATE}, {"projection_placement", OptimizerType::PROJECTION_PLACEMENT}, {"redundant_order_keys", OptimizerType::REDUNDANT_ORDER_KEYS}, {"disjunctive_join_rewriter", OptimizerType::DISJUNCTIVE_JOIN_REWRITER}, {"redundant_order", OptimizerType::REDUNDANT_ORDER}, + {"mark_join_simplifier", OptimizerType::MARK_JOIN_SIMPLIFIER}, {"self_join_aggregate", OptimizerType::SELF_JOIN_AGGREGATE}, {"scalar_aggregate_merge", OptimizerType::SCALAR_AGGREGATE_MERGE}, + {"redundant_distinct", OptimizerType::REDUNDANT_DISTINCT}, + {"set_operation_aggregate", OptimizerType::SET_OPERATION_AGGREGATE}, + {"join_to_semi_join", OptimizerType::JOIN_TO_SEMI_JOIN}, {nullptr, OptimizerType::INVALID}}; string OptimizerTypeToString(OptimizerType type) { diff --git a/src/duckdb/src/common/enums/relation_type.cpp b/src/duckdb/src/common/enums/relation_type.cpp deleted file mode 100644 index dc02b8970..000000000 --- a/src/duckdb/src/common/enums/relation_type.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include "duckdb/common/enums/relation_type.hpp" - -#include "duckdb/common/exception.hpp" - -namespace duckdb { - -// LCOV_EXCL_START -string RelationTypeToString(RelationType type) { - switch (type) { - case RelationType::TABLE_RELATION: - return "TABLE_RELATION"; - case RelationType::DELIM_GET_RELATION: - return "DELIM_GET_RELATION"; - case RelationType::DELIM_JOIN_RELATION: - return "DELIM_JOIN_RELATION"; - case RelationType::PROJECTION_RELATION: - return "PROJECTION_RELATION"; - case RelationType::FILTER_RELATION: - return "FILTER_RELATION"; - case RelationType::EXPLAIN_RELATION: - return "EXPLAIN_RELATION"; - case RelationType::CROSS_PRODUCT_RELATION: - return "CROSS_PRODUCT_RELATION"; - case RelationType::JOIN_RELATION: - return "JOIN_RELATION"; - case RelationType::AGGREGATE_RELATION: - return "AGGREGATE_RELATION"; - case RelationType::SET_OPERATION_RELATION: - return "SET_OPERATION_RELATION"; - case RelationType::DISTINCT_RELATION: - return "DISTINCT_RELATION"; - case RelationType::LIMIT_RELATION: - return "LIMIT_RELATION"; - case RelationType::ORDER_RELATION: - return "ORDER_RELATION"; - case RelationType::CREATE_VIEW_RELATION: - return "CREATE_VIEW_RELATION"; - case RelationType::CREATE_TABLE_RELATION: - return "CREATE_TABLE_RELATION"; - case RelationType::INSERT_RELATION: - return "INSERT_RELATION"; - case RelationType::VALUE_LIST_RELATION: - return "VALUE_LIST_RELATION"; - case RelationType::MATERIALIZED_RELATION: - return "MATERIALIZED_RELATION"; - case RelationType::DELETE_RELATION: - return "DELETE_RELATION"; - case RelationType::UPDATE_RELATION: - return "UPDATE_RELATION"; - case RelationType::WRITE_CSV_RELATION: - return "WRITE_CSV_RELATION"; - case RelationType::WRITE_PARQUET_RELATION: - return "WRITE_PARQUET_RELATION"; - case RelationType::READ_CSV_RELATION: - return "READ_CSV_RELATION"; - case RelationType::SUBQUERY_RELATION: - return "SUBQUERY_RELATION"; - case RelationType::TABLE_FUNCTION_RELATION: - return "TABLE_FUNCTION_RELATION"; - case RelationType::VIEW_RELATION: - return "VIEW_RELATION"; - case RelationType::QUERY_RELATION: - return "QUERY_RELATION"; - case RelationType::EXTENSION_RELATION: - return "EXTENSION_RELATION"; - case RelationType::INVALID_RELATION: - break; - } - return "INVALID_RELATION"; -} -// LCOV_EXCL_STOP - -} // namespace duckdb diff --git a/src/duckdb/src/common/hive_partitioning.cpp b/src/duckdb/src/common/hive_partitioning.cpp index 8c35102c5..8efac22e1 100644 --- a/src/duckdb/src/common/hive_partitioning.cpp +++ b/src/duckdb/src/common/hive_partitioning.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/uhugeint.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/function/table_function.hpp" +#include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" @@ -10,6 +11,9 @@ #include "duckdb/planner/table_filter.hpp" #include "duckdb/common/multi_file/multi_file_list.hpp" #include "duckdb/common/vector/flat_vector.hpp" +#include "duckdb/common/vector/vector_writer.hpp" +#include "duckdb/main/error_manager.hpp" +#include "utf8proc_wrapper.hpp" namespace duckdb { @@ -49,38 +53,180 @@ GetKnownColumnValues(const string &filename, const HivePartitioningFilterInfo &f return result; } -// Takes an expression and converts a list of known column_refs to constants -static void -ConvertKnownColRefToConstants(ClientContext &context, unique_ptr &expr, - const unordered_map &known_column_values, - TableIndex table_index) { +//! Unescapes a partition value as a string of the given type - returns false if the value is NULL +static bool TryGetPartitionString(const string &str_val, const LogicalType &type, string &result) { + // On SQLNULL, DuckDB writes "__HIVE_DEFAULT_PARTITION__", instead of string version "NULL". + if (str_val == HivePartitioning::DEFAULT_PARTITION_NAME) { + return false; + } + // "NULL" and empty strings are NULL for non-string partition types + if (type.id() != LogicalTypeId::VARCHAR && (StringUtil::CIEquals(str_val, "NULL") || str_val.empty())) { + return false; + } + result = HivePartitioning::Unescape(str_val); + return true; +} + +// Replaces references to columns of the given table using the replacement callback (nullptr = keep) +static void ReplaceTableColumns(unique_ptr &expr, TableIndex table_index, + const std::function(BoundColumnRefExpression &)> &replace) { if (expr->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { auto &bound_colref = expr->Cast(); - - // This bound column ref is for another table - if (table_index != bound_colref.Binding().table_index) { + if (bound_colref.Depth() != 0 || bound_colref.Binding().table_index != table_index) { return; } + auto replacement = replace(bound_colref); + if (replacement) { + expr = std::move(replacement); + } + return; + } + ExpressionIterator::EnumerateChildren( + *expr, [&](unique_ptr &child) { ReplaceTableColumns(child, table_index, replace); }); +} + +enum class PartitionFilterResult : uint8_t { NOT_EVALUATED, KEEP_FILE, PRUNE_FILE }; + +//! A filter rewritten to read the partition columns it references from an input chunk +struct PartitionFilter { + unique_ptr expr; + vector columns; + vector types; +}; + +static unique_ptr PreparePartitionFilter(ClientContext &context, const Expression &filter, + const HivePartitioningFilterInfo &filter_info, + TableIndex table_index) { + unordered_set partition_columns; + for (auto &entry : filter_info.column_map) { + if (filter_info.hive_enabled || (filter_info.filename_enabled && entry.first == filter_info.filename_column)) { + partition_columns.insert(ProjectionIndex(entry.second)); + } + } + + // the filter can only be evaluated if it becomes foldable once the partition columns are known + auto check = filter.Copy(); + ReplaceTableColumns(check, table_index, [&](BoundColumnRefExpression &colref) -> unique_ptr { + if (partition_columns.find(colref.Binding().column_index) == partition_columns.end()) { + return nullptr; + } + return make_uniq(Value(colref.GetReturnType())); + }); + if (!check->IsScalar() || !check->IsFoldable()) { + return nullptr; + } + + auto result = make_uniq(); + result->expr = filter.Copy(); + ReplaceTableColumns(result->expr, table_index, [&](BoundColumnRefExpression &colref) { + auto column_index = colref.Binding().column_index; + idx_t slot; + for (slot = 0; slot < result->columns.size(); slot++) { + if (result->columns[slot] == column_index) { + break; + } + } + if (slot == result->columns.size()) { + result->columns.push_back(column_index); + result->types.push_back(colref.GetReturnType()); + } + // the partition values are loaded as strings and cast as part of the filter + auto reference = make_uniq(LogicalType::VARCHAR, slot); + return BoundCastExpression::AddCastToType(context, std::move(reference), colref.GetReturnType()); + }); + return result; +} + +//! Evaluates the filter over a chunk of files - returns false (leaving the files unevaluated) if the filter throws +static bool EvaluatePartitionFilterChunk(ExpressionExecutor &executor, DataChunk &chunk, + array_ptr file_indexes, + vector &file_results) { + SelectionVector true_sel(chunk.size()); + idx_t true_count; + try { + true_count = executor.SelectExpression(chunk, true_sel); + } catch (InternalException &) { + throw; + } catch (...) { + return false; + } + for (auto &file_idx : file_indexes) { + file_results[file_idx] = PartitionFilterResult::PRUNE_FILE; + } + for (idx_t i = 0; i < true_count; i++) { + file_results[file_indexes[true_sel.get_index(i)]] = PartitionFilterResult::KEEP_FILE; + } + return true; +} - auto lookup = known_column_values.find(bound_colref.Binding().column_index); - if (lookup != known_column_values.end()) { - auto &partition_val = lookup->second; - Value result_val; +//! Loads the (unescaped) string values of a partition column for the given files into the result vector +static void LoadPartitionColumn(ProjectionIndex column, const LogicalType &type, + const vector> &known_values, + array_ptr file_indexes, Vector &result) { + auto count = file_indexes.size(); + Vector strings(LogicalType::VARCHAR, count); + { + auto writer = FlatVector::Writer(strings, count); + string unescaped; + for (auto &file_idx : file_indexes) { + auto &partition_val = known_values[file_idx].find(column)->second; if (partition_val.key.empty()) { // filename column - use directly - result_val = Value(partition_val.value); - } else { - // hive partitioning column - cast the value to the target type - result_val = HivePartitioning::GetValue(context, partition_val.key, partition_val.value, - bound_colref.GetReturnType()); + unescaped = partition_val.value; + } else if (!TryGetPartitionString(partition_val.value, type, unescaped)) { + writer.WriteNull(); + continue; } - expr = make_uniq(std::move(result_val)); + if (!Utf8Proc::IsValid(unescaped.c_str(), unescaped.size())) { + throw ErrorManager::InvalidUnicodeError(unescaped, "value construction"); + } + writer.WriteValue(string_t(unescaped)); } - } else { - ExpressionIterator::EnumerateChildren(*expr, [&](unique_ptr &child) { - ConvertKnownColRefToConstants(context, child, known_column_values, table_index); - }); } + result.Reference(strings); +} + +static vector +EvaluatePartitionFilter(ClientContext &context, const PartitionFilter &filter, + const vector> &known_values) { + vector file_results(known_values.size(), PartitionFilterResult::NOT_EVALUATED); + // files that have values for all partition columns referenced by the filter + vector file_indexes; + for (idx_t file_idx = 0; file_idx < known_values.size(); file_idx++) { + auto &file_values = known_values[file_idx]; + bool has_all_columns = true; + for (auto &column : filter.columns) { + if (file_values.find(column) == file_values.end()) { + has_all_columns = false; + break; + } + } + if (has_all_columns) { + file_indexes.push_back(file_idx); + } + } + + ExpressionExecutor executor(context, *filter.expr); + DataChunk chunk; + chunk.InitializeEmpty(vector(filter.columns.size(), LogicalType::VARCHAR)); + // if the filter throws for some files, the batch is split in halves so the remaining files can still be pruned + std::function)> evaluate_files = [&](array_ptr batch) { + for (idx_t col = 0; col < filter.columns.size(); col++) { + LoadPartitionColumn(filter.columns[col], filter.types[col], known_values, batch, chunk.data[col]); + } + chunk.SetChildCardinality(batch.size()); + if (EvaluatePartitionFilterChunk(executor, chunk, batch, file_results) || batch.size() == 1) { + return; + } + auto half = batch.size() / 2; + evaluate_files(array_ptr(batch.data(), half)); + evaluate_files(array_ptr(batch.data() + half, batch.size() - half)); + }; + for (idx_t offset = 0; offset < file_indexes.size(); offset += STANDARD_VECTOR_SIZE) { + auto count = MinValue(STANDARD_VECTOR_SIZE, file_indexes.size() - offset); + evaluate_files(array_ptr(file_indexes.data() + offset, count)); + } + return file_results; } string HivePartitioning::Escape(const string &input) { @@ -150,25 +296,14 @@ std::map HivePartitioning::Parse(const string &filename) { Value HivePartitioning::GetValue(ClientContext &context, const string &key, const string &str_val, const LogicalType &type) { - // On SQLNULL, DuckDB writes "__HIVE_DEFAULT_PARTITION__", instead of string version "NULL". - if (str_val == DEFAULT_PARTITION_NAME) { + string unescaped; + if (!TryGetPartitionString(str_val, type, unescaped)) { return Value(type); } + Value value(std::move(unescaped)); if (type.id() == LogicalTypeId::VARCHAR) { - // for string values we can directly return the type - return Value(Unescape(str_val)); - } - // Handle Hive NULL markers for non-string partition types - if (StringUtil::CIEquals(str_val, "NULL")) { - return Value(type); + return value; } - if (str_val.empty()) { - // empty strings are NULL for non-string types - return Value(type); - } - - // cast to the target type - Value value(Unescape(str_val)); auto cast = value.TryCastAs(context, type); if (!cast) { throw InvalidInputException("Unable to cast '%s' (from hive partition column '%s') to: '%s'", value.ToString(), @@ -197,38 +332,47 @@ void HivePartitioning::ApplyFiltersToFileList(ClientContext &context, vector>(); } + vector> known_values; + known_values.reserve(files.size()); + for (auto &file : files) { + known_values.push_back(GetKnownColumnValues(file.path, filter_info)); + } + vector> filter_results; + for (auto &filter : filters) { + auto partition_filter = PreparePartitionFilter(context, *filter, filter_info, table_index); + if (!partition_filter) { + filter_results.emplace_back(files.size(), PartitionFilterResult::NOT_EVALUATED); + continue; + } + filter_results.push_back(EvaluatePartitionFilter(context, *partition_filter, known_values)); + } + for (idx_t i = 0; i < files.size(); i++) { - auto &file = files[i]; bool should_prune_file = false; - auto known_values = GetKnownColumnValues(file.path, filter_info); - for (idx_t j = 0; j < filters.size(); j++) { auto &filter = filters[j]; - unique_ptr filter_copy = filter->Copy(); - ConvertKnownColRefToConstants(context, filter_copy, known_values, table_index); - // Evaluate the filter, if it can be evaluated here, we can not prune this filter - Value result_value; - - if (!filter_copy->IsScalar() || !filter_copy->IsFoldable() || - !ExpressionExecutor::TryEvaluateScalar(context, *filter_copy, result_value)) { + switch (filter_results[j][i]) { + case PartitionFilterResult::NOT_EVALUATED: // can not be evaluated only with the filename/hive columns added, we can not prune this filter if (!have_preserved_filter[j]) { pruned_filters.emplace_back(filter->Copy()); have_preserved_filter[j] = true; } - } else if (result_value.IsNull() || !result_value.GetValue()) { - // filter evaluates to false + break; + case PartitionFilterResult::PRUNE_FILE: should_prune_file = true; - // convert the filter to a table filter. if (filters_applied_to_files.find(j) == filters_applied_to_files.end()) { info.extra_info.file_filters += filter->ToString(); filters_applied_to_files.insert(j); } + break; + case PartitionFilterResult::KEEP_FILE: + break; } } if (!should_prune_file) { - pruned_files.push_back(file); + pruned_files.push_back(files[i]); } } diff --git a/src/duckdb/src/common/local_file_system.cpp b/src/duckdb/src/common/local_file_system.cpp index 3113c2484..e4ba75798 100644 --- a/src/duckdb/src/common/local_file_system.cpp +++ b/src/duckdb/src/common/local_file_system.cpp @@ -2441,8 +2441,4 @@ unique_ptr LocalFileSystem::GlobFilesExtended(const string &path, return make_uniq(*this, path, FileGlobOptions::ALLOW_EMPTY, opener); } -unique_ptr FileSystem::CreateLocal() { - return make_uniq(); -} - } // namespace duckdb diff --git a/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp b/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp index d3d03b8e6..1e0f6abf1 100644 --- a/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp +++ b/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp @@ -17,6 +17,7 @@ #include "duckdb/planner/filter/list.hpp" #include "duckdb/function/scalar/struct_functions.hpp" #include "duckdb/function/scalar/struct_utils.hpp" +#include "duckdb/function/scalar/variant_functions.hpp" #include "duckdb/function/scalar/nested_functions.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/filter/table_filter_functions.hpp" @@ -554,8 +555,8 @@ static ColumnMapResult MapColumnStruct(ClientContext &context, const MultiFileCo ColumnMapResult result; result.local_column = local_column; - if (!column_mapping.empty()) { - // we have column mappings at this level - construct the struct + if (!column_mapping.empty() || !is_root) { + // A nested source still supplies validity when every selected child comes from a default. result.column_map = Value::STRUCT(std::move(column_mapping)); if (!is_root) { // if this is nested we need to refer to the current column at this level @@ -674,6 +675,150 @@ static unique_ptr ConstructMapExpression(ClientContext &context, Mul return BindBuiltinScalarFunction(context, RemapStructFun::Name, std::move(children)); } +//! How a file maps onto a pushed-down extract +enum class PushdownExtractMapping { + //! the file has every field on the extract path + PUSHDOWN, + //! the file lacks a field on the path whose default is NULL, so the extracted field is NULL in every row + NULL_VALUE, + //! the whole column must be mapped before the field can be extracted + WHOLE_COLUMN +}; + +//! Map a pushed-down extract of a struct whose fields are not defined by the global schema, matching the fields by +//! name, as a cast of the whole column does +static PushdownExtractMapping GetPushdownExtractMappingByName(const LogicalType &global_type, + const LogicalType &local_type, + const ColumnIndex &global_index) { + if (local_type.id() == LogicalTypeId::SQLNULL) { + return PushdownExtractMapping::NULL_VALUE; + } + if (!global_index.IsPushdownExtract()) { + // preserve the schema conversion before a pushed cast + if (global_type != local_type && global_type != global_index.GetScanType()) { + return PushdownExtractMapping::WHOLE_COLUMN; + } + return PushdownExtractMapping::PUSHDOWN; + } + if (global_type.id() != local_type.id()) { + return PushdownExtractMapping::WHOLE_COLUMN; + } + if (global_type.id() != LogicalTypeId::STRUCT) { + return PushdownExtractMapping::PUSHDOWN; + } + auto &child_index = global_index.GetChildIndex(0); + auto &global_children = StructType::GetChildTypes(global_type); + if (child_index.GetPrimaryIndex() >= global_children.size()) { + return PushdownExtractMapping::PUSHDOWN; + } + auto &field = global_children[child_index.GetPrimaryIndex()]; + auto &local_children = StructType::GetChildTypes(local_type); + for (idx_t local_idx = 0; local_idx < local_children.size(); local_idx++) { + if (!(local_children[local_idx].first == field.first)) { + continue; + } + if (local_idx != child_index.GetPrimaryIndex()) { + // the field is at another position in this file + return PushdownExtractMapping::WHOLE_COLUMN; + } + return GetPushdownExtractMappingByName(field.second, local_children[local_idx].second, child_index); + } + // the file lacks the field, which a cast of the whole column fills with NULL + return PushdownExtractMapping::NULL_VALUE; +} + +static PushdownExtractMapping GetPushdownExtractMapping(ClientContext &context, + const MultiFileColumnDefinition &global_column, + const ColumnIndex &global_index, + const vector &local_columns, + const ColumnMapper &mapper, bool is_root) { + auto local_idx = mapper.Find(global_column); + if (!local_idx.IsValid()) { + if (is_root) { + return PushdownExtractMapping::WHOLE_COLUMN; + } + auto default_expr = mapper.GetDefaultExpression(context, global_column, false); + if (default_expr->GetExpressionType() == ExpressionType::VALUE_CONSTANT && + default_expr->Cast().GetValue().IsNull()) { + return PushdownExtractMapping::NULL_VALUE; + } + return PushdownExtractMapping::WHOLE_COLUMN; + } + auto &local_column = local_columns[local_idx]; + if (local_column.type.id() == LogicalTypeId::SQLNULL) { + // an explicitly NULL field is NULL whatever is extracted from it + return PushdownExtractMapping::NULL_VALUE; + } + if (!global_index.IsPushdownExtract()) { + if (global_column.children.empty() && global_column.type != local_column.type && + global_column.type != global_index.GetScanType()) { + return PushdownExtractMapping::WHOLE_COLUMN; + } + return PushdownExtractMapping::PUSHDOWN; + } + if (global_column.type.id() != local_column.type.id()) { + return PushdownExtractMapping::WHOLE_COLUMN; + } + if (global_column.type.id() != LogicalTypeId::STRUCT) { + return PushdownExtractMapping::PUSHDOWN; + } + if (global_column.children.empty()) { + return GetPushdownExtractMappingByName(global_column.type, local_column.type, global_index); + } + auto &child_index = global_index.GetChildIndex(0); + if (child_index.GetPrimaryIndex() >= global_column.children.size()) { + return PushdownExtractMapping::PUSHDOWN; + } + auto &child_column = global_column.children[child_index.GetPrimaryIndex()]; + auto nested_mapper = mapper.Create(local_column.children); + return GetPushdownExtractMapping(context, child_column, child_index, local_column.children, *nested_mapper, false); +} + +//! The type that the field a pushed-down extract selects has in the global schema, before any cast pushed into it +static LogicalType GetExtractedFieldType(const LogicalType &type, const ColumnIndex &global_index) { + reference field_type(type); + reference current(global_index); + while (current.get().IsPushdownExtract()) { + auto &child = current.get().GetChildIndex(0); + if (!child.HasPrimaryIndex()) { + // a field of a VARIANT is a VARIANT + return field_type.get(); + } + field_type = StructType::GetChildType(field_type.get(), child.GetPrimaryIndex()); + current = child; + } + return field_type.get(); +} + +//! Apply a pushed-down extract to an expression that produces the whole column +static unique_ptr ApplyPushdownExtract(ClientContext &context, unique_ptr expr, + const ColumnIndex &global_index) { + reference current(global_index); + while (current.get().IsPushdownExtract()) { + auto &child = current.get().GetChildIndex(0); + vector> arguments; + arguments.push_back(std::move(expr)); + if (child.HasPrimaryIndex()) { + auto index = Value::BIGINT(NumericCast(child.GetPrimaryIndex() + 1)); + arguments.push_back(make_uniq(std::move(index))); + expr = BindBuiltinScalarExpression(context, StructExtractAtFun::Name, std::move(arguments)); + } else { + arguments.push_back(make_uniq(Value(child.GetFieldName()))); + expr = BindBuiltinScalarExpression(context, VariantExtractFun::Name, std::move(arguments)); + } + current = child; + } + auto &scan_type = global_index.GetScanType(); + if (expr->GetReturnType() != scan_type) { + expr = BoundCastExpression::AddCastToType(context, std::move(expr), scan_type); + } + if (expr->IsFoldable()) { + // keep constants constant so filters on them can be evaluated up front + return make_uniq(ExpressionExecutor::EvaluateScalar(context, *expr, true)); + } + return expr; +} + ResultColumnMapping MultiFileColumnMapper::CreateColumnMappingByMapper(const ColumnMapper &mapper) { auto &reader = *reader_data.reader; auto &local_columns = reader.GetColumns(); @@ -808,6 +953,37 @@ ResultColumnMapping MultiFileColumnMapper::CreateColumnMappingByMapper(const Col continue; } + auto extract_mapping = + global_id.IsPushdownExtract() + ? GetPushdownExtractMapping(context, global_column, global_id, local_columns, mapper, true) + : PushdownExtractMapping::PUSHDOWN; + if (extract_mapping == PushdownExtractMapping::NULL_VALUE) { + reader_data.expressions.push_back(make_uniq(Value(global_id.GetScanType()))); + continue; + } + if (extract_mapping == PushdownExtractMapping::WHOLE_COLUMN) { + // map the whole column and extract from it, so the defaults are the same as when the whole column is read + ColumnIndex root_index(global_column_id); + auto root_map = MapColumn(context, global_column, root_index, local_columns, mapper, local_idx); + if (!root_map.column_index) { + auto default_expr = ApplyPushdownExtract(context, std::move(root_map.default_value), global_id); + reader_data.expressions.push_back(std::move(default_expr)); + continue; + } + auto trivial_map = IsTriviallyMappable(global_column, local_columns, mapper); + auto local_index = std::move(root_map.column_index); + auto local_id = local_index->GetPrimaryIndex(); + auto &local_type = local_columns[local_id].type; + auto expr = + ConstructMapExpression(context, local_idx, root_map, global_column.type, local_type, trivial_map); + reader_data.expressions.push_back(ApplyPushdownExtract(context, std::move(expr), global_id)); + MultiFileColumnMap index_mapping(std::move(*root_map.mapping), local_type, global_id.GetScanType(), + FilterConversionType::CANNOT_CONVERT); + result.global_to_local.insert(make_pair(global_idx, std::move(index_mapping))); + reader.column_ids.emplace_back(local_id); + reader.column_indexes.push_back(std::move(*local_index)); + continue; + } auto column_map = MapColumn(context, global_column, global_id, local_columns, mapper, local_idx); if (!column_map.column_index) { // no columns were emitted @@ -820,10 +996,21 @@ ResultColumnMapping MultiFileColumnMapper::CreateColumnMappingByMapper(const Col auto &local_type = local_columns[local_id].type; auto global_column_type = global_id.HasType() ? global_id.GetScanType() : global_column.type; auto local_column_type = local_index->HasType() ? local_index->GetScanType() : local_type; - auto expr = - ConstructMapExpression(context, local_idx, column_map, global_column_type, local_column_type, trivial_map); + auto map_type = global_column_type; + if (global_id.IsPushdownExtract() && local_column_type.IsNested()) { + // a nested field is read with its type in the file, so map it to its global type before a pushed cast + map_type = GetExtractedFieldType(global_column.type, global_id); + } + auto expr = ConstructMapExpression(context, local_idx, column_map, map_type, local_column_type, trivial_map); + if (map_type != global_column_type) { + expr = BoundCastExpression::AddCastToType(context, std::move(expr), global_column_type); + } reader_data.expressions.push_back(std::move(expr)); auto filter_conversion = trivial_map ? FilterConversionType::COPY_DIRECTLY : FilterConversionType::CAST_FILTER; + if (map_type != global_column_type) { + // the filter is on the cast value, so it is evaluated after the mapping and the cast + filter_conversion = FilterConversionType::CANNOT_CONVERT; + } MultiFileColumnMap index_mapping(std::move(*column_map.mapping), local_column_type, global_column_type, filter_conversion); diff --git a/src/duckdb/src/common/multi_file/multi_file_list.cpp b/src/duckdb/src/common/multi_file/multi_file_list.cpp index 2f91401ce..69c23cf8e 100644 --- a/src/duckdb/src/common/multi_file/multi_file_list.cpp +++ b/src/duckdb/src/common/multi_file/multi_file_list.cpp @@ -363,8 +363,9 @@ bool LazyMultiFileList::ExpandNextPathInternal() const { if (all_files_expanded) { return false; } - if (services && services->IsInterrupted()) { - throw InterruptException(); + if (services) { + // each expansion step can be a slow remote listing, so read the clock every time + services->InterruptCheck(); } if (!ExpandNextPath()) { all_files_expanded = true; diff --git a/src/duckdb/src/common/multi_file/multi_file_reader.cpp b/src/duckdb/src/common/multi_file/multi_file_reader.cpp index d452c3db6..155fcf755 100644 --- a/src/duckdb/src/common/multi_file/multi_file_reader.cpp +++ b/src/duckdb/src/common/multi_file/multi_file_reader.cpp @@ -117,14 +117,6 @@ unique_ptr MultiFileReader::CreateDefault(const string &functio return res; } -Value MultiFileReader::CreateValueFromFileList(const vector &file_list) { - vector files; - for (auto &file : file_list) { - files.push_back(file); - } - return Value::LIST(LogicalType::VARCHAR, std::move(files)); -} - void MultiFileReader::AddParameters(TableFunction &table_function, MultiFileParameters which) { auto add_options = [&](TypedKwargs &options) { if (which == MultiFileParameters::ALL) { @@ -1343,7 +1335,8 @@ bool MultiFileOptions::AutoDetectHivePartitioningInternal(MultiFileList &files, return true; } void MultiFileOptions::AutoDetectHiveTypesInternal(MultiFileList &files, ClientContext &context) { - const LogicalType candidates[] = {LogicalType::DATE, LogicalType::TIMESTAMP, LogicalType::BIGINT}; + const LogicalType candidates[] = {LogicalType::DATE, LogicalType::TIMESTAMP, LogicalType::BIGINT, + LogicalType::TIME}; unordered_map detected_types; for (const auto &file : files.Files()) { @@ -1362,7 +1355,7 @@ void MultiFileOptions::AutoDetectHiveTypesInternal(MultiFileList &files, ClientC continue; // don't update detected_types for this partition/file } LogicalType detected_type = LogicalType::VARCHAR; - Value value(part.second); + Value value(HivePartitioning::Unescape(part.second)); for (auto &candidate : candidates) { const bool success = value.TryCastAs(context, candidate, nullptr, true).has_value(); if (success) { diff --git a/src/duckdb/src/common/multi_file/table_function_multi_file.cpp b/src/duckdb/src/common/multi_file/table_function_multi_file.cpp index b405e84b8..7884d177b 100644 --- a/src/duckdb/src/common/multi_file/table_function_multi_file.cpp +++ b/src/duckdb/src/common/multi_file/table_function_multi_file.cpp @@ -19,9 +19,12 @@ namespace duckdb { //===--------------------------------------------------------------------===// class TableFunctionMultiFileGlobalState : public GlobalTableFunctionState { public: - //! The operator the files are scanned for, and how many files that scan reads + explicit TableFunctionMultiFileGlobalState(const MultiFileList &file_list_p) : file_list(file_list_p) { + } + + //! The operator and file list of the scan optional_ptr op; - idx_t file_count = 1; + const MultiFileList &file_list; //! What the wrapped function has reported for the files of this scan - collected whenever a file may have //! counted more, so that a reader can be released without losing what it counted. //! "scanned" is handed over and cleared on every report - the profiler sums what each thread reports, so a @@ -270,7 +273,7 @@ TableFunctionInitInput TableFunctionFileReader::GetInitInput(TableFunctionFileIn file_input.filter_global_indices = filter_global_indices; } file_input.file_index = file_list_idx; - file_input.file_count = scan_file_count; + file_input.file_list = scan_file_list; if (!cast_map.empty()) { file_input.cast_map = cast_map; } @@ -291,7 +294,7 @@ optional_idx TableFunctionFileReader::MaxThreads(ClientContext &context, GlobalT void TableFunctionFileReader::SetScanState(GlobalTableFunctionState &gstate) { auto &scan_state = gstate.Cast(); scan_op = scan_state.op; - scan_file_count = scan_state.file_count; + scan_file_list = scan_state.file_list; } void TableFunctionFileReader::InitializeFunctionState(ClientContext &context) { @@ -674,9 +677,8 @@ void TableFunctionMultiFileWrapper::BindReader(ClientContext &context, vector TableFunctionMultiFileWrapper::InitializeGlobalState(ClientContext &, MultiFileBindData &, MultiFileGlobalState &global_state) { - auto result = make_uniq(); + auto result = make_uniq(global_state.file_list); result->op = global_state.op; - result->file_count = global_state.file_list.GetTotalFileCount(); return std::move(result); } diff --git a/src/duckdb/src/common/operator/cast_operators.cpp b/src/duckdb/src/common/operator/cast_operators.cpp index 44096199d..af8d86d41 100644 --- a/src/duckdb/src/common/operator/cast_operators.cpp +++ b/src/duckdb/src/common/operator/cast_operators.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/operator/cast_operators.hpp" +#include "duckdb/function/cast/wide_decimal_cast.hpp" #include "duckdb/function/cast/default_casts.hpp" #include "duckdb/common/hugeint.hpp" #include "duckdb/common/operator/string_cast.hpp" @@ -1879,6 +1880,22 @@ bool TryCastToGeometry::Operation(string_t input, string_t &result, Vector &resu return false; } +template <> +bool TryCastToGeography::Operation(string_t input, string_t &result, Vector &result_vector, + CastParameters ¶meters) { + // Parse the WKT text into WKB, then validate the canonical GEOGRAPHY coordinate ranges. + if (!TryCastToGeometry::Operation(input, result, result_vector, parameters)) { + return false; + } + if (!Geometry::IsValidGeography(result)) { + HandleCastError::AssignError("Geometry coordinates are outside the canonical GEOGRAPHY ranges " + "(longitude/X must be within [-180, 180], latitude/Y within [-90, 90])", + parameters); + return false; + } + return true; +} + //===--------------------------------------------------------------------===// // Cast To Date //===--------------------------------------------------------------------===// @@ -3437,37 +3454,40 @@ bool TryCastFromDecimal::Operation(hugeint_t input, double &result, CastParamete // Decimal Casts of the bignum_t tier (width > 38), and BIGNUM as a decimal with scale 0 //===--------------------------------------------------------------------===// //! The BIGNUM blob of an integer -static string IntegerToBignumBlob(hugeint_t value) { - return DecimalHelper::FromInteger(value); +static void IntegerToBignumBlob(hugeint_t value, string &result) { + DecimalHelper::FromInteger(value, result); } -static string IntegerToBignumBlob(uhugeint_t value) { - return DecimalHelper::FromInteger(value); +static void IntegerToBignumBlob(uhugeint_t value, string &result) { + DecimalHelper::FromInteger(value, result); } -static string IntegerToBignumBlob(bool value) { - return DecimalHelper::FromInteger(hugeint_t(value ? 1 : 0)); +static void IntegerToBignumBlob(bool value, string &result) { + DecimalHelper::FromInteger(hugeint_t(value ? 1 : 0), result); } template -static string IntegerToBignumBlob(SRC value) { - return DecimalHelper::FromInteger(Hugeint::Convert(value)); +static void IntegerToBignumBlob(SRC value, string &result) { + DecimalHelper::FromInteger(Hugeint::Convert(value), result); } //! Scales an integer to the bignum_t tier, false if it does not fit the width template static bool TryCastIntegerToBignumDecimal(SRC input, bignum_t &result, Vector &result_vector, CastParameters ¶meters, uint32_t width, uint32_t scale) { - auto unscaled = IntegerToBignumBlob(input); - string blob; - if (!DecimalHelper::TryRescale(bignum_t(string_t(unscaled)), 0, width, scale, blob, - DefaultCasts::WideDecimalCastContext(parameters))) { + WideDecimalCastState fallback(DefaultCasts::WideDecimalCastContext(parameters)); + auto &state = parameters.local_state ? parameters.local_state->Cast() : fallback; + IntegerToBignumBlob(input, state.unscaled_blob); + auto &rescale_state = state.GetRescaleState(); + rescale_state.Reset(); + auto rescaled = DecimalHelper::Rescale(rescale_state, bignum_t(string_t(state.unscaled_blob)), 0, scale); + if (!DecimalHelper::FitsWidth(rescaled, width)) { string error = StringUtil::Format("Could not cast value %s to DECIMAL(%d,%d)", ConvertToString::Operation(input), width, scale); HandleCastError::AssignError(error, parameters); return false; } - result = DecimalHelper::Store(result_vector, blob); + result = bignum_t(StringVector::AddStringOrBlob(result_vector, rescaled.data)); return true; } @@ -3541,7 +3561,11 @@ template static bool TryCastBignumDecimalToFloatingPoint(bignum_t input, DST &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { auto context = DefaultCasts::WideDecimalCastContext(parameters); - if (!DecimalHelper::TryToFloating(input, scale, result, context)) { + auto state = parameters.local_state ? ¶meters.local_state->Cast() : nullptr; + const bool success = state ? DecimalHelper::TryToFloating(state->GetFormattingState(), state->formatted, + input, scale, result) + : DecimalHelper::TryToFloating(input, scale, result, context); + if (!success) { string error = StringUtil::Format("Casting value \"%s\" to type %s failed: value is out of range!", DecimalHelper::ToString(input, width, scale, context), GetTypeId()); @@ -3554,7 +3578,8 @@ static bool TryCastBignumDecimalToFloatingPoint(bignum_t input, DST &result, Cas //! A fixed-size decimal rounds to an integer BIGNUM template static bool CastDecimalToBignum(SRC input, bignum_t &result, Vector &result_vector, uint32_t scale) { - auto unscaled = IntegerToBignumBlob(hugeint_t(input)); + string unscaled; + IntegerToBignumBlob(hugeint_t(input), unscaled); result = DecimalHelper::Store(result_vector, RoundBignumDecimal(bignum_t(string_t(unscaled)), scale)); return true; } diff --git a/src/duckdb/src/common/radix_partitioning.cpp b/src/duckdb/src/common/radix_partitioning.cpp index 5005a3647..6dcd52d05 100644 --- a/src/duckdb/src/common/radix_partitioning.cpp +++ b/src/duckdb/src/common/radix_partitioning.cpp @@ -16,7 +16,7 @@ struct RadixPartitioningConstants { }; template -RETURN_TYPE RadixBitsSwitch(const idx_t radix_bits, ARGS &&... args) { +RETURN_TYPE RadixBitsSwitch(const idx_t radix_bits, ARGS &&...args) { D_ASSERT(radix_bits <= RadixPartitioning::MAX_RADIX_BITS); switch (radix_bits) { case 0: diff --git a/src/duckdb/src/common/row_operations/row_aggregate.cpp b/src/duckdb/src/common/row_operations/row_aggregate.cpp index 4a8ffff05..e787fe2b3 100644 --- a/src/duckdb/src/common/row_operations/row_aggregate.cpp +++ b/src/duckdb/src/common/row_operations/row_aggregate.cpp @@ -75,6 +75,11 @@ void RowOperations::UpdateFilteredStates(RowOperationsState &state, AggregateFil if (count == 0) { return; } + if (filter_data.all_selected) { + // every row passes the filter: the payload has not been sliced + UpdateStates(state, aggr, addresses, filter_data.filtered_payload, arg_idx); + return; + } Vector filtered_addresses(addresses, filter_data.true_sel, count); filtered_addresses.Flatten(); diff --git a/src/duckdb/src/common/serializer/async_task_queue.cpp b/src/duckdb/src/common/serializer/async_task_queue.cpp index d6bb56e33..476ca1eed 100644 --- a/src/duckdb/src/common/serializer/async_task_queue.cpp +++ b/src/duckdb/src/common/serializer/async_task_queue.cpp @@ -74,6 +74,10 @@ class AsyncTaskQueueTask : public BaseExecutorTask { queue.DrainRequest(); } + string TaskType() const override { + return "AsyncTaskQueueTask"; + } + private: AsyncTaskQueue &queue; bool started = false; diff --git a/src/duckdb/src/common/serializer/async_write_queue.cpp b/src/duckdb/src/common/serializer/async_write_queue.cpp index 384332c6a..9b1400f3e 100644 --- a/src/duckdb/src/common/serializer/async_write_queue.cpp +++ b/src/duckdb/src/common/serializer/async_write_queue.cpp @@ -81,6 +81,10 @@ class AsyncWriteQueueTask : public BaseExecutorTask { queue.CancelScheduledTask(); } + string TaskType() const override { + return "AsyncWriteQueueTask"; + } + private: AsyncWriteQueue &queue; }; @@ -355,11 +359,16 @@ void AsyncWriteQueue::WriteBuffer(data_ptr_t buffer, idx_t size, idx_t offset) { } try { target.Write(buffer, size, offset); - } catch (const IOException &ex) { - throw IOException("Async write failed for range [offset=%llu, size=%llu]: %s", offset, size, ex.what()); - } catch (const HTTPException &ex) { - throw HTTPException(Exception::ConstructMessage("Async write failed for range [offset=%llu, size=%llu]: %s", - offset, size, ex.what())); + } catch (const std::exception &ex) { + ErrorData error(ex); + if (error.Type() == ExceptionType::IO) { + throw IOException("Async write failed for range [offset=%llu, size=%llu]: %s", offset, size, ex.what()); + } + if (error.Type() == ExceptionType::HTTP) { + throw HTTPException(Exception::ConstructMessage("Async write failed for range [offset=%llu, size=%llu]: %s", + offset, size, ex.what())); + } + throw; } } diff --git a/src/duckdb/src/common/sort/hashed_sort.cpp b/src/duckdb/src/common/sort/hashed_sort.cpp index ae2923c0f..5e4fa5829 100644 --- a/src/duckdb/src/common/sort/hashed_sort.cpp +++ b/src/duckdb/src/common/sort/hashed_sort.cpp @@ -1,4 +1,6 @@ #include "duckdb/common/sorting/hashed_sort.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/common/sorting/partition_key_tracker.hpp" @@ -104,7 +106,8 @@ HashedSortGlobalSinkState::HashedSortGlobalSinkState(ClientContext &client, cons : client(client), hashed_sort(hashed_sort), buffer_manager(BufferManager::GetBufferManager(client)), allocator(Allocator::Get(client)), fixed_bits(0), max_bits(1), count(0) { if (hashed_sort.track_single_keys) { - single_key_tracker = make_uniq(allocator, hashed_sort.partition_key_types); + single_key_tracker = make_uniq( + client.GetContext(), allocator, hashed_sort.partition_key_types, *hashed_sort.partition_key_mismatch); } const auto memory_per_thread = PhysicalOperator::GetMaxThreadMemory(client); @@ -410,7 +413,8 @@ HashedSortLocalSinkState::HashedSortLocalSinkState(ExecutionContext &context, co payload_chunk.Initialize(allocator, hash_types); if (hashed_sort.track_single_keys) { - single_key_tracker = make_uniq(allocator, group_types); + single_key_tracker = make_uniq(context.client.GetContext(), allocator, group_types, + *hashed_sort.partition_key_mismatch); } } @@ -654,6 +658,16 @@ HashedSort::HashedSort(ClientContext &client, const vectorGetReturnType()); } + if (partition_key_count > 0) { + vector> key_mismatches; + for (idx_t key_idx = 0; key_idx < partition_key_count; key_idx++) { + auto &type = partition_key_types[key_idx]; + key_mismatches.push_back(BoundComparisonExpression::CreateOnColumns( + client, ExpressionType::COMPARE_DISTINCT_FROM, type, key_idx, type, partition_key_count + key_idx)); + } + partition_key_mismatch = + BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_OR, std::move(key_mismatches)); + } // We have to compute ordering expressions ourselves and materialise them. // To do this, we scan the orders and add generate extra payload columns that we can reference. diff --git a/src/duckdb/src/common/sort/partition_key_tracker.cpp b/src/duckdb/src/common/sort/partition_key_tracker.cpp index 3b65a0bbb..c570a295b 100644 --- a/src/duckdb/src/common/sort/partition_key_tracker.cpp +++ b/src/duckdb/src/common/sort/partition_key_tracker.cpp @@ -17,8 +17,12 @@ static idx_t GetPartitionRowIndex(PartitionedTupleDataAppendState &append_state, return idx; } -PartitionKeyTracker::PartitionKeyTracker(Allocator &allocator_p, const vector &key_types_p) - : key_count(key_types_p.size()) { +PartitionKeyTracker::PartitionKeyTracker(Context &context, Allocator &allocator_p, + const vector &key_types_p, const Expression &key_mismatch) + : key_count(key_types_p.size()), key_mismatch(context, key_mismatch) { + auto compare_types = key_types_p; + compare_types.insert(compare_types.end(), key_types_p.begin(), key_types_p.end()); + compare_keys.InitializeEmpty(compare_types); single_value_sel.Initialize(); candidate_input_sel.Initialize(PARTITION_KEY_TRACKER_CAPACITY); candidate_rep_sel.Initialize(PARTITION_KEY_TRACKER_CAPACITY); @@ -36,6 +40,12 @@ void PartitionKeyTracker::Reset(idx_t radix_bits_p) { hashes.resize(partition_count); representatives.Reset(); representatives.SetChildCardinality(partition_count); + // the comparisons slice the representatives, so the bins without a key must hold valid (NULL) values + for (auto &representative : representatives.data) { + for (idx_t bin_idx = 0; bin_idx < partition_count; bin_idx++) { + FlatVector::SetNull(representative, bin_idx, true); + } + } } bool PartitionKeyTracker::CanBypass(idx_t hash_bin) const { @@ -156,33 +166,20 @@ idx_t PartitionKeyTracker::BuildCandidates(DataChunk &keys, Vector &input_hashes return candidate_count; } -idx_t PartitionKeyTracker::CompactCandidates(idx_t candidate_count) { - idx_t new_count = 0; - for (idx_t candidate_idx = 0; candidate_idx < candidate_count; candidate_idx++) { - const auto bin_idx = candidate_rep_sel.get_index_unsafe(candidate_idx); - const auto input_idx = candidate_input_sel.get_index_unsafe(candidate_idx); - const auto keep = states[bin_idx] == PartitionKeyTrackerState::SINGLE_KEY; - candidate_input_sel.set_index(new_count, input_idx); - candidate_rep_sel.set_index(new_count, bin_idx); - new_count += keep; - } - return new_count; -} - void PartitionKeyTracker::CompareCandidates(DataChunk &keys, idx_t candidate_count) { D_ASSERT(candidate_count <= STANDARD_VECTOR_SIZE); - for (idx_t col_idx = 0; col_idx < key_count && candidate_count; col_idx++) { - Vector input_slice(keys.data[col_idx], candidate_input_sel, candidate_count); - Vector representative_slice(representatives.data[col_idx], candidate_rep_sel, candidate_count); - const auto mismatch_count = VectorOperations::DistinctFrom(input_slice, representative_slice, nullptr, - candidate_count, &mismatch_sel, nullptr); - for (idx_t mismatch_idx = 0; mismatch_idx < mismatch_count; mismatch_idx++) { - const auto candidate_idx = mismatch_sel.get_index_unsafe(mismatch_idx); - MarkMixed(candidate_rep_sel.get_index_unsafe(candidate_idx)); - } - if (mismatch_count && col_idx + 1 < key_count) { - candidate_count = CompactCandidates(candidate_count); - } + if (!candidate_count) { + return; + } + for (idx_t col_idx = 0; col_idx < key_count; col_idx++) { + compare_keys.data[col_idx].Slice(keys.data[col_idx], candidate_input_sel, candidate_count); + compare_keys.data[key_count + col_idx].Slice(representatives.data[col_idx], candidate_rep_sel, candidate_count); + } + compare_keys.CheckCardinality(candidate_count); + const auto mismatch_count = key_mismatch.SelectExpression(compare_keys, mismatch_sel); + for (idx_t mismatch_idx = 0; mismatch_idx < mismatch_count; mismatch_idx++) { + const auto candidate_idx = mismatch_sel.get_index_unsafe(mismatch_idx); + MarkMixed(candidate_rep_sel.get_index_unsafe(candidate_idx)); } } @@ -210,33 +207,21 @@ void PartitionKeyTracker::CombineBin(const PartitionKeyTracker &source, idx_t bi candidate_count++; } -idx_t PartitionKeyTracker::CompactTrackerCandidates(idx_t candidate_count) { - idx_t new_count = 0; - for (idx_t candidate_idx = 0; candidate_idx < candidate_count; candidate_idx++) { - const auto bin_idx = candidate_input_sel.get_index_unsafe(candidate_idx); - const auto source_bin_idx = candidate_rep_sel.get_index_unsafe(candidate_idx); - const auto keep = states[bin_idx] == PartitionKeyTrackerState::SINGLE_KEY; - candidate_input_sel.set_index(new_count, bin_idx); - candidate_rep_sel.set_index(new_count, source_bin_idx); - new_count += keep; - } - return new_count; -} - void PartitionKeyTracker::CompareTrackerCandidates(const PartitionKeyTracker &source, idx_t candidate_count) { D_ASSERT(candidate_count <= PARTITION_KEY_TRACKER_CAPACITY); - for (idx_t col_idx = 0; col_idx < key_count && candidate_count; col_idx++) { - Vector target_slice(representatives.data[col_idx], candidate_input_sel, candidate_count); - Vector source_slice(source.representatives.data[col_idx], candidate_rep_sel, candidate_count); - const auto mismatch_count = VectorOperations::DistinctFrom(target_slice, source_slice, nullptr, candidate_count, - &mismatch_sel, nullptr); - for (idx_t mismatch_idx = 0; mismatch_idx < mismatch_count; mismatch_idx++) { - const auto candidate_idx = mismatch_sel.get_index_unsafe(mismatch_idx); - MarkMixed(candidate_input_sel.get_index_unsafe(candidate_idx)); - } - if (mismatch_count && col_idx + 1 < key_count) { - candidate_count = CompactTrackerCandidates(candidate_count); - } + if (!candidate_count) { + return; + } + for (idx_t col_idx = 0; col_idx < key_count; col_idx++) { + compare_keys.data[col_idx].Slice(representatives.data[col_idx], candidate_input_sel, candidate_count); + compare_keys.data[key_count + col_idx].Slice(source.representatives.data[col_idx], candidate_rep_sel, + candidate_count); + } + compare_keys.CheckCardinality(candidate_count); + const auto mismatch_count = key_mismatch.SelectExpression(compare_keys, mismatch_sel); + for (idx_t mismatch_idx = 0; mismatch_idx < mismatch_count; mismatch_idx++) { + const auto candidate_idx = mismatch_sel.get_index_unsafe(mismatch_idx); + MarkMixed(candidate_input_sel.get_index_unsafe(candidate_idx)); } } diff --git a/src/duckdb/src/common/sort/sort.cpp b/src/duckdb/src/common/sort/sort.cpp index b6699d532..c6782a5b8 100644 --- a/src/duckdb/src/common/sort/sort.cpp +++ b/src/duckdb/src/common/sort/sort.cpp @@ -261,6 +261,11 @@ unique_ptr Sort::GetGlobalSinkState(ClientContext &context) con } //! Returns true if the Sink call is done (either because run size is small or because run was finalized) +idx_t Sort::GetLocalSizeInBytes(LocalSinkState &lstate_p) const { + auto &lstate = lstate_p.Cast(); + return lstate.sorted_run ? lstate.sorted_run->SizeInBytesForSorting() : 0; +} + static bool TryFinishSink(SortGlobalSinkState &gstate, SortLocalSinkState &lstate, unique_lock &guard) { // Check if we exceed the limit (sorting the run needs a merge buffer on top of the run itself) const auto sorted_run_size = lstate.sorted_run->SizeInBytesForSorting(); @@ -550,7 +555,7 @@ SourceResultType Sort::MaterializeColumnData(ExecutionContext &context, Operator while (true) { // Check for interrupts since this could be a long-running task - context.client.InterruptCheck(); + context.client.FastInterruptCheck(); // Scan a chunk chunk.Reset(); GetData(context, chunk, input); diff --git a/src/duckdb/src/common/sort/sorted_run.cpp b/src/duckdb/src/common/sort/sorted_run.cpp index 08fe1623b..ee7abbcb5 100644 --- a/src/duckdb/src/common/sort/sorted_run.cpp +++ b/src/duckdb/src/common/sort/sorted_run.cpp @@ -284,7 +284,7 @@ static void SortTiedBucket(ClientContext &context, const ITERATOR &begin, const if constexpr (SORT_KEY::CONSTANT_SIZE) { duckdb_ska_sort::detail::StdSortFallback(begin, end, extract_key, merge); } else { - context.InterruptCheck(); + context.FastInterruptCheck(); D_ASSERT(end - begin >= 2); using SUFFIX = SkaExtractSuffixKey; constexpr idx_t MIN_RADIX_COUNT = 1024; @@ -330,7 +330,7 @@ static void SortTiedBucket(ClientContext &context, const ITERATOR &begin, const idx_t scanned = 0; for (auto it = begin + 1; it != end; ++it) { if (++scanned % STANDARD_VECTOR_SIZE == 0) { - context.InterruptCheck(); + context.FastInterruptCheck(); } if (it->part0 != samples[0].part0 || !SUFFIX::PrefixMatches(samples[0], *it, offset)) { duckdb_ska_sort::detail::StdSortFallback(begin, end, extract_key, merge); @@ -353,7 +353,7 @@ static void SortTiedBucket(ClientContext &context, const ITERATOR &begin, const scanned = 0; for (auto it = begin; it != end; ++it) { if (++scanned % STANDARD_VECTOR_SIZE == 0) { - context.InterruptCheck(); + context.FastInterruptCheck(); } it->part0 = SUFFIX::ExtractWord(*it, offset); } @@ -398,7 +398,7 @@ static void TemplatedSort(ClientContext &context, TupleDataCollection &key_data, }; duckdb_vergesort::vergesort(begin, end, std::less(), fallback, merge); - context.InterruptCheck(); + context.FastInterruptCheck(); } static void SortSwitch(ClientContext &context, TupleDataCollection &key_data, bool is_index_sort) { @@ -488,7 +488,7 @@ static void TemplatedReorder(ClientContext &context, unique_ptr(total_count - index, STANDARD_VECTOR_SIZE); for (idx_t i = 0; i < next; i++) { diff --git a/src/duckdb/src/common/sort/sorted_run_merger.cpp b/src/duckdb/src/common/sort/sorted_run_merger.cpp index af7c90d99..b813fb008 100644 --- a/src/duckdb/src/common/sort/sorted_run_merger.cpp +++ b/src/duckdb/src/common/sort/sorted_run_merger.cpp @@ -959,7 +959,7 @@ static idx_t CollectMergeByteSamples(const SortedRunMerger &merger, const TupleD ExternalBlockIteratorState key_state(*run.key_data, nullptr); idx_t begin = 0; for (idx_t interval_idx = 0; interval_idx < intervals; interval_idx++) { - context.InterruptCheck(); + context.FastInterruptCheck(); const auto width = interval_size + (interval_idx < remainder); const auto end = begin + width; const auto phase = (width / run_count) * run_idx + ((width % run_count) * run_idx) / run_count; diff --git a/src/duckdb/src/common/string_util.cpp b/src/duckdb/src/common/string_util.cpp index ff9d96457..eb1300459 100644 --- a/src/duckdb/src/common/string_util.cpp +++ b/src/duckdb/src/common/string_util.cpp @@ -1143,6 +1143,17 @@ const char *StringUtil::EnumToString(const EnumStringLiteral enum_list[], idx_t throw NotImplementedException("Enum value: unrecognized enum value \"%d\" for enum \"%s\"", enum_value, enum_name); } +string StringUtil::TruncateUTF8TOByteLength(const char *data, idx_t length, idx_t max_bytes) { + if (length <= max_bytes) { + return string(data, length); + } + idx_t end = max_bytes; + while (end > 0 && ((static_cast(data[end]) & 0xC0) == 0x80)) { + end--; + } + return string(data, end) + "..."; +} + const uint8_t StringUtil::ASCII_TO_UPPER_MAP[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, diff --git a/src/duckdb/src/common/tree_renderer.cpp b/src/duckdb/src/common/tree_renderer.cpp index c02d50dd7..23dcba5a9 100644 --- a/src/duckdb/src/common/tree_renderer.cpp +++ b/src/duckdb/src/common/tree_renderer.cpp @@ -10,7 +10,6 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/main/query_profiler.hpp" -#include "duckdb/main/client_config.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/main/profiler_extension.hpp" @@ -119,14 +118,21 @@ Value TreeRenderer::RendererSettingsToValue(const unordered_map & } unique_ptr TreeRenderer::CreateRenderer(ClientContext &context, const string &name) { + return CreateRenderer(context, name, GetRendererSettings(context)); +} + +unique_ptr TreeRenderer::CreateRenderer(ClientContext &context, const string &name, + const unordered_map &settings) { // registered renderers take precedence over the built-in formats + unique_ptr renderer; auto extension = ProfilerExtension::Find(context, name); if (extension && extension->create_renderer) { - return extension->create_renderer(context); + renderer = extension->create_renderer(context); + } else { + renderer = CreateRenderer(name); } - auto renderer = CreateRenderer(name); if (renderer) { - renderer->Configure(GetRendererSettings(context)); + renderer->Configure(settings); } return renderer; } diff --git a/src/duckdb/src/common/types.cpp b/src/duckdb/src/common/types.cpp index 1ff8f3619..4286e7f0f 100644 --- a/src/duckdb/src/common/types.cpp +++ b/src/duckdb/src/common/types.cpp @@ -99,6 +99,7 @@ static bool TryGetBuiltinPhysicalType(LogicalTypeId id, PhysicalType &result) no case LogicalTypeId::BIT: case LogicalTypeId::TYPE: case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: result = PhysicalType::VARCHAR; return true; case LogicalTypeId::INTERVAL: @@ -318,6 +319,7 @@ bool LogicalType::HasParameters() const { case LogicalTypeId::TEMPLATE: return info_type == LogicalTypeInfoType::TEMPLATE_TYPE_INFO; case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: return info_type == LogicalTypeInfoType::GEO_TYPE_INFO; case LogicalTypeId::UNBOUND: return info_type == LogicalTypeInfoType::UNBOUND_TYPE_INFO; @@ -414,10 +416,10 @@ const vector LogicalType::AllTypes() { LogicalTypeId::UBIGINT, LogicalTypeId::TIMESTAMP_TZ, LogicalTypeId::TIMESTAMP_TZ_NS, LogicalTypeId::TIME_TZ, LogicalTypeId::TIME_NS, LogicalTypeId::BIT, LogicalTypeId::BIGNUM, LogicalTypeId::UHUGEINT, LogicalTypeId::HUGEINT, - LogicalTypeId::UUID, LogicalTypeId::GEOMETRY, LogicalTypeId::STRUCT, - LogicalTypeId::TUPLE, LogicalTypeId::LIST, LogicalTypeId::MAP, - LogicalTypeId::ENUM, LogicalTypeId::UNION, LogicalTypeId::ARRAY, - LogicalTypeId::VARIANT, + LogicalTypeId::UUID, LogicalTypeId::GEOMETRY, LogicalTypeId::GEOGRAPHY, + LogicalTypeId::STRUCT, LogicalTypeId::TUPLE, LogicalTypeId::LIST, + LogicalTypeId::MAP, LogicalTypeId::ENUM, LogicalTypeId::UNION, + LogicalTypeId::ARRAY, LogicalTypeId::VARIANT, }; return types; } @@ -717,6 +719,15 @@ string LogicalType::ToString() const { result += StringUtil::Format("GEOMETRY(%s)", SQLString(crs.GetDefinition())); break; } + case LogicalTypeId::GEOGRAPHY: { + if (!GeoType::HasCRS(type)) { + result += "GEOGRAPHY"; + break; + } + auto &crs = GeoType::GetCRS(type); + result += StringUtil::Format("GEOGRAPHY(%s)", SQLString(crs.GetDefinition())); + break; + } case LogicalTypeId::VARCHAR: { // a collation is part of the type's identity: the constructor form parses in type position auto &string_type_info = type.GetTypeInfo(); @@ -906,6 +917,71 @@ bool LogicalType::IsTemplated() const { return TypeVisitor::Contains(*this, LogicalTypeId::TEMPLATE); } +bool LogicalType::EqualValuesAreIdentical() const { + switch (id()) { + case LogicalTypeId::BOOLEAN: + case LogicalTypeId::TINYINT: + case LogicalTypeId::SMALLINT: + case LogicalTypeId::INTEGER: + case LogicalTypeId::BIGINT: + case LogicalTypeId::HUGEINT: + case LogicalTypeId::UTINYINT: + case LogicalTypeId::USMALLINT: + case LogicalTypeId::UINTEGER: + case LogicalTypeId::UBIGINT: + case LogicalTypeId::UHUGEINT: + case LogicalTypeId::DECIMAL: + case LogicalTypeId::DATE: + case LogicalTypeId::TIME: + case LogicalTypeId::TIME_NS: + case LogicalTypeId::TIMESTAMP_SEC: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::TIMESTAMP_NS: + case LogicalTypeId::TIMESTAMP_TZ: + case LogicalTypeId::TIMESTAMP_TZ_NS: + case LogicalTypeId::BLOB: + case LogicalTypeId::UUID: + case LogicalTypeId::ENUM: + return true; + case LogicalTypeId::VARCHAR: + return StringType::GetCollation(*this).empty(); + case LogicalTypeId::STRUCT: + for (auto &child : StructType::GetChildTypes(*this)) { + if (!child.second.EqualValuesAreIdentical()) { + return false; + } + } + return true; + case LogicalTypeId::LIST: + return ListType::GetChildType(*this).EqualValuesAreIdentical(); + case LogicalTypeId::ARRAY: + return ArrayType::GetChildType(*this).EqualValuesAreIdentical(); + default: + return false; + } +} + +bool LogicalType::HasPhysicalType() const { + return !TypeVisitor::Contains(*this, [](const LogicalType &type) { + switch (type.InternalType()) { + case PhysicalType::INVALID: + return true; + case PhysicalType::LIST: + case PhysicalType::STRUCT: + case PhysicalType::ARRAY: + if (!type.HasParameters()) { + return true; + } + // the visitor does not look at the child types of a VARIANT, which are those of its storage layout + return type.id() == LogicalTypeId::VARIANT && + StructType::GetChildTypes(type) != StructType::GetChildTypes(LogicalType::VARIANT()); + default: + return false; + } + }); +} + bool LogicalType::SupportsRegularUpdate() const { switch (id()) { case LogicalTypeId::LIST: @@ -913,7 +989,8 @@ bool LogicalType::SupportsRegularUpdate() const { case LogicalTypeId::MAP: case LogicalTypeId::UNION: case LogicalTypeId::VARIANT: - case LogicalTypeId::GEOMETRY: // If geometry is shredded, its parts (lists/structs) can't be regularly updated. + case LogicalTypeId::GEOMETRY: // If geometry is shredded, its parts (lists/structs) can't be regularly updated. + case LogicalTypeId::GEOGRAPHY: // Same shredded storage as geometry. return false; case LogicalTypeId::STRUCT: case LogicalTypeId::TUPLE: { @@ -1313,6 +1390,8 @@ static idx_t GetLogicalTypeScore(const LogicalType &type) { return 103; case LogicalTypeId::GEOMETRY: return 104; + case LogicalTypeId::GEOGRAPHY: + return 106; // nested types case LogicalTypeId::STRUCT: case LogicalTypeId::TUPLE: @@ -1466,6 +1545,12 @@ void LogicalType::Serialize(Serializer &serializer) const { return; } + // GEOGRAPHY has no legacy representation, so it cannot be downgraded to older storage versions. + if (id() == LogicalTypeId::GEOGRAPHY && !serializer.ShouldSerialize(Geometry::GEOGRAPHY_VERSION_ADDED)) { + throw NotImplementedException("The GEOGRAPHY type cannot be written to a storage version older than %s", + GetStorageVersionName(Geometry::GEOGRAPHY_VERSION_ADDED, false)); + } + // This is a UNBOUND type and we are writing to older storage. // 1. try to default-bind into a concrete logical type, and serialize that // 2. if that fails, serialize normally, in which case the UNBOUND_TYPE_INFO will try to @@ -1505,6 +1590,21 @@ void LogicalType::Serialize(Serializer &serializer) const { serializer.WritePropertyWithDefault>(101, "type_info", type_info); } +//! Whether a type cannot be used without its type info (the info holds the child types / members) +static bool RequiresTypeInfo(LogicalTypeId id) { + switch (id) { + case LogicalTypeId::LIST: + case LogicalTypeId::MAP: + case LogicalTypeId::ARRAY: + case LogicalTypeId::STRUCT: + case LogicalTypeId::UNION: + case LogicalTypeId::ENUM: + return true; + default: + return false; + } +} + LogicalType LogicalType::Deserialize(Deserializer &deserializer) { auto id = deserializer.ReadProperty(100, "id"); deserializer.CheckAllowed(id); @@ -1537,6 +1637,10 @@ LogicalType LogicalType::Deserialize(Deserializer &deserializer) { throw SerializationException("Failed to deserialize type %s: type info %s does not match the type", EnumUtil::ToString(id), EnumUtil::ToString(info_type)); } + if (RequiresTypeInfo(id) && !result.HasParameters()) { + // the child types of these types are looked up in the type info without checking that it is there + throw SerializationException("Failed to deserialize type %s: missing type info", EnumUtil::ToString(id)); + } if (Geometry::IsSpatialGeometryType(result)) { // This is a legacy geometry type, deserialize as geometry return LogicalType::GEOMETRY(); @@ -2145,8 +2249,27 @@ LogicalType LogicalType::GEOMETRY(const CoordinateReferenceSystem &crs) { return LogicalType(LogicalTypeId::GEOMETRY, std::move(info)); } +LogicalType LogicalType::GEOGRAPHY() { + return LogicalType(LogicalTypeId::GEOGRAPHY); +} + +LogicalType LogicalType::GEOGRAPHY(const string &crs) { + if (crs.empty()) { + return LogicalType::GEOGRAPHY(); + } + auto info = make_uniq(); + info->crs = CoordinateReferenceSystem(crs); + return LogicalType(LogicalTypeId::GEOGRAPHY, std::move(info)); +} + +LogicalType LogicalType::GEOGRAPHY(const CoordinateReferenceSystem &crs) { + auto info = make_uniq(); + info->crs = crs; + return LogicalType(LogicalTypeId::GEOGRAPHY, std::move(info)); +} + bool GeoType::HasCRS(const LogicalType &type) { - D_ASSERT(type.id() == LogicalTypeId::GEOMETRY); + D_ASSERT(type.id() == LogicalTypeId::GEOMETRY || type.id() == LogicalTypeId::GEOGRAPHY); auto &info = type.GetTypeInfo(); if (info.type != LogicalTypeInfoType::GEO_TYPE_INFO) { // a GEOMETRY type without geo type info has no CRS - this can happen when an alias is set on a geometry @@ -2159,7 +2282,7 @@ bool GeoType::HasCRS(const LogicalType &type) { } const CoordinateReferenceSystem &GeoType::GetCRS(const LogicalType &type) { - D_ASSERT(type.id() == LogicalTypeId::GEOMETRY); + D_ASSERT(type.id() == LogicalTypeId::GEOMETRY || type.id() == LogicalTypeId::GEOGRAPHY); auto &info = type.GetTypeInfo(); if (info.type != LogicalTypeInfoType::GEO_TYPE_INFO) { throw InternalException("Geometry type has no CRS information"); diff --git a/src/duckdb/src/common/types/bignum.cpp b/src/duckdb/src/common/types/bignum.cpp index 717c37f87..8b84bce8b 100644 --- a/src/duckdb/src/common/types/bignum.cpp +++ b/src/duckdb/src/common/types/bignum.cpp @@ -716,14 +716,19 @@ static idx_t BignumCastToDecimal(const bignum_t &blob, BignumCastScratch &scratc } string Bignum::BignumToVarchar(const bignum_t &blob, optional_ptr context) { - BignumCastScratch scratch(context); - bool is_negative; - const idx_t length = BignumCastToDecimal(blob, scratch, is_negative); - string result(length, '\0'); - BignumCastWriteDecimal(&result[0] + length, scratch.decimal, length - (is_negative ? 1 : 0), is_negative); + BignumCastScratch state(context); + string result; + BignumToVarchar(state, blob, result); return result; } +void Bignum::BignumToVarchar(BignumCastScratch &state, const bignum_t &blob, string &result) { + bool is_negative; + const idx_t length = BignumCastToDecimal(blob, state, is_negative); + result.resize(length); + BignumCastWriteDecimal(&result[0] + length, state.decimal, length - (is_negative ? 1 : 0), is_negative); +} + string_t Bignum::BignumToVarchar(const bignum_t &blob, Vector &result, BignumCastScratch &scratch) { bool is_negative; const idx_t length = BignumCastToDecimal(blob, scratch, is_negative); diff --git a/src/duckdb/src/common/types/bignum_decimal.cpp b/src/duckdb/src/common/types/bignum_decimal.cpp index d7cc63316..a551f81f9 100644 --- a/src/duckdb/src/common/types/bignum_decimal.cpp +++ b/src/duckdb/src/common/types/bignum_decimal.cpp @@ -313,10 +313,10 @@ bool DecimalHelper::IsZero(const bignum_t &value) { } //! The unscaled value formatted with the given scale, with at least one digit before the decimal point -static string FormatScaled(const bignum_t &value, uint32_t scale, optional_ptr context) { - auto digits = Bignum::BignumToVarchar(value, context); +static void FormatScaled(BignumCastScratch &state, string &digits, const bignum_t &value, uint32_t scale) { + Bignum::BignumToVarchar(state, value, digits); if (scale == 0) { - return digits; + return; } bool negative = false; if (!digits.empty() && digits[0] == '-') { @@ -331,7 +331,13 @@ static string FormatScaled(const bignum_t &value, uint32_t scale, optional_ptr context) { + BignumCastScratch state(context); + string result; + FormatScaled(state, result, value, scale); + return result; } string DecimalHelper::ToString(const bignum_t &value, uint32_t width, uint32_t scale, @@ -450,41 +456,94 @@ bool DecimalHelper::TryParse(const char *data, idx_t size, uint32_t wi return true; } +const string &DecimalHelper::RescaleState::GetPowerOfTen(idx_t exponent) { + if (cached_exponent != exponent) { + cached_power = PowerOfTen(exponent, Context::TryGetClientContext(arithmetic.context)); + cached_exponent = exponent; + } + return cached_power; +} + +static string_t DivideAndRound(const BignumIntermediate &source, const BignumIntermediate &divisor, + DecimalRounding rounding, StringHeap &heap, BignumArithmeticState &state) { + string_t quotient; + string_t remainder; + if (!BignumIntermediate::TryDivMod(heap, state, source, divisor, quotient, remainder)) { + throw InternalException("Decimal rescaling: division by a power of ten failed"); + } + if (DecimalHelper::IsZero(bignum_t(remainder))) { + return quotient; + } + // The remainder has the sign of the value; the quotient is truncated towards zero. + const bool negative = source.is_negative; + int32_t adjustment = 0; + switch (rounding) { + case DecimalRounding::TRUNCATE: + break; + case DecimalRounding::FLOOR: + adjustment = negative ? -1 : 0; + break; + case DecimalRounding::CEIL: + adjustment = negative ? 0 : 1; + break; + default: { + BorrowedBignum remainder_value {bignum_t(remainder)}; + auto twice_remainder = + BignumIntermediate::Multiply(heap, state, remainder_value.intermediate, BignumConstant(2).intermediate); + BorrowedBignum twice_remainder_value {bignum_t(twice_remainder)}; + BorrowedBignum quotient_value {bignum_t(quotient)}; + auto comparison = twice_remainder_value.intermediate.IsAbsoluteBigger(divisor); + const bool away = comparison == GREATER || + (comparison == EQUAL && + (rounding == DecimalRounding::HALF_AWAY_FROM_ZERO || IsOdd(quotient_value.intermediate))); + adjustment = away ? (negative ? -1 : 1) : 0; + break; + } + } + if (adjustment == 0) { + return quotient; + } + BorrowedBignum quotient_value {bignum_t(quotient)}; + return BignumIntermediate::Add(heap, quotient_value.intermediate, BignumConstant(adjustment).intermediate); +} + +static string_t RescaleBignum(const bignum_t &value, uint32_t source_scale, uint32_t target_scale, const string &power, + StringHeap &heap, BignumArithmeticState &state) { + BorrowedBignum source(value); + BorrowedBignum factor(power); + if (target_scale > source_scale) { + return BignumIntermediate::Multiply(heap, state, source.intermediate, factor.intermediate); + } + return DivideAndRound(source.intermediate, factor.intermediate, DecimalRounding::HALF_AWAY_FROM_ZERO, heap, state); +} + string DecimalHelper::Rescale(const bignum_t &value, uint32_t source_scale, uint32_t target_scale, optional_ptr context) { if (target_scale == source_scale) { return value.data.GetString(); } - BorrowedBignum source(value); - StringHeap heap; - BignumArithmeticState state(context); - if (target_scale > source_scale) { - const auto power = PowerOfTen(target_scale - source_scale, context); - BorrowedBignum factor(power); - return BignumIntermediate::Multiply(heap, state, source.intermediate, factor.intermediate).GetString(); - } - // scaling down divides by the power of ten and rounds half away from zero - const auto power = PowerOfTen(source_scale - target_scale, context); - BorrowedBignum divisor(power); - string_t quotient; - string_t remainder; - if (!BignumIntermediate::TryDivMod(heap, state, source.intermediate, divisor.intermediate, quotient, remainder)) { - throw InternalException("DecimalHelper::Rescale: division by a power of ten failed"); + RescaleState state(context); + return Rescale(state, value, source_scale, target_scale).data.GetString(); +} + +bignum_t DecimalHelper::Rescale(RescaleState &scratch, const bignum_t &value, uint32_t source_scale, + uint32_t target_scale) { + if (target_scale == source_scale) { + return value; } - const bignum_t remainder_bignum(remainder); - BorrowedBignum remainder_value(remainder_bignum); - auto twice_remainder = - BignumIntermediate::Multiply(heap, state, remainder_value.intermediate, BignumConstant(2).intermediate); - const bignum_t twice_remainder_bignum(twice_remainder); - BorrowedBignum twice_remainder_value(twice_remainder_bignum); - if (twice_remainder_value.intermediate.IsAbsoluteBigger(divisor.intermediate) != SMALLER) { - // |remainder| >= divisor / 2 rounds away from zero - auto &one = BignumConstant(source.intermediate.is_negative ? -1 : 1); - const bignum_t quotient_bignum(quotient); - BorrowedBignum quotient_value(quotient_bignum); - quotient = BignumIntermediate::Add(heap, quotient_value.intermediate, one.intermediate); + const auto exponent = target_scale > source_scale ? target_scale - source_scale : source_scale - target_scale; + return bignum_t(RescaleBignum(value, source_scale, target_scale, scratch.GetPowerOfTen(exponent), scratch.heap, + scratch.arithmetic)); +} + +bignum_t DecimalHelper::Rescale(RescaleState &scratch, hugeint_t value, uint32_t source_scale, + uint32_t target_scale) { + if (target_scale > source_scale && target_scale - source_scale <= Decimal::MAX_WIDTH_INT128) { + return bignum_t( + BignumIntermediate::Multiply(scratch.heap, value, Hugeint::POWERS_OF_TEN[target_scale - source_scale])); } - return quotient.GetString(); + auto unscaled = HugeintCastToBignum::Operation(value, scratch.heap); + return Rescale(scratch, unscaled, source_scale, target_scale); } bool DecimalHelper::TryRescale(const bignum_t &value, uint32_t source_scale, uint32_t target_width, @@ -515,51 +574,7 @@ bool DecimalHelper::TryRound(const bignum_t &value, idx_t drop_digits, if (drop_digits > 0) { const auto power = PowerOfTen(drop_digits, Context::TryGetClientContext(state.context)); BorrowedBignum divisor(power); - string_t quotient; - string_t remainder; - if (!BignumIntermediate::TryDivMod(heap, state, source.intermediate, divisor.intermediate, quotient, - remainder)) { - throw InternalException("DecimalHelper::TryRound: division by a power of ten failed"); - } - // the remainder has the sign of the value: the quotient is truncated towards zero - const bool negative = source.intermediate.is_negative; - int32_t adjustment = 0; - if (!IsZero(bignum_t(remainder))) { - switch (rounding) { - case DecimalRounding::TRUNCATE: - break; - case DecimalRounding::FLOOR: - adjustment = negative ? -1 : 0; - break; - case DecimalRounding::CEIL: - adjustment = negative ? 0 : 1; - break; - default: { - const bignum_t remainder_bignum(remainder); - BorrowedBignum remainder_value(remainder_bignum); - auto twice_remainder = BignumIntermediate::Multiply(heap, state, remainder_value.intermediate, - BignumConstant(2).intermediate); - const bignum_t twice_remainder_bignum(twice_remainder); - BorrowedBignum twice_remainder_value(twice_remainder_bignum); - const bignum_t quotient_bignum(quotient); - BorrowedBignum quotient_value(quotient_bignum); - auto comparison = twice_remainder_value.intermediate.IsAbsoluteBigger(divisor.intermediate); - // above the half the value rounds away from zero, on the half the rounding mode decides - const bool away = comparison == GREATER || - (comparison == EQUAL && (rounding == DecimalRounding::HALF_AWAY_FROM_ZERO || - IsOdd(quotient_value.intermediate))); - adjustment = away ? (negative ? -1 : 1) : 0; - break; - } - } - } - rounded = quotient; - if (adjustment != 0) { - const bignum_t quotient_bignum(quotient); - BorrowedBignum quotient_value(quotient_bignum); - rounded = - BignumIntermediate::Add(heap, quotient_value.intermediate, BignumConstant(adjustment).intermediate); - } + rounded = DivideAndRound(source.intermediate, divisor.intermediate, rounding, heap, state); } if (restore_digits > 0) { const bignum_t rounded_bignum(rounded); @@ -575,7 +590,7 @@ bool DecimalHelper::TryRound(const bignum_t &value, idx_t drop_digits, return true; } -string DecimalHelper::FromInteger(uhugeint_t value) { +void DecimalHelper::FromInteger(uhugeint_t value, string &result) { uint8_t bytes[16]; idx_t size = 0; for (idx_t i = 0; i < 16; i++) { @@ -587,22 +602,36 @@ string DecimalHelper::FromInteger(uhugeint_t value) { } bytes[size++] = byte; } - return Bignum::FromByteArray(bytes, size, false); + result.resize(Bignum::BIGNUM_HEADER_SIZE + size); + Bignum::SetHeader(&result[0], size, false); + memcpy(&result[Bignum::BIGNUM_HEADER_SIZE], bytes, size); } -string DecimalHelper::FromInteger(hugeint_t value) { +void DecimalHelper::FromInteger(hugeint_t value, string &result) { if (value.upper >= 0) { - return FromInteger(uhugeint_t(static_cast(value.upper), value.lower)); + FromInteger(uhugeint_t(static_cast(value.upper), value.lower), result); + return; } // the magnitude of the minimum hugeint (2^127) fits a uhugeint, so negate in uhugeint two's complement space uhugeint_t bits(static_cast(value.upper), value.lower); uhugeint_t magnitude = ~bits + uhugeint_t(1); - auto blob = FromInteger(magnitude); + FromInteger(magnitude, result); // complementing the header and data bytes flips the sign - for (auto &c : blob) { + for (auto &c : result) { c = static_cast(~c); } - return blob; +} + +string DecimalHelper::FromInteger(hugeint_t value) { + string result; + FromInteger(value, result); + return result; +} + +string DecimalHelper::FromInteger(uhugeint_t value) { + string result; + FromInteger(value, result); + return result; } bool DecimalHelper::TryToUhugeint(const bignum_t &value, uhugeint_t &result) { @@ -616,10 +645,10 @@ bool DecimalHelper::TryToHugeint(const bignum_t &value, hugeint_t &res } template -static bool TryToFloatingInternal(const bignum_t &value, uint32_t scale, T &result, - optional_ptr context) { +static bool TryToFloatingInternal(BignumCastScratch &state, string &text, const bignum_t &value, uint32_t scale, + T &result) { // the decimal text parses directly into the target type, so the value is rounded once - auto text = FormatScaled(value, scale, context); + FormatScaled(state, text, value, scale); if (!TryCast::Operation(string_t(text), result, false)) { throw InternalException("Could not convert wide decimal '%s' to a floating point number", text); } @@ -629,12 +658,26 @@ static bool TryToFloatingInternal(const bignum_t &value, uint32_t scale, T &resu bool DecimalHelper::TryToFloating(const bignum_t &value, uint32_t scale, float &result, optional_ptr context) { - return TryToFloatingInternal(value, scale, result, context); + BignumCastScratch state(context); + string text; + return TryToFloatingInternal(state, text, value, scale, result); } bool DecimalHelper::TryToFloating(const bignum_t &value, uint32_t scale, double &result, optional_ptr context) { - return TryToFloatingInternal(value, scale, result, context); + BignumCastScratch state(context); + string text; + return TryToFloatingInternal(state, text, value, scale, result); +} + +bool DecimalHelper::TryToFloating(BignumCastScratch &state, string &text, const bignum_t &value, + uint32_t scale, float &result) { + return TryToFloatingInternal(state, text, value, scale, result); +} + +bool DecimalHelper::TryToFloating(BignumCastScratch &state, string &text, const bignum_t &value, + uint32_t scale, double &result) { + return TryToFloatingInternal(state, text, value, scale, result); } double DecimalHelper::ToDouble(const bignum_t &value, uint32_t scale, optional_ptr context) { diff --git a/src/duckdb/src/common/types/cast_helpers.cpp b/src/duckdb/src/common/types/cast_helpers.cpp index ffbd693ea..66a801201 100644 --- a/src/duckdb/src/common/types/cast_helpers.cpp +++ b/src/duckdb/src/common/types/cast_helpers.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/types/cast_helpers.hpp" +#include "duckdb/common/bignum_limbs.hpp" #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/types/uhugeint.hpp" @@ -170,32 +171,32 @@ int NumericHelper::UnsignedLength(hugeint_t value) { } } -template <> -string_t NumericHelper::FormatSigned(hugeint_t value, StringHeap &heap) { - int negative = value.upper < 0; +char *NumericHelper::FormatSigned(hugeint_t value, char *ptr) { + const bool negative = value.upper < 0; + uhugeint_t magnitude(static_cast(value.upper), value.lower); if (negative) { - if (value == NumericLimits::Minimum()) { - string_t result = heap.AddString(Hugeint::HUGEINT_MINIMUM_STRING); - return result; - } - Hugeint::NegateInPlace(value); - } - int length = UnsignedLength(value) + negative; - string_t result = heap.EmptyString(NumericCast(length)); - auto dataptr = result.GetDataWriteable(); - auto endptr = dataptr + length; - if (value.upper == 0) { - // small value: format as uint64_t - endptr = NumericHelper::FormatUnsigned(value.lower, endptr); - } else { - endptr = FormatUnsigned(value, endptr); + magnitude = -magnitude; } + ptr = FormatUnsigned(magnitude, ptr); if (negative) { - *--endptr = '-'; + *--ptr = '-'; } - D_ASSERT(endptr == dataptr); - result.Finalize(); - return result; + return ptr; +} + +template <> +string_t NumericHelper::FormatSigned(hugeint_t value, StringHeap &heap) { + char buffer[NumericLimits::Digits() + 1]; + auto end = buffer + sizeof(buffer); + auto start = FormatSigned(value, end); + return heap.AddString(start, NumericCast(end - start)); +} + +string_t UhugeintToStringCast::Format(uhugeint_t value, StringHeap &heap) { + char buffer[NumericLimits::Digits()]; + auto end = buffer + sizeof(buffer); + auto start = NumericHelper::FormatUnsigned(value, end); + return heap.AddString(start, NumericCast(end - start)); } template <> @@ -249,64 +250,55 @@ string_t DecimalToString::Format(hugeint_t value, uint32_t width, uint32_t scale template <> char *NumericHelper::FormatUnsigned(hugeint_t value, char *ptr) { + D_ASSERT(value.upper >= 0); + return FormatUnsigned(uhugeint_t(static_cast(value.upper), value.lower), ptr); +} + +template <> +char *NumericHelper::FormatUnsigned(uhugeint_t value, char *ptr) { + // divide by the largest power of ten that fits in a uint64_t to do as few 128-bit divisions as possible + static constexpr uint64_t DIVISOR = 10000000000000000000ULL; + static constexpr idx_t DIVISOR_DIGITS = 19; while (value.upper > 0) { - // while integer division is slow, hugeint division is MEGA slow - // we want to avoid doing as many divisions as possible - // for that reason we start off doing a division by a large power of ten that uint64_t can hold - // (100000000000000000) - this is the third largest - // the reason we don't use the largest is because that can result in an overflow inside the division - // function uint64_t remainder; - value = Hugeint::DivModPositive(value, 100000000000000000ULL, remainder); + const auto upper = value.upper / DIVISOR; + const auto lower = BignumLimb::DivRemPortable(value.upper % DIVISOR, value.lower, DIVISOR, remainder); + value = uhugeint_t(upper, lower); - auto startptr = ptr; - // now we format the remainder: note that we need to pad with zero's in case - // the remainder is small (i.e. less than 10000000000000000) + auto chunk_start = ptr - DIVISOR_DIGITS; ptr = NumericHelper::FormatUnsigned(remainder, ptr); - - int format_length = UnsafeNumericCast(startptr - ptr); - // pad with zero - for (int i = format_length; i < 17; i++) { + while (ptr > chunk_start) { *--ptr = '0'; } } - // once the value falls in the range of a uint64_t, fallback to formatting as uint64_t to avoid hugeint division return NumericHelper::FormatUnsigned(value.lower, ptr); } template <> void DecimalToString::FormatDecimal(hugeint_t value, uint32_t width, uint32_t scale, char *dst, idx_t len) { auto endptr = dst + len; - - int negative = value.upper < 0; - if (negative) { + if (value.upper < 0) { Hugeint::NegateInPlace(value); *dst = '-'; - dst++; } + auto start = NumericHelper::FormatUnsigned(value, endptr); if (scale == 0) { - // with scale=0 we format the number as a regular number - NumericHelper::FormatUnsigned(value, endptr); return; } - - // we write two numbers: - // the numbers BEFORE the decimal (major) - // and the numbers AFTER the decimal (minor) - hugeint_t minor; - hugeint_t major = Hugeint::DivMod(value, Hugeint::POWERS_OF_TEN[scale], minor); - - // write the number after the decimal - dst = NumericHelper::FormatUnsigned(minor, endptr); - // (optionally) pad with zeros and add the decimal point - while (dst > (endptr - scale)) { - *--dst = '0'; + auto point = endptr - scale; + if (start < point) { + // shift the digits before the decimal point one to the left to make room for it + D_ASSERT(width > scale); + memmove(start - 1, start, NumericCast(point - start)); + point[-1] = '.'; + return; + } + while (start > point) { + *--start = '0'; } - *--dst = '.'; - // now write the part before the decimal - D_ASSERT(width > scale || major == 0); + *--start = '.'; if (width > scale) { - dst = NumericHelper::FormatUnsigned(major, dst); + *--start = '0'; } } diff --git a/src/duckdb/src/common/types/data_chunk.cpp b/src/duckdb/src/common/types/data_chunk.cpp index 2bb0d97ba..cb097b55f 100644 --- a/src/duckdb/src/common/types/data_chunk.cpp +++ b/src/duckdb/src/common/types/data_chunk.cpp @@ -1,11 +1,14 @@ #include "duckdb/common/types/data_chunk.hpp" #include "duckdb/common/array.hpp" +#include "duckdb/common/enum_util.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/helper.hpp" #include "duckdb/common/printer.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/serializer/deserializer.hpp" +#include "duckdb/common/type_visitor.hpp" +#include "duckdb/common/types/geometry.hpp" #include "duckdb/common/types/interval.hpp" #include "duckdb/common/types/sel_cache.hpp" #include "duckdb/common/types/vector_cache.hpp" @@ -355,6 +358,14 @@ void DataChunk::Deserialize(Deserializer &deserializer) { types.push_back(type); }); + for (auto &type : types) { + if (!type.HasPhysicalType()) { + // the type is named by its id: it can lack the type info that ToString reads + throw SerializationException("Failed to deserialize data chunk: a vector cannot hold the type %s", + EnumUtil::ToString(type.id())); + } + } + // initialize the data chunk D_ASSERT(!types.empty()); Initialize(Allocator::DefaultAllocator(), types, MaxValue(row_count, STANDARD_VECTOR_SIZE)); @@ -514,6 +525,14 @@ void DataChunk::VerifyInternal(DebugVerificationMode mode, optional_ptr= Date::DAYS_PER_YEAR_INTERVAL) { - n -= Date::DAYS_PER_YEAR_INTERVAL; - year += Date::YEAR_INTERVAL; - } - // interpolation search - // we can find an upper bound of the year by assuming each year has 365 days - year_offset = n / 365; - // because of leap years we might be off by a little bit: compensate by decrementing the year offset until we find - // our year - while (n < Date::CUMULATIVE_YEAR_DAYS[year_offset]) { - year_offset--; - D_ASSERT(year_offset >= 0); - } - year += year_offset; - D_ASSERT(n >= Date::CUMULATIVE_YEAR_DAYS[year_offset]); +namespace { + +// Days since 1970-01-01 to a civil date, using the Euclidean affine functions of Neri & Schneider (2022). +// The computation uses a calendar that starts on March 1st, so January and February belong to the previous year. +struct CivilDate { + int32_t year; + int32_t month; + int32_t day; +}; + +//! The 32-bit path is valid for days in [-FAST_DATE_RANGE, FAST_DATE_RANGE) (roughly +/- 1.4 million years) +constexpr int32_t FAST_DATE_RANGE = 536000000; +//! Shifts (in 400-year eras) that make the shifted day number non-negative and keep 4 * N + 3 in range +constexpr uint64_t FAST_DATE_ERA_SHIFT = 3670; +constexpr uint64_t FULL_DATE_ERA_SHIFT = 14704; + +inline bool IsInFastDateRange(int32_t days) { + return uint32_t(days) + uint32_t(FAST_DATE_RANGE) < uint32_t(2 * FAST_DATE_RANGE); +} + +template +inline CivilDate CivilFromDaysInternal(int32_t days) { + constexpr UINT DAY_SHIFT = 719468 + 146097 * ERA_SHIFT; + const UINT n1 = 4 * (UINT(int64_t(days)) + DAY_SHIFT) + 3; + const UINT century = n1 / 146097; + const uint32_t n2 = 4 * (uint32_t(n1 % 146097) / 4) + 3; + const uint64_t p2 = uint64_t(2939745) * n2; + const uint32_t year_of_century = uint32_t(p2 >> 32); + const uint32_t day_of_year = uint32_t(p2) / 2939745 / 4; + const uint32_t n3 = 2141 * day_of_year + 197913; + const uint32_t month = n3 >> 16; + const uint32_t day = (n3 & 0xFFFF) / 2141; + const uint32_t january_or_february = day_of_year >= 306; + CivilDate result; + result.year = + static_cast(int64_t(100 * century + year_of_century + january_or_february) - int64_t(400 * ERA_SHIFT)); + result.month = static_cast(january_or_february ? month - 12 : month); + result.day = static_cast(day + 1); + return result; } -void Date::Convert(date_t d, int32_t &year, int32_t &month, int32_t &day) { - auto n = d.days; - int32_t year_offset; - Date::ExtractYearOffset(n, year, year_offset); +inline CivilDate CivilFromDays(int32_t days) { + if (DUCKDB_LIKELY(IsInFastDateRange(days))) { + return CivilFromDaysInternal(days); + } + return CivilFromDaysInternal(days); +} - day = n - Date::CUMULATIVE_YEAR_DAYS[year_offset]; - D_ASSERT(day >= 0 && day <= 365); +} // namespace - bool is_leap_year = (Date::CUMULATIVE_YEAR_DAYS[year_offset + 1] - Date::CUMULATIVE_YEAR_DAYS[year_offset]) == 366; - if (is_leap_year) { - month = Date::LEAP_MONTH_PER_DAY_OF_YEAR[day]; - day -= Date::CUMULATIVE_LEAP_DAYS[month - 1]; - } else { - month = Date::MONTH_PER_DAY_OF_YEAR[day]; - day -= Date::CUMULATIVE_DAYS[month - 1]; +void Date::ExtractYearOffset(int32_t &n, int32_t &year, int32_t &year_offset) { + year = CivilFromDays(n).year; + // leap years repeat every 400 years: normalize n to the years [1970, 2370) + auto era = (year - Date::EPOCH_YEAR) / Date::YEAR_INTERVAL; + year_offset = (year - Date::EPOCH_YEAR) % Date::YEAR_INTERVAL; + if (year_offset < 0) { + era--; + year_offset += Date::YEAR_INTERVAL; } - day++; - D_ASSERT(day > 0 && day <= (is_leap_year ? Date::LEAP_DAYS[month] : Date::NORMAL_DAYS[month])); + n = static_cast(int64_t(n) - int64_t(era) * Date::DAYS_PER_YEAR_INTERVAL); + D_ASSERT(n >= Date::CUMULATIVE_YEAR_DAYS[year_offset] && n < Date::CUMULATIVE_YEAR_DAYS[year_offset + 1]); +} + +void Date::Convert(date_t d, int32_t &year, int32_t &month, int32_t &day) { + auto result = CivilFromDays(d.days); + year = result.year; + month = result.month; + day = result.day; D_ASSERT(month > 0 && month <= 12); + D_ASSERT(day > 0 && day <= (Date::IsLeapYear(year) ? Date::LEAP_DAYS[month] : Date::NORMAL_DAYS[month])); } bool Date::TryFromDate(int32_t year, int32_t month, int32_t day, date_t &result) { @@ -466,21 +492,15 @@ int64_t Date::EpochMilliseconds(date_t date) { } int32_t Date::ExtractYear(date_t d) { - int32_t year, year_offset; - Date::ExtractYearOffset(d.days, year, year_offset); - return year; + return CivilFromDays(d.days).year; } int32_t Date::ExtractMonth(date_t date) { - int32_t out_year, out_month, out_day; - Date::Convert(date, out_year, out_month, out_day); - return out_month; + return CivilFromDays(date.days).month; } int32_t Date::ExtractDay(date_t date) { - int32_t out_year, out_month, out_day; - Date::Convert(date, out_year, out_month, out_day); - return out_day; + return CivilFromDays(date.days).day; } int32_t Date::ExtractDayOfTheYear(date_t date) { diff --git a/src/duckdb/src/common/types/geometry.cpp b/src/duckdb/src/common/types/geometry.cpp index 2e7539f77..2a58fd46c 100644 --- a/src/duckdb/src/common/types/geometry.cpp +++ b/src/duckdb/src/common/types/geometry.cpp @@ -1308,9 +1308,8 @@ string_t Geometry::ToString(StringHeap &heap, const string_t &geom) { return heap.AddString(buffer.data(), buffer.size()); } -pair Geometry::GetType(const string_t &wkb) { - BlobReader reader(wkb.GetData(), static_cast(wkb.GetSize())); - +//! Read and validate the byte order and type of a WKB geometry +static pair ReadGeometryHeader(BlobReader &reader) { // Read the byte order (should always be 1 for little-endian) const auto byte_order = reader.Read(); if (byte_order != 1) { @@ -1334,125 +1333,794 @@ pair Geometry::GetType(const string_t &wkb) { return {geom_type, vert_type}; } -template -static uint32_t ParseVerticesInternal(BlobReader &reader, GeometryExtent &extent, uint32_t vert_count, bool check_nan) { - uint32_t count = 0; +pair Geometry::GetType(const string_t &wkb) { + BlobReader reader(wkb.GetData(), static_cast(wkb.GetSize())); + return ReadGeometryHeader(reader); +} - // Issue a single .Reserve() for all vertices, to minimize bounds checking overhead - const auto ptr = const_data_ptr_cast(reader.Reserve(vert_count * sizeof(VERTEX_TYPE))); -#if DUCKDB_IS_BIG_ENDIAN - double be_buffer[sizeof(VERTEX_TYPE)]; - auto be_ptr = reinterpret_cast(be_buffer); -#endif - for (uint32_t vert_idx = 0; vert_idx < vert_count; vert_idx++) { +//---------------------------------------------------------------------------------------------------------------------- +// Geometry visitor +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +//! Receives the parts and vertices of a WKB geometry from VisitGeometry. Each part is entered and left with its index +//! within its parent (0 for the root) and its number of children: vertices, rings or parts. An empty point has no +//! vertex. Implementations should be final and passed to VisitGeometry as their own type, so that the calls are direct +//! and can be inlined. +class GeometryVisitor { +public: + virtual ~GeometryVisitor() = default; + + virtual void EnterPoint(idx_t part_idx, idx_t vert_count) { + } + virtual void LeavePoint(idx_t part_idx, idx_t vert_count) { + } + virtual void EnterLineString(idx_t part_idx, idx_t vert_count) { + } + virtual void LeaveLineString(idx_t part_idx, idx_t vert_count) { + } + virtual void EnterPolygon(idx_t part_idx, idx_t ring_count) { + } + virtual void LeavePolygon(idx_t part_idx, idx_t ring_count) { + } + virtual void EnterPolygonRing(idx_t ring_idx, idx_t vert_count) { + } + virtual void LeavePolygonRing(idx_t ring_idx, idx_t vert_count) { + } + virtual void EnterMultiPoint(idx_t part_idx, idx_t part_count) { + } + virtual void LeaveMultiPoint(idx_t part_idx, idx_t part_count) { + } + virtual void EnterMultiLineString(idx_t part_idx, idx_t part_count) { + } + virtual void LeaveMultiLineString(idx_t part_idx, idx_t part_count) { + } + virtual void EnterMultiPolygon(idx_t part_idx, idx_t part_count) { + } + virtual void LeaveMultiPolygon(idx_t part_idx, idx_t part_count) { + } + virtual void EnterGeometryCollection(idx_t part_idx, idx_t part_count) { + } + virtual void LeaveGeometryCollection(idx_t part_idx, idx_t part_count) { + } + + virtual void OnVertexXY(const VertexXY &vertex) = 0; + virtual void OnVertexXYZ(const VertexXYZ &vertex) = 0; + virtual void OnVertexXYM(const VertexXYM &vertex) = 0; + virtual void OnVertexXYZM(const VertexXYZM &vertex) = 0; +}; + +//! Walks the parts of a WKB geometry whose vertices are all of type VERTEX_TYPE +template +class GeometryWalker { +public: + //! Visit a geometry of the given type, whose header has already been read + static void Visit(BlobReader &reader, GeometryType type, idx_t part_idx, VISITOR &visitor, idx_t depth) { + switch (type) { + case GeometryType::POINT: + VisitPoint(reader, part_idx, visitor); + break; + case GeometryType::LINESTRING: + VisitLineString(reader, part_idx, visitor); + break; + case GeometryType::POLYGON: + VisitPolygon(reader, part_idx, visitor); + break; + case GeometryType::MULTIPOINT: { + const auto part_count = reader.Read(); + visitor.EnterMultiPoint(part_idx, part_count); + for (uint32_t i = 0; i < part_count; i++) { + ReadPartHeader(reader, GeometryType::POINT); + VisitPoint(reader, i, visitor); + } + visitor.LeaveMultiPoint(part_idx, part_count); + } break; + case GeometryType::MULTILINESTRING: { + const auto part_count = reader.Read(); + visitor.EnterMultiLineString(part_idx, part_count); + for (uint32_t i = 0; i < part_count; i++) { + ReadPartHeader(reader, GeometryType::LINESTRING); + VisitLineString(reader, i, visitor); + } + visitor.LeaveMultiLineString(part_idx, part_count); + } break; + case GeometryType::MULTIPOLYGON: { + const auto part_count = reader.Read(); + visitor.EnterMultiPolygon(part_idx, part_count); + for (uint32_t i = 0; i < part_count; i++) { + ReadPartHeader(reader, GeometryType::POLYGON); + VisitPolygon(reader, i, visitor); + } + visitor.LeaveMultiPolygon(part_idx, part_count); + } break; + case GeometryType::GEOMETRYCOLLECTION: { + if (depth >= Geometry::MAX_RECURSION_DEPTH) { + throw InvalidInputException("Geometry exceeds maximum recursion depth of %d", + Geometry::MAX_RECURSION_DEPTH); + } + const auto part_count = reader.Read(); + visitor.EnterGeometryCollection(part_idx, part_count); + for (uint32_t i = 0; i < part_count; i++) { + const auto part_type = ReadPartHeader(reader); + Visit(reader, part_type, i, visitor, depth + 1); + } + visitor.LeaveGeometryCollection(part_idx, part_count); + } break; + default: + throw InvalidInputException("Unsupported geometry type %d in WKB", static_cast(type)); + } + } + +private: + static VERTEX_TYPE LoadVertex(const_data_ptr_t ptr) { #if DUCKDB_IS_BIG_ENDIAN - auto vert_ofs = vert_idx * sizeof(VERTEX_TYPE); - for (idx_t i = 0; i < sizeof(VERTEX_TYPE) / sizeof(double); ++i) { - be_buffer[i] = LoadLE(ptr + vert_ofs + i * sizeof(double)); + double be_buffer[VERTEX_TYPE::WIDTH]; + for (idx_t i = 0; i < VERTEX_TYPE::WIDTH; i++) { + be_buffer[i] = LoadLE(ptr + i * sizeof(double)); } - VERTEX_TYPE vertex = Load(be_ptr); + return Load(reinterpret_cast(be_buffer)); #else - VERTEX_TYPE vertex = Load(ptr + vert_idx * sizeof(VERTEX_TYPE)); + return Load(ptr); #endif - if (check_nan && vertex.AllNan()) { - continue; + } + + static void OnVertex(VISITOR &visitor, const VertexXY &vertex) { + visitor.OnVertexXY(vertex); + } + static void OnVertex(VISITOR &visitor, const VertexXYZ &vertex) { + visitor.OnVertexXYZ(vertex); + } + static void OnVertex(VISITOR &visitor, const VertexXYM &vertex) { + visitor.OnVertexXYM(vertex); + } + static void OnVertex(VISITOR &visitor, const VertexXYZM &vertex) { + visitor.OnVertexXYZM(vertex); + } + + static void VisitVertices(BlobReader &reader, uint32_t vert_count, VISITOR &visitor) { + // Issue a single .Reserve() for all vertices, to minimize bounds checking overhead + const auto ptr = const_data_ptr_cast(reader.Reserve(vert_count * sizeof(VERTEX_TYPE))); + for (uint32_t vert_idx = 0; vert_idx < vert_count; vert_idx++) { + OnVertex(visitor, LoadVertex(ptr + vert_idx * sizeof(VERTEX_TYPE))); } + } - extent.Extend(vertex); - count++; + static void VisitPoint(BlobReader &reader, idx_t part_idx, VISITOR &visitor) { + const auto vertex = LoadVertex(const_data_ptr_cast(reader.Reserve(sizeof(VERTEX_TYPE)))); + // An empty point has all-NaN ordinates + const idx_t vert_count = vertex.AllNan() ? 0 : 1; + visitor.EnterPoint(part_idx, vert_count); + if (vert_count != 0) { + OnVertex(visitor, vertex); + } + visitor.LeavePoint(part_idx, vert_count); } - return count; -} -static uint32_t ParseVertices(BlobReader &reader, GeometryExtent &extent, uint32_t vert_count, VertexType type, - bool check_nan) { - switch (type) { + static void VisitLineString(BlobReader &reader, idx_t part_idx, VISITOR &visitor) { + const auto vert_count = reader.Read(); + visitor.EnterLineString(part_idx, vert_count); + VisitVertices(reader, vert_count, visitor); + visitor.LeaveLineString(part_idx, vert_count); + } + + static void VisitPolygon(BlobReader &reader, idx_t part_idx, VISITOR &visitor) { + const auto ring_count = reader.Read(); + visitor.EnterPolygon(part_idx, ring_count); + for (uint32_t ring_idx = 0; ring_idx < ring_count; ring_idx++) { + const auto vert_count = reader.Read(); + visitor.EnterPolygonRing(ring_idx, vert_count); + VisitVertices(reader, vert_count, visitor); + visitor.LeavePolygonRing(ring_idx, vert_count); + } + visitor.LeavePolygon(part_idx, ring_count); + } + + //! Read the header of a collection part, which must have the same vertex type as the root + static GeometryType ReadPartHeader(BlobReader &reader) { + const auto header = ReadGeometryHeader(reader); + if (header.second != VERTEX_TYPE::TYPE) { + throw InvalidInputException("Geometry has inconsistent Z/M dimensions, starting at position %zu", + reader.GetPosition()); + } + return header.first; + } + + static void ReadPartHeader(BlobReader &reader, GeometryType expected_type) { + const auto type = ReadPartHeader(reader); + if (type != expected_type) { + throw InvalidInputException("Unexpected geometry type %d in a collection of type %d at position %zu", + static_cast(type), static_cast(expected_type) + 3, + reader.GetPosition()); + } + } +}; + +//! Walk a WKB geometry, calling the visitor for each of its parts and vertices +template +void VisitGeometry(const string_t &wkb, VISITOR &visitor) { + BlobReader reader(wkb.GetData(), static_cast(wkb.GetSize())); + const auto header = ReadGeometryHeader(reader); + switch (header.second) { case VertexType::XY: - return ParseVerticesInternal(reader, extent, vert_count, check_nan); + GeometryWalker::Visit(reader, header.first, 0, visitor, 0); + break; case VertexType::XYZ: - return ParseVerticesInternal(reader, extent, vert_count, check_nan); + GeometryWalker::Visit(reader, header.first, 0, visitor, 0); + break; case VertexType::XYM: - return ParseVerticesInternal(reader, extent, vert_count, check_nan); + GeometryWalker::Visit(reader, header.first, 0, visitor, 0); + break; case VertexType::XYZM: - return ParseVerticesInternal(reader, extent, vert_count, check_nan); + GeometryWalker::Visit(reader, header.first, 0, visitor, 0); + break; default: - throw InvalidInputException("Unsupported vertex type %d in WKB", static_cast(type)); + throw InvalidInputException("Unsupported vertex type %d in WKB", static_cast(header.second)); + } + if (!reader.IsAtEnd()) { + throw InvalidInputException("Unexpected trailing data at position %zu", reader.GetPosition()); } } -uint32_t Geometry::GetExtent(const string_t &wkb, GeometryExtent &extent) { - bool has_any_empty = false; - return GetExtent(wkb, extent, has_any_empty); -} +} // namespace -uint32_t Geometry::GetExtent(const string_t &wkb, GeometryExtent &extent, bool &has_any_empty) { - BlobReader reader(wkb.GetData(), static_cast(wkb.GetSize())); +//---------------------------------------------------------------------------------------------------------------------- +// Geodetic (GEOGRAPHY) coverage extents +//---------------------------------------------------------------------------------------------------------------------- +// GEOGRAPHY edges are geodesics (great-circle arcs), which can bulge poleward past their endpoints, and polygon rings +// can enclose a pole. The geodetic extent therefore bounds what the geometry covers, not just its coordinates. +// (i.e., we cant just accumulate the min/max of all the coordinates individually) +// +// For example, the edge from A (60W, 45N) to B (60E, 45N), drawn in lon/lat: +// +// 63N _.--''''''--._ +// _.-'' ''-._ geodesic: great-circle arc, bulges poleward +// _.-' '-._ +// 45N A*--------------------------------*B planar: straight line in lon/lat +// 60W 0 60E +// +// The geodesic reaches ~63.4N at longitude 0, so a latitude range over the endpoints alone (45N) would miss it. +// Longitude is monotone along any edge spanning less than half a circle, so an edge covers the short arc between its +// endpoints' longitudes. The vertices alone may not: LINESTRING(0 10, 170 10, -170 10, 0 10) has vertices within the +// arc from 0 east to -170, but its last edge runs from -170 east to 0. +// +// Here's a mini-glossary to help understanding the following code: +// - Longitude / Latitude: degrees east in [-180, 180] and degrees north in [-90, 90]. +// - Great circle: a circle on the sphere whose center is the sphere's center, e.g. the equator. +// - Geodesic: the shortest path between two points on the sphere, an arc of the great circle through both. +// - Meridian: a line of constant longitude, running from pole to pole. +// - Antipodal: diametrically opposite, e.g. the two poles. Every great circle through one point also passes through +// its antipode, so the geodesic between them is ambiguous. +// - Apex: the northernmost or southernmost point of a great circle. +// - Bulge: the part of an edge that reaches beyond the latitudes of its endpoints, towards a pole. +// - Winding: the total signed longitude change around a ring, about +-360 degrees if the ring encircles a pole. +// - Shell / hole: the first ring of a polygon and the remaining ones. The interior lies to the left of the direction +// of travel along the ring. - uint32_t vertex_count = 0; +namespace { - while (!reader.IsAtEnd()) { - const auto byte_order = reader.Read(); - if (byte_order != 1) { - throw InvalidInputException("Unsupported byte order %d in WKB", byte_order); +constexpr double DEG_TO_RAD = 0.017453292519943295; + +//! Outward padding for computed apex latitudes, in degrees +constexpr double APEX_EPSILON = 1e-9; + +//! Edges spanning within this many degrees of half a circle of longitude are ambiguous +constexpr double HALF_CIRCLE_EPSILON = 1e-9; + +//! Tolerance for dimensionless quantities on the unit sphere (sines and cosines) +constexpr double UNIT_EPSILON = 1e-14; + +struct Vec2 { + double x; + double y; + + double Cross(const Vec2 &o) const { + return x * o.y - y * o.x; + } +}; + +struct Vec3 { + double x; + double y; + double z; + + Vec3 Cross(const Vec3 &o) const { + return {y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x}; + } + double Dot(const Vec3 &o) const { + return x * o.x + y * o.y + z * o.z; + } +}; + +//! A point on the sphere, in degrees +struct LonLat { + double lon; + double lat; + + //! Signed eastward longitude difference in degrees, in [-180, 180] + static double LonDelta(double from, double to) { + double d = to - from; + if (d > 180.0) { + d -= 360.0; + } else if (d < -180.0) { + d += 360.0; } - const auto meta = reader.Read(); - const auto type_id = (meta & 0x0000FFFF) % 1000; - const auto flag_id = (meta & 0x0000FFFF) / 1000; - if (type_id < 1 || type_id > 7) { - throw InvalidInputException("Unsupported geometry type %d in WKB", type_id); + return d; + } + + Vec3 ToCartesian() const { + const double phi = lat * DEG_TO_RAD; + const double lam = lon * DEG_TO_RAD; + return {std::cos(phi) * std::cos(lam), std::cos(phi) * std::sin(lam), std::sin(phi)}; + } + + //! Initial (east, north) tangent of the geodesic from this point towards `to`, unnormalized + Vec2 DirectionTo(const LonLat &to) const { + const double phi_from = lat * DEG_TO_RAD; + const double phi_to = to.lat * DEG_TO_RAD; + const double dl = LonDelta(lon, to.lon) * DEG_TO_RAD; + return {std::sin(dl) * std::cos(phi_to), + std::cos(phi_from) * std::sin(phi_to) - std::sin(phi_from) * std::cos(phi_to) * std::cos(dl)}; + } +}; + +//! A great-circle arc from p1 to p2, spanning less than half a circle +struct GeodesicEdge { + LonLat p1; + LonLat p2; + + //! Signed eastward longitude change from p1 to p2, in degrees, in [-180, 180] + double GetLonDelta() const { + return LonLat::LonDelta(p1.lon, p2.lon); + } + + //! Whether `lon` lies within the longitudes the edge passes through + bool ContainsLon(double lon) const { + const double delta = GetLonDelta(); + const double offset = LonLat::LonDelta(p1.lon, lon); + return delta > 0 ? (offset >= 0 && offset <= delta) : (offset <= 0 && offset >= delta); + } + + //! Latitude range reached by the edge, including any poleward bulge past its endpoints. + //! Returns false if the edge is ambiguous (endpoints nearly antipodal). + bool TryGetLatRange(double &min_lat, double &max_lat) const { + min_lat = MinValue(p1.lat, p2.lat); + max_lat = MaxValue(p1.lat, p2.lat); + + // The endpoints only bound a planar edge. + // On the sphere it can bulge poleward, which is what the rest of this function computes. + + const double delta = GetLonDelta(); + + if (!(std::fabs(delta) < 180.0 - HALF_CIRCLE_EPSILON)) { + // Spans (nearly) half a circle of longitude, or NaN + return false; } - if (flag_id > 3) { - throw InvalidInputException("Unsupported geometry flag %d in WKB", flag_id); + if (delta == 0.0) { + // This is a meridian arc, i.e. same longitude, i.e. no bulge + return true; } - const auto geom_type = static_cast(type_id); - const auto vert_type = static_cast(flag_id); - switch (geom_type) { - case GeometryType::POINT: { - const auto parsed_count = ParseVertices(reader, extent, 1, vert_type, true); - if (parsed_count == 0) { - has_any_empty = true; - continue; + const Vec3 c1 = p1.ToCartesian(); + const Vec3 c2 = p2.ToCartesian(); + const Vec3 n = c1.Cross(c2); + const double nxy = std::hypot(n.x, n.y); + const double nlen = std::hypot(nxy, n.z); + + if (!(nlen > UNIT_EPSILON)) { + // Coincident endpoints (e.g. a pole under two longitudes) are fine, antipodal ones are ambiguous + return c1.Dot(c2) > 0; + } + if (std::fabs(n.z) <= UNIT_EPSILON * nlen) { + // The great circle runs (nearly) through the poles, where all of its longitude change happens, so the edge + // crosses a pole iff it spans about half a circle. The shorter arc crosses the pole nearer to the + // endpoints. + if (std::fabs(delta) > 90.0) { + const double lat_sum = p1.lat + p2.lat; + if (lat_sum > 0) { + max_lat = 90.0; + } else if (lat_sum < 0) { + min_lat = -90.0; + } else { + return false; + } } - vertex_count += parsed_count; - } break; - case GeometryType::LINESTRING: { - const auto vert_count = reader.Read(); - if (vert_count == 0) { - has_any_empty = true; - continue; + return true; + } + // Northernmost point of the great circle, atan2 stays well-conditioned near the pole, unlike asin(nxy / nlen) + const double apex_lat = std::atan2(nxy, std::fabs(n.z)) / DEG_TO_RAD; + const double apex_lon = std::atan2(-n.y * n.z, -n.x * n.z) / DEG_TO_RAD; + + if (ContainsLon(apex_lon) && apex_lat > max_lat) { + max_lat = apex_lat; + } + + // The southernmost point is antipodal to the northernmost + const double south_apex_lon = apex_lon > 0 ? apex_lon - 180.0 : apex_lon + 180.0; + + if (ContainsLon(south_apex_lon) && -apex_lat < min_lat) { + min_lat = -apex_lat; + } + return true; + } +}; + +//! Side of the boundary that a ring's interior lies on at its highest point. SOUTH is the bounded, pole-free side. +enum class InteriorSide : int8_t { UNKNOWN, SOUTH, NORTH }; + +//! Coverage state of a linestring or polygon ring, accumulated vertex by vertex +class GeodeticRingState { +public: + //! Add the next vertex, extending the extent with the edge from the previous one + void AddVertex(GeometryExtent &extent, const LonLat &vertex) { + if (vertex_count == 0) { + first_vertex = vertex; + } else { + AddEdge(extent, last_vertex, vertex); + if (vertex_count == 1) { + second_vertex = vertex; } - vertex_count += ParseVertices(reader, extent, vert_count, vert_type, false); - } break; - case GeometryType::POLYGON: { - const auto ring_count = reader.Read(); - if (ring_count == 0) { - has_any_empty = true; - continue; + } + last_vertex = vertex; + vertex_count++; + } + + //! Close the ring, adding the closing edge unless the last vertex already repeats the first (+180 and -180 are the + //! same longitude). The closing vertex's successor is the second vertex. + void CloseRing(GeometryExtent &extent) { + if (vertex_count < 2) { + return; + } + if (LonLat::LonDelta(last_vertex.lon, first_vertex.lon) != 0.0 || last_vertex.lat != first_vertex.lat) { + AddEdge(extent, last_vertex, first_vertex); + } + ResolvePending(second_vertex); + } + + //! Apply the ring state to the extent. A shell's interior lies on the left of the travel direction (as in S2), + //! with the orientation read off at the ring's highest point, since a planar shoelace fails when edges bulge. + //! Holes never extend the interior, so only their edges contribute. + void Finish(GeometryExtent &extent, bool is_shell) const { + if (ambiguous) { + ExtendFullGlobe(extent); + return; + } + if (!is_shell) { + return; + } + // The winding thresholds lie halfway between whole turns + if (std::fabs(winding) >= 540.0) { + // Wound around the globe more than once: not a simple ring + ExtendFullGlobe(extent); + return; + } + if (std::fabs(winding) >= 180.0) { + // Wound around the globe once: east encloses the north pole, west the south pole + extent.x_min = -180.0; + extent.x_max = 180.0; + if (winding > 0) { + extent.y_max = MaxValue(extent.y_max, 90.0); + } else { + extent.y_min = MinValue(extent.y_min, -90.0); } - for (uint32_t ring_idx = 0; ring_idx < ring_count; ring_idx++) { - const auto vert_count = reader.Read(); - if (vert_count == 0) { - has_any_empty = true; - continue; - } - vertex_count += ParseVertices(reader, extent, vert_count, vert_type, false); + return; + } + if (top_conflict || top_side != InteriorSide::SOUTH || top_lat >= 90.0) { + // Clockwise (the interior is the complement), or the orientation is undefined (cusp, degenerate, on a pole) + ExtendFullGlobe(extent); + } + // Otherwise counterclockwise: the interior lies within the boundary's extent + } + +private: + //! Add the edge prev -> cur, extending the extent with its longitude and latitude ranges + void AddEdge(GeometryExtent &extent, const LonLat &prev, const LonLat &cur) { + const GeodesicEdge edge = {prev, cur}; + double min_lat = 0; + double max_lat = 0; + if (!edge.TryGetLatRange(min_lat, max_lat)) { + ambiguous = true; + return; + } + const double delta = edge.GetLonDelta(); + winding += delta; + ResolvePending(cur); + if (delta > 0) { + extent.ExtendXArc(prev.lon, cur.lon); + } else if (delta < 0) { + extent.ExtendXArc(cur.lon, prev.lon); + } + // The endpoints are already in the extent, and computed apexes beyond them are padded outward + if (min_lat < MinValue(prev.lat, cur.lat)) { + extent.y_min = MinValue(extent.y_min, MaxValue(min_lat - APEX_EPSILON, -90.0)); + } + if (max_lat > MaxValue(prev.lat, cur.lat)) { + extent.y_max = MaxValue(extent.y_max, MinValue(max_lat + APEX_EPSILON, 90.0)); + // A smooth highest point: traveling east puts the interior (on the left) north of it + SubmitTop(max_lat, delta > 0 ? InteriorSide::NORTH : InteriorSide::SOUTH); + } + if (cur.lat >= top_lat) { + // A vertex's interior side needs the next vertex, so it is kept pending until the following edge + pending = true; + pending_vertex = cur; + pending_prev = prev; + } + } + + //! Submit the pending vertex's interior side, now that its successor is known + void ResolvePending(const LonLat &next) { + if (!pending) { + return; + } + const auto &v = pending_vertex; + const Vec2 to_next = v.DirectionTo(next); + const Vec2 to_prev = v.DirectionTo(pending_prev); + const bool next_descends = to_next.y < -UNIT_EPSILON; + const bool prev_descends = to_prev.y < -UNIT_EPSILON; + if (next_descends && prev_descends) { + // A corner: traversed prev -> v -> next with both edges leaving v heading south, the interior (on the left) + // is pole-free iff the turn at v is a left turn + const double cross = to_next.Cross(to_prev); + SubmitTop(v.lat, + cross > 0 ? InteriorSide::SOUTH : (cross < 0 ? InteriorSide::NORTH : InteriorSide::UNKNOWN)); + } else { + // An edge that does not descend from v peaks at or past v, possibly higher by less than the rounding of its + // apex. The boundary is smooth there, so as at an apex, traveling east puts the interior north of it. + if (!next_descends) { + SubmitTop(v.lat, SideOfTravel(to_next.x)); } - } break; - case GeometryType::MULTIPOINT: - case GeometryType::MULTILINESTRING: - case GeometryType::MULTIPOLYGON: - case GeometryType::GEOMETRYCOLLECTION: { - const auto part_count = reader.Read(); - if (part_count == 0) { - has_any_empty = true; + if (!prev_descends) { + SubmitTop(v.lat, SideOfTravel(-to_prev.x)); } - } break; - default: - throw InvalidInputException("Unsupported geometry type %d in WKB", static_cast(geom_type)); } + pending = false; + } + + //! Interior side at a smooth boundary point, given the eastward component of the travel direction there + static InteriorSide SideOfTravel(double east) { + if (east > UNIT_EPSILON) { + return InteriorSide::NORTH; + } + if (east < -UNIT_EPSILON) { + return InteriorSide::SOUTH; + } + return InteriorSide::UNKNOWN; + } + + //! Record the interior side at a boundary point at `lat`, if it is (one of) the highest + void SubmitTop(double lat, InteriorSide side) { + if (lat > top_lat) { + top_lat = lat; + top_side = side; + top_conflict = side == InteriorSide::UNKNOWN; + } else if (lat == top_lat && side != top_side) { + top_conflict = true; + } + } + + //! Extend the extent to cover the entire globe + static void ExtendFullGlobe(GeometryExtent &extent) { + extent.x_min = -180.0; + extent.x_max = 180.0; + extent.y_min = MinValue(extent.y_min, -90.0); + extent.y_max = MaxValue(extent.y_max, 90.0); + } + +private: + //! Number of vertices added so far, and the first, second and last of them + idx_t vertex_count = 0; + LonLat first_vertex = {0, 0}; + LonLat second_vertex = {0, 0}; + LonLat last_vertex = {0, 0}; + //! Accumulated signed longitude change in degrees, ~+-360 for a ring that winds around a pole + double winding = 0; + //! Highest latitude reached by the boundary (vertices and edge apexes) + double top_lat = -std::numeric_limits::infinity(); + //! Side of the boundary the interior lies on at top_lat + InteriorSide top_side = InteriorSide::UNKNOWN; + //! The boundary reaches top_lat with conflicting interior sides (a cusp or degenerate ring) + bool top_conflict = false; + //! A highest vertex whose interior side awaits the next vertex + bool pending = false; + LonLat pending_vertex = {0, 0}; + LonLat pending_prev = {0, 0}; + //! Saw a (nearly) antipodal edge, whose geodesic is ambiguous and may pass arbitrarily close to a pole + bool ambiguous = false; +}; + +} // namespace + +//---------------------------------------------------------------------------------------------------------------------- +// Extents +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +//! Extends an extent with the vertices of a geometry, counting them and whether any part is empty +class ExtentVisitor : public GeometryVisitor { +public: + explicit ExtentVisitor(GeometryExtent &extent) : extent(extent) { + } + + uint32_t GetVertexCount() const { + return vertex_count; + } + bool HasAnyEmpty() const { + return has_any_empty; + } + + void EnterPoint(idx_t part_idx, idx_t vert_count) override { + MarkIfEmpty(vert_count); + } + void EnterLineString(idx_t part_idx, idx_t vert_count) override { + MarkIfEmpty(vert_count); + } + void EnterPolygon(idx_t part_idx, idx_t ring_count) override { + MarkIfEmpty(ring_count); + } + void EnterPolygonRing(idx_t ring_idx, idx_t vert_count) override { + MarkIfEmpty(vert_count); + } + void EnterMultiPoint(idx_t part_idx, idx_t part_count) override { + MarkIfEmpty(part_count); + } + void EnterMultiLineString(idx_t part_idx, idx_t part_count) override { + MarkIfEmpty(part_count); + } + void EnterMultiPolygon(idx_t part_idx, idx_t part_count) override { + MarkIfEmpty(part_count); + } + void EnterGeometryCollection(idx_t part_idx, idx_t part_count) override { + MarkIfEmpty(part_count); + } + +protected: + void MarkIfEmpty(idx_t child_count) { + if (child_count == 0) { + has_any_empty = true; + } + } + +protected: + GeometryExtent &extent; + uint32_t vertex_count = 0; + bool has_any_empty = false; +}; + +//! Extends the extent with every vertex +class PlanarExtentVisitor final : public ExtentVisitor { +public: + explicit PlanarExtentVisitor(GeometryExtent &extent) : ExtentVisitor(extent) { + } + + void OnVertexXY(const VertexXY &vertex) override { + AddVertex(vertex); + } + void OnVertexXYZ(const VertexXYZ &vertex) override { + AddVertex(vertex); + } + void OnVertexXYM(const VertexXYM &vertex) override { + AddVertex(vertex); + } + void OnVertexXYZM(const VertexXYZM &vertex) override { + AddVertex(vertex); + } + +private: + template + void AddVertex(const VERTEX_TYPE &vertex) { + extent.Extend(vertex, GeometryModel::PLANAR); + vertex_count++; + } +}; + +//! Extends the extent with the coverage of every vertex, geodesic edge, and polygon interior +class GeodeticExtentVisitor final : public ExtentVisitor { +public: + explicit GeodeticExtentVisitor(GeometryExtent &extent) : ExtentVisitor(extent) { + } + + void EnterLineString(idx_t part_idx, idx_t vert_count) override { + ExtentVisitor::EnterLineString(part_idx, vert_count); + if (vert_count > 0) { + ring = GeodeticRingState(); + in_ring = true; + } + } + void LeaveLineString(idx_t part_idx, idx_t vert_count) override { + if (in_ring) { + ring.Finish(extent, false); + in_ring = false; + } + } + void EnterPolygon(idx_t part_idx, idx_t ring_count) override { + ExtentVisitor::EnterPolygon(part_idx, ring_count); + is_shell = true; + } + void EnterPolygonRing(idx_t ring_idx, idx_t vert_count) override { + ExtentVisitor::EnterPolygonRing(ring_idx, vert_count); + if (vert_count > 0) { + ring = GeodeticRingState(); + in_ring = true; + } + } + void LeavePolygonRing(idx_t ring_idx, idx_t vert_count) override { + if (in_ring) { + ring.CloseRing(extent); + ring.Finish(extent, is_shell); + in_ring = false; + // The first non-empty ring is the shell, the rest are holes + is_shell = false; + } + } + + void OnVertexXY(const VertexXY &vertex) override { + AddVertex(vertex); + } + void OnVertexXYZ(const VertexXYZ &vertex) override { + AddVertex(vertex); + } + void OnVertexXYM(const VertexXYM &vertex) override { + AddVertex(vertex); + } + void OnVertexXYZM(const VertexXYZM &vertex) override { + AddVertex(vertex); + } + +private: + template + void AddVertex(const VERTEX_TYPE &vertex) { + extent.Extend(vertex, GeometryModel::GEODETIC); + vertex_count++; + if (in_ring) { + ring.AddVertex(extent, {vertex.x, vertex.y}); + } + } + +private: + //! State of the current linestring or polygon ring + GeodeticRingState ring; + bool in_ring = false; + //! Whether the next non-empty ring of the current polygon is its shell + bool is_shell = false; +}; + +template +uint32_t GetExtentInternal(const string_t &wkb, GeometryExtent &extent, bool &has_any_empty) { + VISITOR visitor(extent); + VisitGeometry(wkb, visitor); + if (visitor.HasAnyEmpty()) { + has_any_empty = true; + } + return visitor.GetVertexCount(); +} + +} // namespace + +uint32_t Geometry::GetExtent(const string_t &wkb, GeometryExtent &extent, GeometryModel model) { + bool has_any_empty = false; + return GetExtent(wkb, extent, has_any_empty, model); +} + +uint32_t Geometry::GetExtent(const string_t &wkb, GeometryExtent &extent, bool &has_any_empty, GeometryModel model) { + if (model == GeometryModel::GEODETIC) { + return GetExtentInternal(wkb, extent, has_any_empty); + } + return GetExtentInternal(wkb, extent, has_any_empty); +} + +bool Geometry::IsValidGeography(const string_t &wkb) { + // Coordinates must lie within X in [-180, 180] and Y in [-90, 90], so the planar extent suffices + auto extent = GeometryExtent::Empty(); + const auto vertex_count = GetExtent(wkb, extent, GeometryModel::PLANAR); + if (vertex_count == 0) { + return true; + } + // A non-finite X or Y (e.g. NaN) leaves the axis unset, and the geodetic math requires finite values + if (!extent.HasX() || !extent.HasY()) { + return false; } - return vertex_count; + return extent.x_min >= -180.0 && extent.x_max <= 180.0 && extent.y_min >= -90.0 && extent.y_max <= 90.0; } //---------------------------------------------------------------------------------------------------------------------- diff --git a/src/duckdb/src/common/types/hugeint.cpp b/src/duckdb/src/common/types/hugeint.cpp index 16024a0b4..896ce3804 100644 --- a/src/duckdb/src/common/types/hugeint.cpp +++ b/src/duckdb/src/common/types/hugeint.cpp @@ -1,5 +1,6 @@ #include "duckdb/common/types/hugeint.hpp" #include "duckdb/common/types/uhugeint.hpp" +#include "duckdb/common/types/cast_helpers.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/algorithm.hpp" #include "duckdb/common/hugeint.hpp" @@ -125,27 +126,10 @@ hugeint_t Hugeint::DivModPositive(hugeint_t lhs, uint64_t rhs, uint64_t &remaind } string Hugeint::ToString(hugeint_t input) { - uint64_t remainder; - string result; - if (input == NumericLimits::Minimum()) { - return string(Hugeint::HUGEINT_MINIMUM_STRING); - } - bool negative = input.upper < 0; - if (negative) { - NegateInPlace(input); - } - while (true) { - if (!input.lower && !input.upper) { - break; - } - input = Hugeint::DivModPositive(input, 10, remainder); - result = string(1, UnsafeNumericCast('0' + remainder)) + result; // NOLINT - } - if (result.empty()) { - // value is zero - return "0"; - } - return negative ? "-" + result : result; + char buffer[NumericLimits::Digits() + 1]; + auto end = buffer + sizeof(buffer); + auto start = NumericHelper::FormatSigned(input, end); + return string(start, end); } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp b/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp index 8eafa082e..d89d6cf52 100644 --- a/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp +++ b/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp @@ -420,7 +420,7 @@ void PartitionedTupleData::Repartition(ClientContext &context, PartitionedTupleD auto &chunk_state = iterator.GetChunkState(); do { // Check for interrupts with each chunk - context.InterruptCheck(); + context.FastInterruptCheck(); const auto count = iterator.GetCurrentChunkCount(); new_partitioned_data.Append(append_state, chunk_state, count); if (key_tracker) { diff --git a/src/duckdb/src/common/types/row/tuple_data_allocator.cpp b/src/duckdb/src/common/types/row/tuple_data_allocator.cpp index 0c0f820d6..5d703d5a0 100644 --- a/src/duckdb/src/common/types/row/tuple_data_allocator.cpp +++ b/src/duckdb/src/common/types/row/tuple_data_allocator.cpp @@ -137,7 +137,7 @@ idx_t TupleDataAllocator::GetPartitionIndex() const { bool TupleDataAllocator::BuildFastPath(TupleDataSegment &segment, TupleDataPinState &pin_state, TupleDataChunkState &chunk_state, const idx_t append_offset, const idx_t append_count) { - if (!layout.AllConstant() || layout.HasDestructor()) { + if (layout.HasDestructor()) { return false; } @@ -160,9 +160,41 @@ bool TupleDataAllocator::BuildFastPath(TupleDataSegment &segment, TupleDataPinSt return false; } - // We can do the fast path append! - auto row_locations = FlatVector::Writer(chunk_state.row_locations, append_count, append_offset); const auto base_row_ptr = GetRowPointer(pin_state, part) + part.count * row_width; + if (!layout.AllConstant()) { + if (part.total_heap_size == 0) { + return false; + } + + const auto heap_sizes = FlatVector::GetData(chunk_state.heap_sizes); + idx_t added_heap_size = 0; + for (idx_t i = 0; i < append_count; i++) { + added_heap_size += heap_sizes[append_offset + i]; + } + auto &heap_block = heap_blocks[part.heap_block_index]; + if (added_heap_size > heap_block.RemainingCapacity()) { + return false; + } + + const auto base_heap_ptr = GetBaseHeapPointer(pin_state, part); + if (base_heap_ptr != part.base_heap_ptr) { + // Keep relocated heaps in a separate part until the existing rows have been recomputed. + return false; + } + D_ASSERT(part.heap_block_offset + part.total_heap_size == heap_block.size); + auto heap_ptr = base_heap_ptr + heap_block.size; + auto heap_locations = FlatVector::Writer(chunk_state.heap_locations, append_count, append_offset); + for (idx_t i = 0; i < append_count; i++) { + heap_locations.WriteValue(heap_ptr); + heap_ptr += heap_sizes[append_offset + i]; + } + + part.total_heap_size += added_heap_size; + heap_block.size += added_heap_size; + segment.data_size += added_heap_size; + } + + auto row_locations = FlatVector::Writer(chunk_state.row_locations, append_count, append_offset); for (idx_t i = 0; i < append_count; i++) { row_locations.WriteValue(base_row_ptr + i * row_width); } @@ -190,25 +222,21 @@ void TupleDataAllocator::Build(TupleDataSegment &segment, TupleDataPinState &pin chunk_state.chunk_part_indices.clear(); idx_t offset = 0; while (offset != append_count) { + unsafe_arena_ptr new_chunk; if (chunks.empty() || chunks.back()->count == STANDARD_VECTOR_SIZE) { - chunks.push_back(stl_allocator->MakeUnsafePtr(*stl_allocator->Make())); + new_chunk = stl_allocator->MakeUnsafePtr(*stl_allocator->Make()); } - auto &chunk = *chunks.back(); + auto &chunk = new_chunk ? *new_chunk : *chunks.back(); // Build the next part auto next = MinValue(append_count - offset, STANDARD_VECTOR_SIZE - chunk.count); - auto &chunk_part = chunk.AddPart( - segment, BuildChunkPart(segment, pin_state, chunk_state, append_offset + offset, next, chunk)); - next = chunk_part.count; - - segment.count += next; - segment.data_size += chunk_part.count * layout.GetRowWidth(); - if (!layout.AllConstant()) { - segment.data_size += chunk_part.total_heap_size; - } + auto part_ptr = BuildChunkPart(segment, pin_state, chunk_state, append_offset + offset, next, chunk); + next = part_ptr->count; + // Zero the states before adding the chunk and counting the part, as counted rows are destroyed if a pin + // throws if (layout.HasDestructor()) { - const auto base_row_ptr = GetRowPointer(pin_state, chunk_part); + const auto base_row_ptr = GetRowPointer(pin_state, *part_ptr); for (auto &aggr_idx : layout.GetAggregateDestructorIndices()) { const auto aggr_offset = layout.GetOffsets()[layout.ColumnCount() + aggr_idx]; auto &aggr_fun = layout.GetAggregates()[aggr_idx]; @@ -218,6 +246,16 @@ void TupleDataAllocator::Build(TupleDataSegment &segment, TupleDataPinState &pin } } + if (new_chunk) { + chunks.push_back(std::move(new_chunk)); + } + auto &chunk_part = chunk.AddPart(segment, std::move(part_ptr)); + segment.count += next; + segment.data_size += chunk_part.count * layout.GetRowWidth(); + if (!layout.AllConstant()) { + segment.data_size += chunk_part.total_heap_size; + } + offset += next; chunk_state.chunk_part_indices.emplace_back(chunks.size() - 1, chunk.part_ids.End() - 1); } diff --git a/src/duckdb/src/common/types/row/tuple_data_collection.cpp b/src/duckdb/src/common/types/row/tuple_data_collection.cpp index 48d0145e9..622c46472 100644 --- a/src/duckdb/src/common/types/row/tuple_data_collection.cpp +++ b/src/duckdb/src/common/types/row/tuple_data_collection.cpp @@ -498,23 +498,81 @@ void VerifyHeapSizes(const data_ptr_t source_locations[], const idx_t heap_sizes } // LCOV_EXCL_STOP -void TupleDataCollection::CopyRows(TupleDataChunkState &chunk_state, TupleDataChunkState &input, - const SelectionVector &append_sel, const idx_t append_count) const { - const auto source_locations = FlatVector::GetData(input.row_locations); - const auto target_locations = FlatVector::GetData(chunk_state.row_locations); - - // Copy rows - const auto row_width = layout.GetRowWidth(); +template +static void CopyRowBytes(const data_ptr_t source_locations[], const data_ptr_t target_locations[], + const SelectionVector &append_sel, idx_t append_count, idx_t variable_width) { + const auto width = FIXED_WIDTH ? FIXED_WIDTH : variable_width; if (append_sel.IsSet()) { for (idx_t i = 0; i < append_count; i++) { - const auto idx = append_sel[i]; - memcpy(target_locations[i], source_locations[idx], row_width); + memcpy(target_locations[i], source_locations[append_sel[i]], width); } } else { for (idx_t i = 0; i < append_count; i++) { - memcpy(target_locations[i], source_locations[i], row_width); + memcpy(target_locations[i], source_locations[i], width); } } +} + +void TupleDataCollection::CopyRows(TupleDataChunkState &chunk_state, TupleDataChunkState &input, + const SelectionVector &append_sel, const idx_t append_count) const { + const auto source_locations = FlatVector::GetData(input.row_locations); + const auto target_locations = FlatVector::GetData(chunk_state.row_locations); + + // Constant sizes let the compiler inline short row copies. + const auto row_width = layout.GetRowWidth(); + switch (row_width) { + case 8: + CopyRowBytes<8>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 16: + CopyRowBytes<16>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 24: + CopyRowBytes<24>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 32: + CopyRowBytes<32>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 40: + CopyRowBytes<40>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 48: + CopyRowBytes<48>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 56: + CopyRowBytes<56>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 64: + CopyRowBytes<64>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 72: + CopyRowBytes<72>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 80: + CopyRowBytes<80>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 88: + CopyRowBytes<88>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 96: + CopyRowBytes<96>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 104: + CopyRowBytes<104>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 112: + CopyRowBytes<112>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 120: + CopyRowBytes<120>(source_locations, target_locations, append_sel, append_count, row_width); + break; + case 128: + CopyRowBytes<128>(source_locations, target_locations, append_sel, append_count, row_width); + break; + default: + CopyRowBytes<0>(source_locations, target_locations, append_sel, append_count, row_width); + break; + } // Copy heap if we need to if (!layout.AllConstant()) { @@ -611,6 +669,8 @@ void TupleDataCollection::Combine(unique_ptr other) { } void TupleDataCollection::Reset() { + static constexpr idx_t PARALLEL_RESET_THRESHOLD = 512; + static constexpr idx_t MAX_RESET_TASKS = 8; count = 0; data_size = 0; // Find the first non-null segment. @@ -629,6 +689,12 @@ void TupleDataCollection::Reset() { if (live_idx > 0) { segments[0] = std::move(segments[live_idx]); } + if (segments.size() > PARALLEL_RESET_THRESHOLD && scheduler.NumberOfThreads() > 1) { + // Keep the first segment for reuse, and join before resetting its shared allocator. + const auto task_count = MinValue(MAX_RESET_TASKS, scheduler.NumberOfThreads()); + ParallelDestroyTask::Schedule(scheduler, segments.begin() + 1, segments.end(), + task_count); + } segments.resize(1); allocator = segments[0]->allocator; segments[0]->Reset(); diff --git a/src/duckdb/src/common/types/selection_vector.cpp b/src/duckdb/src/common/types/selection_vector.cpp index b8e4a5e28..8f0186a7e 100644 --- a/src/duckdb/src/common/types/selection_vector.cpp +++ b/src/duckdb/src/common/types/selection_vector.cpp @@ -17,8 +17,6 @@ SelectionData::SelectionData(idx_t count) { #endif } -SelectionData::~SelectionData() = default; - namespace { struct BooleanSelectionTable { sel_t positions[256][8] {}; diff --git a/src/duckdb/src/common/types/uhugeint.cpp b/src/duckdb/src/common/types/uhugeint.cpp index ea9679eed..29850659f 100644 --- a/src/duckdb/src/common/types/uhugeint.cpp +++ b/src/duckdb/src/common/types/uhugeint.cpp @@ -1,6 +1,7 @@ #include "duckdb/common/types/uhugeint.hpp" #include "duckdb/common/bit_utils.hpp" #include "duckdb/common/types/hugeint.hpp" +#include "duckdb/common/types/cast_helpers.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/algorithm.hpp" #include "duckdb/common/limits.hpp" @@ -59,20 +60,10 @@ const uhugeint_t Uhugeint::POWERS_OF_TEN[] { uhugeint_t(1000000000000000000) * uhugeint_t(1000000000000000000) * uhugeint_t(100)}; string Uhugeint::ToString(uhugeint_t input) { - uhugeint_t remainder; - string result; - while (true) { - if (!input.lower && !input.upper) { - break; - } - input = Uhugeint::DivMod(input, 10, remainder); - result = string(1, UnsafeNumericCast('0' + remainder.lower)) + result; // NOLINT - } - if (result.empty()) { - // value is zero - return "0"; - } - return result; + char buffer[NumericLimits::Digits()]; + auto end = buffer + sizeof(buffer); + auto start = NumericHelper::FormatUnsigned(input, end); + return string(start, end); } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/common/types/value.cpp b/src/duckdb/src/common/types/value.cpp index 7e845344c..f9d428b10 100644 --- a/src/duckdb/src/common/types/value.cpp +++ b/src/duckdb/src/common/types/value.cpp @@ -246,49 +246,20 @@ Value Value::MinimumValue(const LogicalType &type) { case LogicalTypeId::UBIGINT: return Value::UBIGINT(NumericLimits::Minimum()); case LogicalTypeId::DATE: - return Value::DATE(Date::FromDate(Date::DATE_MIN_YEAR, Date::DATE_MIN_MONTH, Date::DATE_MIN_DAY)); + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::TIMESTAMP_SEC: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP_NS: + case LogicalTypeId::TIMESTAMP_TZ: + case LogicalTypeId::TIMESTAMP_TZ_NS: + return Value::NegativeInfinity(type); case LogicalTypeId::TIME: return Value::TIME(dtime_t(0)); case LogicalTypeId::TIME_NS: return Value::TIME_NS(dtime_ns_t(0)); - case LogicalTypeId::TIMESTAMP: { - const auto date = Date::FromDate(Timestamp::MIN_YEAR, Timestamp::MIN_MONTH, Timestamp::MIN_DAY); - return Value::TIMESTAMP(date, dtime_t(0)); - } - case LogicalTypeId::TIMESTAMP_SEC: { - // Get the minimum timestamp and convert it to timestamp_sec_t. - const auto min_ts = MinimumValue(LogicalType::TIMESTAMP).GetValue(); - const timestamp_sec_t ts(min_ts.value / Interval::MICROS_PER_SEC); - return Value::TIMESTAMPSEC(ts); - } - case LogicalTypeId::TIMESTAMP_MS: { - // Get the minimum timestamp and convert it to timestamp_ms_t. - const auto min_ts = MinimumValue(LogicalType::TIMESTAMP).GetValue(); - const timestamp_ms_t ts(min_ts.value / Interval::MICROS_PER_MSEC); - return Value::TIMESTAMPMS(ts); - } - case LogicalTypeId::TIMESTAMP_NS: { - // Clear the fractional day. - auto min_ns = NumericLimits::Minimum(); - min_ns /= Interval::NANOS_PER_DAY; - min_ns *= Interval::NANOS_PER_DAY; - return Value::TIMESTAMPNS(timestamp_ns_t(min_ns)); - } case LogicalTypeId::TIME_TZ: // "00:00:00+1559" from the PG docs, but actually 00:00:00+15:59:59 return Value::TIMETZ(dtime_tz_t(dtime_t(0), dtime_tz_t::MAX_OFFSET)); - case LogicalTypeId::TIMESTAMP_TZ: { - const auto date = Date::FromDate(Timestamp::MIN_YEAR, Timestamp::MIN_MONTH, Timestamp::MIN_DAY); - const auto ts = Timestamp::FromDatetime(date, dtime_t(0)); - return Value::TIMESTAMPTZ(timestamp_tz_t(ts)); - } - case LogicalTypeId::TIMESTAMP_TZ_NS: { - // Clear the fractional day. - auto min_ns = NumericLimits::Minimum(); - min_ns /= Interval::NANOS_PER_DAY; - min_ns *= Interval::NANOS_PER_DAY; - return Value::TIMESTAMPTZNS(timestamp_tz_ns_t(min_ns)); - } case LogicalTypeId::INTERVAL: { const auto min_months = NumericLimits::Minimum(); const auto min_days = NumericLimits::Minimum(); @@ -360,35 +331,19 @@ Value Value::MaximumValue(const LogicalType &type) { case LogicalTypeId::UBIGINT: return Value::UBIGINT(NumericLimits::Maximum()); case LogicalTypeId::DATE: - return Value::DATE(Date::FromDate(Date::DATE_MAX_YEAR, Date::DATE_MAX_MONTH, Date::DATE_MAX_DAY)); + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::TIMESTAMP_SEC: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP_NS: + case LogicalTypeId::TIMESTAMP_TZ: + case LogicalTypeId::TIMESTAMP_TZ_NS: + return Value::Infinity(type); case LogicalTypeId::TIME: // 24:00:00 according to PG return Value::TIME(dtime_t(Interval::MICROS_PER_DAY)); case LogicalTypeId::TIME_NS: // 24:00:00 according to PG return Value::TIME_NS(dtime_ns_t(Interval::NANOS_PER_DAY)); - case LogicalTypeId::TIMESTAMP: - return Value::TIMESTAMP(timestamp_t(NumericLimits::Maximum() - 1)); - case LogicalTypeId::TIMESTAMP_SEC: { - // Get the maximum timestamp and convert it to timestamp_s_t. - const auto max_ts = MaximumValue(LogicalType::TIMESTAMP).GetValue(); - const timestamp_sec_t ts(max_ts.value / Interval::MICROS_PER_SEC); - return Value::TIMESTAMPSEC(ts); - } - case LogicalTypeId::TIMESTAMP_MS: { - // Get the maximum timestamp and convert it to timestamp_ms_t. - const auto max_ts = MaximumValue(LogicalType::TIMESTAMP).GetValue(); - const timestamp_ms_t ts(max_ts.value / Interval::MICROS_PER_MSEC); - return Value::TIMESTAMPMS(ts); - } - case LogicalTypeId::TIMESTAMP_NS: { - const auto ts = timestamp_ns_t(NumericLimits::Maximum() - 1); - return Value::TIMESTAMPNS(ts); - } - case LogicalTypeId::TIMESTAMP_TZ: - return Value::TIMESTAMPTZ(timestamp_tz_t(NumericLimits::Maximum() - 1)); - case LogicalTypeId::TIMESTAMP_TZ_NS: - return Value::TIMESTAMPTZNS(timestamp_tz_ns_t(NumericLimits::Maximum() - 1)); case LogicalTypeId::TIME_TZ: // "24:00:00-1559" from the PG docs but actually "24:00:00-15:59:59". return Value::TIMETZ(dtime_tz_t(dtime_t(Interval::MICROS_PER_DAY), dtime_tz_t::MIN_OFFSET)); @@ -1030,6 +985,22 @@ Value Value::GEOMETRY(const_data_ptr_t data, idx_t len) { return result; } +Value Value::GEOGRAPHY(const_data_ptr_t data, idx_t len, const CoordinateReferenceSystem &crs) { + Value result; + result.type_ = LogicalType::GEOGRAPHY(crs); // construct type explicitly so that we get the ExtraTypeInfo + result.is_null = false; + result.value_info_ = make_shared_ptr(string(const_char_ptr_cast(data), len)); + return result; +} + +Value Value::GEOGRAPHY(const_data_ptr_t data, idx_t len) { + Value result; + result.type_ = LogicalType::GEOGRAPHY(); // construct type explicitly so that we get the ExtraTypeInfo + result.is_null = false; + result.value_info_ = make_shared_ptr(string(const_char_ptr_cast(data), len)); + return result; +} + Value Value::TYPE(const LogicalType &type) { MemoryStream stream; SerializationOptions options; @@ -1796,6 +1767,7 @@ string Value::ToSQLString() const { case LogicalTypeId::BLOB: case LogicalTypeId::BIT: case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: return "'" + ToString() + "'::" + type_.ToString(); case LogicalTypeId::VARCHAR: case LogicalTypeId::ENUM: { @@ -2369,9 +2341,9 @@ void Value::SerializeInternal(Serializer &serializer, bool serialize_type) const if (type_.id() == LogicalTypeId::BLOB) { auto blob_str = Blob::ToString(StringValue::Get(*this)); serializer.WriteProperty(102, "value", blob_str); - } else if (type_.id() == LogicalTypeId::GEOMETRY) { - if (!serializer.ShouldSerialize(StorageVersion::V1_5_0)) { - // Write as old-style SPATIAL format + } else if (type_.id() == LogicalTypeId::GEOMETRY || type_.id() == LogicalTypeId::GEOGRAPHY) { + if (type_.id() == LogicalTypeId::GEOMETRY && !serializer.ShouldSerialize(StorageVersion::V1_5_0)) { + // Write as old-style SPATIAL format (GEOMETRY only - GEOGRAPHY has no legacy form) string blob; Geometry::ToSpatialGeometry(StringValue::Get(*this), blob); auto text = Blob::ToString(blob); @@ -2632,10 +2604,13 @@ Value Value::Deserialize(Deserializer &deserializer) { if (type.id() == LogicalTypeId::BLOB) { auto str = deserializer.ReadProperty(102, "value"); new_value.value_info_ = make_shared_ptr(Blob::ToBlob(str)); - } else if (type.id() == LogicalTypeId::GEOMETRY) { + } else if (type.id() == LogicalTypeId::GEOMETRY || type.id() == LogicalTypeId::GEOGRAPHY) { auto text = deserializer.ReadProperty(102, "value"); + // GEOGRAPHY is always WKB; GEOMETRY defaults to the legacy SPATIAL format when the property is absent. + const auto default_format = + type.id() == LogicalTypeId::GEOGRAPHY ? GeometryStorageType::WKB : GeometryStorageType::SPATIAL; auto type = deserializer.ReadPropertyWithExplicitDefault(103, "geometry_format", - GeometryStorageType::SPATIAL); + default_format); auto blob = Blob::ToBlob(text); if (type == GeometryStorageType::WKB) { diff --git a/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp b/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp index 4f0667d78..1221aab06 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp @@ -24,8 +24,8 @@ namespace { //! Throw if reading 'size' bytes starting at 'ptr' would read past the end of the value buffer void CheckBinaryRead(const_data_ptr_t ptr, idx_t size, const_data_ptr_t end) { - if (ptr + size > end) { - throw IOException("Data corruption detected, read of length_in_bytes (%d) would exceed buffer capacity", size); + if (ptr > end || size > NumericCast(end - ptr)) { + throw DataCorruptionException("Corrupted VARIANT 'value' buffer, read of %llu bytes is out of bounds", size); } } @@ -62,6 +62,8 @@ struct BinaryObjectReader { count = LoadChecked(data, end); data += sizeof(uint8_t); } + //! The field ids and offsets of 'count' fields must fit in the value, before anything is sized by 'count' + CheckBinaryRead(data, (count * field_id_size) + (NumericCast(count + 1) * field_offset_size), end); field_ids = data; field_offsets = data + (count * field_id_size); values = field_offsets + (NumericCast(count + 1) * field_offset_size); @@ -108,6 +110,8 @@ struct BinaryArrayReader { count = LoadChecked(data, end); data += sizeof(uint8_t); } + //! The offsets of 'count' elements must fit in the value, before anything is sized by 'count' + CheckBinaryRead(data, NumericCast(count + 1) * field_offset_size, end); field_offsets = data; values = field_offsets + (NumericCast(count + 1) * field_offset_size); } diff --git a/src/duckdb/src/common/types/variant/variant_comparison.cpp b/src/duckdb/src/common/types/variant/variant_comparison.cpp index f55f82e96..5b7330bd6 100644 --- a/src/duckdb/src/common/types/variant/variant_comparison.cpp +++ b/src/duckdb/src/common/types/variant/variant_comparison.cpp @@ -1,5 +1,6 @@ #include "duckdb/common/types/uhugeint.hpp" #include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/cast_helpers.hpp" #include "duckdb/common/enum_util.hpp" #include "duckdb/common/types/variant_iterator.hpp" #include "duckdb/common/types/variant_comparison.hpp" @@ -12,20 +13,8 @@ constexpr int64_t NANOS_PER_MILLI = 1000000; constexpr int64_t NANOS_PER_SEC = 1000000000; constexpr int64_t NANOS_PER_DAY = 86400LL * NANOS_PER_SEC; -//! Writes the decimal digits of value into the back of buffer (which must hold 20 characters) and -//! returns the offset of the first digit - so no length has to be computed up front. -idx_t UInt64Digits(uint64_t value, char *buffer) { - idx_t pos = 20; - while (value >= 10) { - buffer[--pos] = static_cast('0' + value % 10); - value /= 10; - } - buffer[--pos] = static_cast('0' + value); - return pos; -} - //! Build a number key from a sign, the decimal digits of the magnitude (no leading zeros, as e.g. -//! produced by UInt64Digits) and a base-10 scale (value = magnitude / 10^scale) +//! produced by NumericHelper::FormatUnsigned) and a base-10 scale (value = magnitude / 10^scale) VariantNumberKey BuildNumberKey(bool negative, const char *digits, idx_t count, int64_t scale) { VariantNumberKey key; // find the first non-zero digit (magnitude digits have no leading zeros, but be defensive) @@ -52,32 +41,19 @@ VariantNumberKey BuildNumberKey(bool negative, const char *digits, idx_t count, return key; } -//! Build a number key from a 128-bit magnitude, using 64-bit arithmetic whenever the value fits +//! Build a number key from a 128-bit magnitude VariantNumberKey BuildNumberKey(bool negative, uhugeint_t magnitude, int64_t scale) { - if (magnitude.upper == 0) { - char buffer[20]; - auto offset = UInt64Digits(magnitude.lower, buffer); - return BuildNumberKey(negative, buffer + offset, 20 - offset, scale); - } - // magnitudes above 64 bits are rare, and are guaranteed to fit inline (39 digits) - auto magnitude_digits = Uhugeint::ToString(magnitude); - return BuildNumberKey(negative, magnitude_digits.data(), magnitude_digits.size(), scale); + char buffer[NumericLimits::Digits()]; + auto end = buffer + sizeof(buffer); + auto start = NumericHelper::FormatUnsigned(magnitude, end); + return BuildNumberKey(negative, start, NumericCast(end - start), scale); } //! Decompose a 128-bit signed value (hugeint) into (sign, magnitude) uhugeint_t HugeintMagnitude(const hugeint_t value, bool &negative) { negative = value.upper < 0; - uint64_t hi = static_cast(value.upper); - uint64_t lo = value.lower; - if (negative) { - // two's complement negate to get the magnitude - hi = ~hi; - lo = ~lo; - if (++lo == 0) { - ++hi; - } - } - return uhugeint_t(hi, lo); + const uhugeint_t magnitude(static_cast(value.upper), value.lower); + return negative ? -magnitude : magnitude; } //! Build a number key from a native (<= 64-bit) integer value, computing the magnitude and its @@ -92,9 +68,10 @@ VariantNumberKey IntegerNumberKey(T value) { magnitude = static_cast(0) - magnitude; // unsigned negate -> |value| (also handles the minimum) } } - char buffer[20]; - auto offset = UInt64Digits(magnitude, buffer); - return BuildNumberKey(negative, buffer + offset, 20 - offset, 0); + char buffer[NumericLimits::Digits()]; + auto end = buffer + sizeof(buffer); + auto start = NumericHelper::FormatUnsigned(magnitude, end); + return BuildNumberKey(negative, start, NumericCast(end - start), 0); } } // namespace @@ -153,6 +130,8 @@ VariantComparisonType GetVariantComparisonType(VariantLogicalType type) { return VariantComparisonType::BITSTRING; case VariantLogicalType::GEOMETRY: return VariantComparisonType::GEOMETRY; + case VariantLogicalType::GEOGRAPHY: + return VariantComparisonType::GEOGRAPHY; case VariantLogicalType::ARRAY: return VariantComparisonType::ARRAY; case VariantLogicalType::OBJECT: diff --git a/src/duckdb/src/common/types/variant/variant_iterator.cpp b/src/duckdb/src/common/types/variant/variant_iterator.cpp index 9c57c8cfe..a8ed7355b 100644 --- a/src/duckdb/src/common/types/variant/variant_iterator.cpp +++ b/src/duckdb/src/common/types/variant/variant_iterator.cpp @@ -138,6 +138,8 @@ VariantLogicalType ResolveShreddedTypeId(const LogicalType &type, bool &resolved return VariantLogicalType::BITSTRING; case LogicalTypeId::GEOMETRY: return VariantLogicalType::GEOMETRY; + case LogicalTypeId::GEOGRAPHY: + return VariantLogicalType::GEOGRAPHY; case LogicalTypeId::STRUCT: return VariantLogicalType::OBJECT; case LogicalTypeId::LIST: diff --git a/src/duckdb/src/common/types/vector.cpp b/src/duckdb/src/common/types/vector.cpp index 95e0a4a55..ee5ee166b 100644 --- a/src/duckdb/src/common/types/vector.cpp +++ b/src/duckdb/src/common/types/vector.cpp @@ -107,12 +107,16 @@ void Vector::Reference(const Value &value, count_t count) { ConstantVector::Reference(*this, value, count); } -void Vector::Reference(const Vector &other) { - if (other.GetType().id() != GetType().id()) { - throw InternalException("Vector::Reference used on vector of different type (source %s referenced %s)", - GetType(), other.GetType()); +static void CheckReferenceType(const LogicalType &type, const LogicalType &other_type) { + if (other_type.id() != type.id()) { + throw InternalException("Vector::Reference used on vector of different type (source %s referenced %s)", type, + other_type); } - D_ASSERT(other.GetType() == GetType()); + D_ASSERT(other_type == type); +} + +void Vector::Reference(const Vector &other) { + CheckReferenceType(GetType(), other.GetType()); ConstReference(other); } @@ -190,7 +194,7 @@ void Vector::Reinterpret(const Vector &other) { Vector new_vector(this_type, nullptr); new_vector.Reinterpret(DictionaryVector::Child(other)); auto &old_dict = buffer->Cast(); - auto new_entry = make_shared_ptr(std::move(new_vector)); + auto new_entry = make_buffer(std::move(new_vector)); // reinterpret re-mints the entry; the id and global flag are one contract and must survive together new_entry->id = old_dict.GetEntry().id; new_entry->global_dictionary = old_dict.GetEntry().global_dictionary; @@ -199,7 +203,7 @@ void Vector::Reinterpret(const Vector &other) { } void Vector::ConstReference(const Vector &other) const { - AssignSharedPointer(buffer, other.buffer); + buffer = other.buffer; } void Vector::ResetFromCache(const VectorCache &cache) { @@ -214,25 +218,24 @@ void Vector::Slice(const Vector &other, idx_t offset, idx_t end) { } void Vector::Slice(const Vector &other, const SelectionVector &sel, idx_t count) { - Reference(other); - Slice(sel, count); -} - -void Vector::Slice(const SelectionVector &sel, idx_t count) { - if (!sel.IsSet() && count == size()) { - // no-op: no selection vector, and the requested count matches the current size - return; - } - if (!buffer) { + CheckReferenceType(GetType(), other.GetType()); + if (!other.buffer || (!sel.IsSet() && count == other.size())) { + ConstReference(other); return; } - auto new_buffer = buffer->Slice(GetType(), sel, count); + auto new_buffer = other.buffer->Slice(GetType(), sel, count); if (new_buffer) { buffer = std::move(new_buffer); + } else { + ConstReference(other); } FlatVector::SetSize(*this, count_t(count)); } +void Vector::Slice(const SelectionVector &sel, idx_t count) { + Slice(*this, sel, count); +} + void Vector::Slice(const SelectionVector &sel, idx_t count, SelCache &cache) { if (!sel.IsSet() && count == size()) { return; @@ -258,8 +261,7 @@ void Vector::Dictionary(const Vector &dict, idx_t dictionary_size, const Selecti if (dict.size() != dictionary_size) { throw InternalException("Vector::Dictionary called with mismatching dictionary size"); } - Reference(dict); - Dictionary(dictionary_size, sel, count); + Slice(dict, sel, count); } void Vector::Dictionary(buffer_ptr reusable_dict, const SelectionVector &sel, idx_t sel_count) { @@ -541,7 +543,9 @@ void Vector::Serialize(Serializer &serializer, bool compressed_serialization) { } ToUnifiedFormat(vdata); - if (logical_type.id() == LogicalTypeId::GEOMETRY && serializer.ShouldSerialize(Geometry::VERSION_ADDED)) { + const bool is_geo_type = + logical_type.id() == LogicalTypeId::GEOMETRY || logical_type.id() == LogicalTypeId::GEOGRAPHY; + if (is_geo_type && serializer.ShouldSerialize(Geometry::VERSION_ADDED)) { serializer.WriteProperty(99, "geometry_format", GeometryStorageType::WKB); } @@ -563,11 +567,12 @@ void Vector::Serialize(Serializer &serializer, bool compressed_serialization) { auto ptr = make_unsafe_uniq_array_uninitialized(write_size); VectorOperations::WriteToStorage(*this, ptr.get()); serializer.WriteProperty(102, "data", ptr.get(), write_size); - } else if (logical_type.id() == LogicalTypeId::GEOMETRY) { + } else if (is_geo_type) { auto geoms = UnifiedVectorFormat::GetData(vdata); - // Are we targeting an older serialization version? - if (!serializer.ShouldSerialize(StorageVersion::V1_5_0)) { + // Are we targeting an older serialization version? GEOGRAPHY has no legacy SPATIAL form, so it always + // uses WKB (and LogicalType::Serialize already rejects writing it to versions older than v1.5.0). + if (logical_type.id() == LogicalTypeId::GEOMETRY && !serializer.ShouldSerialize(StorageVersion::V1_5_0)) { // Serialize data as old-style SPATIAL format string blob; serializer.WriteList(102, "data", count, [&](Serializer::List &list, idx_t i) { @@ -726,12 +731,18 @@ void Vector::Deserialize(Deserializer &deserializer, idx_t count) { return; } + const bool is_geo_type = + logical_type.id() == LogicalTypeId::GEOMETRY || logical_type.id() == LogicalTypeId::GEOGRAPHY; auto geometry_format = GeometryStorageType::WKB; if (logical_type.id() == LogicalTypeId::GEOMETRY) { // Try to read the geometry format, but default to the old SPATIAL format for older versions that did not // serialize this property geometry_format = deserializer.ReadPropertyWithExplicitDefault( 99, "geometry_format", GeometryStorageType::SPATIAL); + } else if (logical_type.id() == LogicalTypeId::GEOGRAPHY) { + // GEOGRAPHY always uses WKB - it never had a legacy SPATIAL representation. + geometry_format = deserializer.ReadPropertyWithExplicitDefault(99, "geometry_format", + GeometryStorageType::WKB); } auto &validity = FlatVector::ValidityMutable(*this); @@ -750,7 +761,7 @@ void Vector::Deserialize(Deserializer &deserializer, idx_t count) { deserializer.ReadProperty(102, "data", ptr.get(), column_size); VectorOperations::ReadFromStorage(ptr.get(), count, *this); - } else if (logical_type.id() == LogicalTypeId::GEOMETRY) { + } else if (is_geo_type) { auto blobs = FlatVector::GetDataMutable(*this); if (geometry_format == GeometryStorageType::WKB) { diff --git a/src/duckdb/src/common/types/vector_cache.cpp b/src/duckdb/src/common/types/vector_cache.cpp index 785b85872..705781415 100644 --- a/src/duckdb/src/common/types/vector_cache.cpp +++ b/src/duckdb/src/common/types/vector_cache.cpp @@ -28,7 +28,7 @@ class VectorCacheEntry { auto array_size = ArrayType::GetSize(type); child_caches.push_back(make_uniq(allocator, child_type, array_size * capacity)); auto child_vector = make_uniq(child_type, nullptr); - buffer = make_shared_ptr(std::move(child_vector), array_size, capacity); + buffer = make_buffer(std::move(child_vector), array_size, capacity); break; } case PhysicalType::STRUCT: { diff --git a/src/duckdb/src/common/vector/dictionary_vector.cpp b/src/duckdb/src/common/vector/dictionary_vector.cpp index a4a2607f4..1df01cc01 100644 --- a/src/duckdb/src/common/vector/dictionary_vector.cpp +++ b/src/duckdb/src/common/vector/dictionary_vector.cpp @@ -109,14 +109,14 @@ buffer_ptr DictionaryBuffer::SliceInternal(const LogicalType &type for (idx_t i = 0; i < count; i++) { new_sel.set_index(i, sel_vector.get_index(offset + i)); } - return make_uniq(new_sel, count, entry); + return make_buffer(new_sel, count, entry); } if (offset == 0) { // for offset = 0 all we have to do is update the count - so just create a new buffer - return make_uniq(sel_data, end, entry); + return make_buffer(sel_data, end, entry); } SelectionVector sliced_sel(sel_vector.data() + offset, count); - auto result = make_uniq(sliced_sel, count, entry); + auto result = make_buffer(sliced_sel, count, entry); result->AddAuxiliaryData(make_uniq(sel_data)); return result; } diff --git a/src/duckdb/src/common/vector/flat_vector.cpp b/src/duckdb/src/common/vector/flat_vector.cpp index e0ce3f7d0..4714709bd 100644 --- a/src/duckdb/src/common/vector/flat_vector.cpp +++ b/src/duckdb/src/common/vector/flat_vector.cpp @@ -115,7 +115,7 @@ buffer_ptr StandardVectorBuffer::SliceInternal(const LogicalType & auto offset_ptr = data_ptr ? data_ptr + type_size * offset : nullptr; auto result = make_buffer(offset_ptr, count, type_size); result->GetValidityMask().Slice(validity, offset, count); - result->AddAuxiliaryData(make_uniq(shared_from_this())); + result->AddAuxiliaryData(make_uniq(buffer_from_this())); return result; } @@ -125,7 +125,7 @@ buffer_ptr StandardVectorBuffer::ConstantSliceInternal(const Logic result->GetValidityMask().Set(0, validity.RowIsValid(0)); result->SetVectorType(VectorType::CONSTANT_VECTOR); result->SetVectorSize(count); - result->AddAuxiliaryData(make_uniq(shared_from_this())); + result->AddAuxiliaryData(make_uniq(buffer_from_this())); return result; } @@ -155,8 +155,8 @@ buffer_ptr StandardVectorBuffer::SliceInternal(const LogicalType & // to avoid creating a DictionaryBuffer with a null selection vector. return SliceInternal(type, idx_t(0), count); } - Vector child_vector(type, shared_from_this()); - auto entry = make_shared_ptr(std::move(child_vector)); + Vector child_vector(type, buffer_from_this()); + auto entry = make_buffer(std::move(child_vector)); return make_buffer(sel, count, std::move(entry)); } @@ -490,6 +490,13 @@ Value StandardVectorBuffer::GetValue(const LogicalType &type, idx_t index) const } return Value::GEOMETRY(const_data_ptr_cast(str.GetData()), str.GetSize()); } + case LogicalTypeId::GEOGRAPHY: { + auto str = reinterpret_cast(data_ptr)[index]; + if (GeoType::HasCRS(type)) { + return Value::GEOGRAPHY(const_data_ptr_cast(str.GetData()), str.GetSize(), GeoType::GetCRS(type)); + } + return Value::GEOGRAPHY(const_data_ptr_cast(str.GetData()), str.GetSize()); + } case LogicalTypeId::LEGACY_AGGREGATE_STATE: { auto str = reinterpret_cast(data_ptr)[index]; return Value::LEGACY_AGGREGATE_STATE(type, const_data_ptr_cast(str.GetData()), str.GetSize()); diff --git a/src/duckdb/src/common/vector/list_vector.cpp b/src/duckdb/src/common/vector/list_vector.cpp index 2bf8c149e..c2e2ca786 100644 --- a/src/duckdb/src/common/vector/list_vector.cpp +++ b/src/duckdb/src/common/vector/list_vector.cpp @@ -143,7 +143,7 @@ buffer_ptr VectorListBuffer::SliceInternal(const LogicalType &type auto count = count_t(end - offset); auto result = make_buffer(offset_ptr, count, *this); result->GetValidityMask().Slice(validity, offset, count); - result->AddAuxiliaryData(make_uniq(shared_from_this())); + result->AddAuxiliaryData(make_uniq(buffer_from_this())); return result; } @@ -153,7 +153,7 @@ buffer_ptr VectorListBuffer::ConstantSliceInternal(const LogicalTy result->GetValidityMask().Set(0, validity.RowIsValid(0)); result->SetVectorType(VectorType::CONSTANT_VECTOR); result->SetVectorSize(count); - result->AddAuxiliaryData(make_uniq(shared_from_this())); + result->AddAuxiliaryData(make_uniq(buffer_from_this())); return result; } diff --git a/src/duckdb/src/common/vector/string_vector.cpp b/src/duckdb/src/common/vector/string_vector.cpp index 21ce4194e..37eed6b83 100644 --- a/src/duckdb/src/common/vector/string_vector.cpp +++ b/src/duckdb/src/common/vector/string_vector.cpp @@ -148,7 +148,7 @@ buffer_ptr VectorStringBuffer::SliceInternal(const LogicalType &ty auto count = count_t(end - offset); auto result = make_buffer(offset_ptr, count); result->GetValidityMask().Slice(validity, offset, count); - result->AddAuxiliaryData(make_uniq(shared_from_this())); + result->AddAuxiliaryData(make_uniq(buffer_from_this())); return result; } @@ -158,7 +158,7 @@ buffer_ptr VectorStringBuffer::ConstantSliceInternal(const Logical result->GetValidityMask().Set(0, validity.RowIsValid(0)); result->SetVectorType(VectorType::CONSTANT_VECTOR); result->SetVectorSize(count); - result->AddAuxiliaryData(make_uniq(shared_from_this())); + result->AddAuxiliaryData(make_uniq(buffer_from_this())); return result; } diff --git a/src/duckdb/src/common/virtual_file_system.cpp b/src/duckdb/src/common/virtual_file_system.cpp index c037480ba..0ae15ed54 100644 --- a/src/duckdb/src/common/virtual_file_system.cpp +++ b/src/duckdb/src/common/virtual_file_system.cpp @@ -5,6 +5,7 @@ #include "duckdb/common/file_opener.hpp" #include "duckdb/common/memory_mapped_file.hpp" #include "duckdb/common/gzip_file_system.hpp" +#include "duckdb/common/local_file_system.hpp" #include "duckdb/common/pipe_file_system.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/main/client_context.hpp" @@ -110,11 +111,12 @@ shared_ptr FileSystemRegistry::ExtractSubSystem(const string return nullptr; } -VirtualFileSystem::VirtualFileSystem() : VirtualFileSystem(FileSystem::CreateLocal()) { +VirtualFileSystem::VirtualFileSystem() : VirtualFileSystem(make_uniq()) { } VirtualFileSystem::VirtualFileSystem(unique_ptr &&inner) - : file_system_registry(make_shared_ptr(std::move(inner))) { + : owned_local_file_system(inner->IsLocalFileSystem() ? nullptr : make_uniq()), + file_system_registry(make_shared_ptr(std::move(inner))) { VirtualFileSystem::RegisterCompressionFilesystem(make_uniq()); } @@ -167,6 +169,14 @@ static FileCompressionType CompressionFromExtension(const string &lower_path) { return FileCompressionType::UNCOMPRESSED; } +FileSystem &VirtualFileSystem::GetLocalFileSystem() { + auto &fs = *file_system_registry->default_fs->file_system; + if (fs.IsLocalFileSystem()) { + return fs; + } + return *owned_local_file_system; +} + optional_ptr VirtualFileSystem::FindCompressionFileSystem(FileSystemRegistry ®istry, const FileCompressionType &compression, const string &filepath, bool for_writing) { diff --git a/src/duckdb/src/execution/aggregate_hashtable.cpp b/src/duckdb/src/execution/aggregate_hashtable.cpp index f922e4535..89bb8b189 100644 --- a/src/duckdb/src/execution/aggregate_hashtable.cpp +++ b/src/duckdb/src/execution/aggregate_hashtable.cpp @@ -302,6 +302,23 @@ void GroupedAggregateHashTable::Verify() { #endif } +void GroupedAggregateHashTable::VerifyEntries(const Vector &group_hashes_v, const Vector &addresses_v, idx_t count) { +#ifdef DEBUG + // every row's entry points to its row, which carries the hash the entry's salt was taken from + const auto hashes = group_hashes_v.Values(); + const auto addresses = FlatVector::GetData(addresses_v); + const auto ht_offsets = FlatVector::GetData(state.ht_offsets); + for (idx_t i = 0; i < count; i++) { + const auto &entry = entries[ht_offsets[i]]; + const auto hash = hashes[i].GetValue(); + D_ASSERT(entry.IsOccupied()); + D_ASSERT(entry.GetPointer() == addresses[i]); + D_ASSERT(entry.GetSalt() == ht_entry_t::ExtractSalt(hash)); + D_ASSERT(Load(addresses[i] + hash_offset) == hash); + } +#endif +} + void GroupedAggregateHashTable::ClearPointerTable() { std::fill_n(entries, capacity, ht_entry_t()); } @@ -322,6 +339,10 @@ idx_t GroupedAggregateHashTable::GetMaterializedCount() const { return result; } +idx_t GroupedAggregateHashTable::GetMaterializedSize() const { + return partitioned_data->GetDataSize() + (unpartitioned_data ? unpartitioned_data->GetDataSize() : 0); +} + void GroupedAggregateHashTable::SkipLookups() { adaptivity.SkipLookups(); } @@ -593,6 +614,10 @@ optional_idx GroupedAggregateHashTable::TryAddDictionaryGroups(DataChunk &groups optional_idx GroupedAggregateHashTable::TryAddConstantGroups(DataChunk &groups, DataChunk &payload, const unsafe_vector &filter) { + if (groups.size() == 0) { + // no rows, no group: the constant group below would be added without a row that has it + return optional_idx(); + } #ifndef DEBUG if (groups.size() <= 1) { // this only has a point if we have multiple groups @@ -633,6 +658,9 @@ optional_idx GroupedAggregateHashTable::TryAddConstantGroups(DataChunk &groups, auto result_addresses = FlatVector::Writer(state.addresses, row_count); uintptr_t aggregate_address = new_dict_addresses[0] + layout_ptr->GetAggrOffset(); static constexpr uint64_t GID_HIGH_MASK = ~(ClusteredAggr::MAX_GID_COUNT - 1); + // This chunk needs its own pointer prefix; retain the metadata for the cached dictionary. + const auto dictionary_high_bits = dict_state.address_high_bits; + const auto dictionary_high_bits_uniform = dict_state.address_high_bits_uniform; dict_state.address_high_bits_uniform = (sizeof(uintptr_t) == sizeof(uint64_t)); dict_state.address_high_bits = static_cast(aggregate_address) & GID_HIGH_MASK; for (idx_t i = 0; i < row_count; i++) { @@ -642,6 +670,8 @@ optional_idx GroupedAggregateHashTable::TryAddConstantGroups(DataChunk &groups, state.addresses.SetVectorType(VectorType::CONSTANT_VECTOR); // ht_offsets are only valid for the single constant group, not the full payload UpdateAggregates(payload, filter, row_count, false); + dict_state.address_high_bits = dictionary_high_bits; + dict_state.address_high_bits_uniform = dictionary_high_bits_uniform; state.addresses.SetVectorType(VectorType::FLAT_VECTOR); return new_group_count; @@ -723,7 +753,6 @@ void GroupedAggregateHashTable::UpdateAggregates(DataChunk &payload, const unsaf // evaluate every aggregate filter once for this chunk filter_set.ApplyFilters(payload, filter); if (UpdateAggregatesClustered(payload, filter, count, ht_offsets_valid)) { - Verify(); return; } @@ -752,8 +781,6 @@ void GroupedAggregateHashTable::UpdateAggregates(DataChunk &payload, const unsaf VectorOperations::AddInPlace(state.addresses, NumericCast(aggr.payload_size)); filter_idx++; } - - Verify(); } idx_t GroupedAggregateHashTable::AddChunk(DataChunk &groups, Vector &group_hashes, DataChunk &payload, @@ -1021,6 +1048,7 @@ idx_t GroupedAggregateHashTable::FindOrCreateGroupsInternal(DataChunk &groups, V FlatVector::SetSize(addresses_v, chunk_size); count += new_group_count; + VerifyEntries(group_hashes_v, addresses_v, chunk_size); return new_group_count; } @@ -1241,7 +1269,7 @@ void GroupedAggregateHashTable::Combine(TupleDataCollection &other_data, optiona while (fm_state.Scan()) { // Check for interrupts with each chunk - context.InterruptCheck(); + context.FastInterruptCheck(); auto &source_rows = fm_state.scan_state.chunk_state; const auto chunk_count = fm_state.groups.size(); if (!layout_ptr->AllConstant()) { diff --git a/src/duckdb/src/execution/aggregate_state_spilling.cpp b/src/duckdb/src/execution/aggregate_state_spilling.cpp index 8d2ab96a0..371d6f50b 100644 --- a/src/duckdb/src/execution/aggregate_state_spilling.cpp +++ b/src/duckdb/src/execution/aggregate_state_spilling.cpp @@ -1,6 +1,7 @@ #include "duckdb/execution/aggregate_state_spilling.hpp" #include "duckdb/function/aggregate_state_serialization.hpp" +#include "duckdb/function/scalar/generic_common.hpp" #include "duckdb/storage/arena_allocator.hpp" #include "duckdb/common/radix_partitioning.hpp" @@ -42,20 +43,23 @@ unique_ptr AggregateStateSpilling::TryCreateSpillPlan(c if (aggregates.empty()) { return nullptr; } + auto plan = make_uniq(); + plan->state_layouts.reserve(aggregates.size()); for (auto &aggr : aggregates) { - if (!aggr.function.HasGetStateTypeCallback()) { - // the aggregate cannot describe its state - return nullptr; - } if (aggr.function.HasStateDestructorCallback()) { // the state owns resources beyond the arena return nullptr; } - } - auto plan = make_uniq(); - plan->state_layouts.reserve(aggregates.size()); - for (auto &aggr : aggregates) { - plan->state_layouts.push_back(aggr.function.GetStateType(aggr.GetFunctionData())); + AggregateStateLayout state_layout; + if (aggr.function.HasGetStateTypeCallback()) { + state_layout = aggr.function.GetStateType(aggr.GetFunctionData()); + } else if (!ExportAggregateFunction::TryGetCombinedStateLayout(aggr.function, aggr.GetFunctionData(), + state_layout)) { + // the aggregate cannot describe its state, and it is not a combine_aggr over states that can: the + // states combine_aggr accumulates have the layout of the aggregate that exported them + return nullptr; + } + plan->state_layouts.push_back(std::move(state_layout)); } // only layouts whose states can reference the arena benefit from spilling bool arena_backed = false; diff --git a/src/duckdb/src/execution/column_binding_resolver.cpp b/src/duckdb/src/execution/column_binding_resolver.cpp index c078d0ff6..7e6a07747 100644 --- a/src/duckdb/src/execution/column_binding_resolver.cpp +++ b/src/duckdb/src/execution/column_binding_resolver.cpp @@ -131,21 +131,20 @@ void ColumnBindingResolver::VisitOperator(LogicalOperator &op) { } case LogicalOperatorType::LOGICAL_ANY_JOIN: { // ANY join, this join is different because we evaluate the expression on the bindings of BOTH join sides at - // once i.e. we set the bindings first to the bindings of the entire join, and then resolve the expressions of - // this operator - VisitOperatorChildren(op); - bindings = op.GetColumnBindings(); - types = op.types; + // once i.e. we set the bindings first to the full bindings of both children, and then resolve the expressions + // of this operator auto &any_join = op.Cast(); - if (any_join.join_type == JoinType::SEMI || any_join.join_type == JoinType::ANTI) { - auto right_bindings = op.children[1]->GetColumnBindings(); - bindings.insert(bindings.end(), right_bindings.begin(), right_bindings.end()); - auto &right_types = op.children[1]->types; - types.insert(types.end(), right_types.begin(), right_types.end()); - } if (any_join.join_type == JoinType::RIGHT_SEMI || any_join.join_type == JoinType::RIGHT_ANTI) { throw InternalException("RIGHT SEMI/ANTI any join not supported yet"); } + VisitOperator(*op.children[0]); + auto left_bindings = bindings; + auto left_types = types; + VisitOperator(*op.children[1]); + auto combined_bindings = left_bindings; + combined_bindings.insert(combined_bindings.end(), bindings.begin(), bindings.end()); + types = CombineJoinTypes(left_bindings, left_types, bindings, types); + bindings = std::move(combined_bindings); VisitOperatorExpressions(op); // Restore bindings for the caller diff --git a/src/duckdb/src/execution/expression_executor.cpp b/src/duckdb/src/execution/expression_executor.cpp index f5fe765a0..f72ff3a43 100644 --- a/src/duckdb/src/execution/expression_executor.cpp +++ b/src/duckdb/src/execution/expression_executor.cpp @@ -143,13 +143,13 @@ idx_t ExpressionExecutor::SelectExpression(DataChunk &input, SelectionVector &se } idx_t ExpressionExecutor::SelectExpression(DataChunk &input, SelectionVector &result_sel, - optional_ptr current_sel, idx_t current_count) { + optional_ptr current_sel, idx_t current_count) { return SelectExpression(input, result_sel, nullptr, current_sel, current_count); } idx_t ExpressionExecutor::SelectExpression(DataChunk &input, optional_ptr true_sel, optional_ptr false_sel, - optional_ptr current_sel, idx_t current_count) { + optional_ptr current_sel, idx_t current_count) { D_ASSERT(expressions.size() == 1); D_ASSERT(current_count <= input.size()); SetChunk(&input); diff --git a/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp b/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp index 2f92d07fd..fc8fa5eae 100644 --- a/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp +++ b/src/duckdb/src/execution/expression_executor/execute_conjunction.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/common/bit_utils.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/logging/logger.hpp" @@ -15,6 +16,15 @@ struct ConjunctionState : public ExpressionState { adaptive_filter->SetLogger(GetContext().GetLoggerPtr()); } unique_ptr adaptive_filter; + SelectionVector true_selection; + SelectionVector false_selection; + + SelectionVector &GetSelection(SelectionVector &selection, idx_t count) { + if (selection.Capacity() < count) { + selection.Initialize(NextPowerOfTwo(count)); + } + return selection; + } }; unique_ptr ExpressionExecutor::InitializeState(const BoundConjunctionExpression &expr, @@ -91,12 +101,12 @@ idx_t ExpressionExecutor::Select(const BoundConjunctionExpression &expr, Express idx_t current_count = count; idx_t false_count = 0; - unique_ptr temp_true, temp_false; + optional_ptr temp_true, temp_false; if (false_sel) { - temp_false = make_uniq(STANDARD_VECTOR_SIZE); + temp_false = state.GetSelection(state.false_selection, count); } if (!true_sel) { - temp_true = make_uniq(STANDARD_VECTOR_SIZE); + temp_true = state.GetSelection(state.true_selection, count); true_sel = temp_true.get(); } for (idx_t i = 0; i < expr.GetChildren().size(); i++) { @@ -132,12 +142,12 @@ idx_t ExpressionExecutor::Select(const BoundConjunctionExpression &expr, Express idx_t current_count = count; idx_t result_count = 0; - unique_ptr temp_true, temp_false; + optional_ptr temp_true, temp_false; if (true_sel) { - temp_true = make_uniq(STANDARD_VECTOR_SIZE); + temp_true = state.GetSelection(state.true_selection, count); } if (!false_sel) { - temp_false = make_uniq(STANDARD_VECTOR_SIZE); + temp_false = state.GetSelection(state.false_selection, count); false_sel = temp_false.get(); } for (idx_t i = 0; i < expr.GetChildren().size(); i++) { diff --git a/src/duckdb/src/execution/expression_executor/execute_operator.cpp b/src/duckdb/src/execution/expression_executor/execute_operator.cpp index acf234f65..be0ca9679 100644 --- a/src/duckdb/src/execution/expression_executor/execute_operator.cpp +++ b/src/duckdb/src/execution/expression_executor/execute_operator.cpp @@ -8,9 +8,30 @@ namespace duckdb { +struct CoalesceState : public ExpressionState { + CoalesceState(const Expression &expr, ExpressionExecutorState &root) : ExpressionState(expr, root) { + } + + void Prepare(idx_t count) { + intermediate_chunk.Reset(); + for (auto &selection : selections) { + if (selection.Capacity() < count) { + selection.Initialize(NextPowerOfTwo(count)); + } + } + } + + SelectionVector selections[4]; +}; + unique_ptr ExpressionExecutor::InitializeState(const BoundOperatorExpression &expr, ExpressionExecutorState &root) { - auto result = make_uniq(expr, root); + unique_ptr result; + if (expr.GetExpressionType() == ExpressionType::OPERATOR_COALESCE) { + result = make_uniq(expr, root); + } else { + result = make_uniq(expr, root); + } const auto save_inside_try = root.inside_try; const auto expression_type = expr.GetExpressionType(); if (expression_type == ExpressionType::OPERATOR_TRY || expression_type == ExpressionType::OPERATOR_HAS_ERROR) { @@ -211,16 +232,18 @@ void ExpressionExecutor::Execute(const BoundOperatorExpression &expr, Expression result.Reference(intermediate); } } else if (expression_type == ExpressionType::OPERATOR_COALESCE) { - SelectionVector sel_a(count); - SelectionVector sel_b(count); - SelectionVector slice_sel(count); - SelectionVector result_sel(count); + auto &coalesce = state->Cast(); + coalesce.Prepare(count); + auto &sel_a = coalesce.selections[0]; + auto &sel_b = coalesce.selections[1]; + auto &slice_sel = coalesce.selections[2]; + auto &result_sel = coalesce.selections[3]; SelectionVector *next_sel = &sel_a; const SelectionVector *current_sel = sel; idx_t remaining_count = count; idx_t next_count; for (idx_t child = 0; child < expr.GetChildren().size(); child++) { - Vector vector_to_check(expr.GetChildren()[child]->GetReturnType()); + auto &vector_to_check = coalesce.intermediate_chunk.data[child]; Execute(*expr.GetChildren()[child], state->child_states[child].get(), current_sel, remaining_count, vector_to_check); diff --git a/src/duckdb/src/execution/index/art/art.cpp b/src/duckdb/src/execution/index/art/art.cpp index adb87de0d..44b43606b 100644 --- a/src/duckdb/src/execution/index/art/art.cpp +++ b/src/duckdb/src/execution/index/art/art.cpp @@ -275,12 +275,18 @@ unique_ptr ART::TryInitializeScan(const Expression &expr, const return nullptr; } + // A NULL bound matches no rows. + if (lower_bound.Cast().GetValue().IsNull() || + upper_bound.Cast().GetValue().IsNull()) { + return nullptr; + } + auto lower_inclusive = BoundBetweenExpression::LowerInclusive(between); auto upper_inclusive = BoundBetweenExpression::UpperInclusive(between); low_value = lower_bound.Cast().GetValue(); low_comparison_type = lower_inclusive ? ExpressionType::COMPARE_GREATERTHANOREQUALTO : ExpressionType::COMPARE_GREATERTHAN; - high_value = (upper_bound.Cast()).GetValue(); + high_value = upper_bound.Cast().GetValue(); high_comparison_type = upper_inclusive ? ExpressionType::COMPARE_LESSTHANOREQUALTO : ExpressionType::COMPARE_LESSTHAN; } else { diff --git a/src/duckdb/src/execution/index/art/art_builder.cpp b/src/duckdb/src/execution/index/art/art_builder.cpp index 8eb83cd19..060f7a489 100644 --- a/src/duckdb/src/execution/index/art/art_builder.cpp +++ b/src/duckdb/src/execution/index/art/art_builder.cpp @@ -1,7 +1,8 @@ #include "duckdb/execution/index/art/art_builder.hpp" +#include "duckdb/common/optional.hpp" #include "duckdb/execution/index/art/art_key.hpp" -#include "duckdb/execution/index/art/prefix.hpp" +#include "duckdb/execution/index/art/prefix_handle.hpp" #include "duckdb/execution/index/art/leaf.hpp" #include "duckdb/execution/index/art/art_operator.hpp" @@ -35,9 +36,16 @@ ARTConflictType ARTBuilder::Build() { return ARTConflictType::CONSTRAINT; } + // Create the prefix, if any. The tail stays pinned while we fill its child. reference node_ptr_ref(entry.node_ptr); + optional tail; auto count = UnsafeNumericCast(start.len - prefix_depth); - Prefix::New(art, node_ptr_ref, start, prefix_depth, count); + if (count != 0) { + auto chain = PrefixHandle::New(art, start, prefix_depth, count); + entry.node_ptr = chain.root_ptr; + tail = std::move(chain.tail); + node_ptr_ref = tail->Child(art); + } // Inline the row ID. if (row_id_count == 1) { @@ -56,10 +64,16 @@ ARTConflictType ARTBuilder::Build() { continue; } - // Create the prefix. Returns early, if the prefix_length is zero. + // Create the prefix, if any. The tail stays pinned while we fill its child. reference node_ptr_ref(entry.node_ptr); + optional tail; auto prefix_length = entry.depth - prefix_depth; - Prefix::New(art, node_ptr_ref, start, prefix_depth, prefix_length); + if (prefix_length != 0) { + auto chain = PrefixHandle::New(art, start, prefix_depth, prefix_length); + entry.node_ptr = chain.root_ptr; + tail = std::move(chain.tail); + node_ptr_ref = tail->Child(art); + } vector child_offsets; child_offsets.emplace_back(entry.start); diff --git a/src/duckdb/src/execution/index/art/prefix.cpp b/src/duckdb/src/execution/index/art/prefix.cpp index 4feaeab20..44e51f417 100644 --- a/src/duckdb/src/execution/index/art/prefix.cpp +++ b/src/duckdb/src/execution/index/art/prefix.cpp @@ -2,7 +2,6 @@ #include "duckdb/common/swap.hpp" #include "duckdb/execution/index/art/art.hpp" -#include "duckdb/execution/index/art/art_key.hpp" #include "duckdb/execution/index/art/base_leaf.hpp" #include "duckdb/execution/index/art/base_node.hpp" #include "duckdb/execution/index/art/const_prefix_handle.hpp" @@ -54,20 +53,6 @@ Prefix Prefix::NewInternal(ART &art, NodePtr &node_ptr, const data_ptr_t data, c return prefix; } -void Prefix::New(ART &art, reference &node_ptr_ref, const ARTKey &key, const idx_t depth, idx_t count) { - idx_t offset = 0; - - while (count) { - auto min = MinValue(UnsafeNumericCast(art.PrefixCount()), count); - auto this_count = UnsafeNumericCast(min); - auto prefix = NewInternal(art, node_ptr_ref, key.data, this_count, offset + depth); - - node_ptr_ref = *prefix.child_slot; - offset += this_count; - count -= this_count; - } -} - void Prefix::Reduce(ART &art, NodePtr &node_ptr, const idx_t pos) { D_ASSERT(node_ptr.HasMetadata()); D_ASSERT(pos < art.PrefixCount()); diff --git a/src/duckdb/src/execution/join_hashtable.cpp b/src/duckdb/src/execution/join_hashtable.cpp index 0f85ed5b4..52887954a 100644 --- a/src/duckdb/src/execution/join_hashtable.cpp +++ b/src/duckdb/src/execution/join_hashtable.cpp @@ -1,3 +1,5 @@ +#include + #include "duckdb/execution/join_hashtable.hpp" #include "duckdb/common/enums/join_type.hpp" @@ -21,6 +23,41 @@ namespace duckdb { +struct JoinHashTable::BuildState { + explicit BuildState(JoinHashTable &ht) : selection(STANDARD_VECTOR_SIZE) { + auto &allocator = ht.buffer_manager.GetBufferAllocator(); + auto &types = ht.layout_ptr->GetTypes(); + source.Initialize(allocator, types, vector(types.size(), false)); + vector initialize_indices(types.size(), false); + for (idx_t i = 0; i < ht.build_types.size(); i++) { + initialize_indices[ht.condition_types.size() + i] = ht.GetDictSurvivingColumn(i) != nullptr; + } + dictionary_indices.Initialize(allocator, types, initialize_indices); + hashes.Initialize(allocator, {LogicalType::HASH, LogicalType::HASH}); + } + + DataChunk source; + DataChunk hashes; + DataChunk dictionary_indices; + SelectionVector selection; +}; + +//! Maps matched build rows to output positions; remaining output positions contain NULL. +struct JoinBuildSelection { + JoinBuildSelection(const SelectionVector &rows, idx_t count) + : JoinBuildSelection(rows, count, *FlatVector::IncrementalSelectionVector(), count) { + } + JoinBuildSelection(const SelectionVector &rows, idx_t match_count, const SelectionVector &output, idx_t count) + : rows(rows), match_count(match_count), output(output), count(count) { + D_ASSERT(match_count <= count); + } + + const SelectionVector &rows; + idx_t match_count; + const SelectionVector &output; + idx_t count; +}; + using ValidityBytes = JoinHashTable::ValidityBytes; using ScanStructure = JoinHashTable::ScanStructure; using ProbeSpill = JoinHashTable::ProbeSpill; @@ -34,7 +71,7 @@ const buffer_ptr &DictionaryOwnershipCache::GetEntry(idx_t colu } auto &local_entry = entries[column]; if (local_entry.get() != entry.get()) { - auto owner = make_shared_ptr(entry); + auto owner = make_buffer(entry); local_entry = buffer_ptr(owner, entry.get()); } return local_entry; @@ -50,22 +87,20 @@ void DictionaryOwnershipCache::Reset() { } JoinHashTable::SharedState::SharedState() - : salt_v(LogicalType::UBIGINT), keys_to_compare_sel(STANDARD_VECTOR_SIZE), keys_no_match_sel(STANDARD_VECTOR_SIZE) { + : keys_to_compare_sel(STANDARD_VECTOR_SIZE), keys_no_match_sel(STANDARD_VECTOR_SIZE) { } JoinHashTable::ProbeState::ProbeState() : SharedState(), hashes(LogicalType::HASH), ht_offsets_and_salts_v(LogicalType::UBIGINT), - hashes_dense_v(LogicalType::HASH), non_empty_sel(STANDARD_VECTOR_SIZE) { + hashes_dense_v(LogicalType::HASH) { } -JoinHashTable::ProbeDictionaryState::ProbeDictionaryState() - : new_dictionary_pointers(LogicalType::POINTER), unique_entries(STANDARD_VECTOR_SIZE), - match_sel(STANDARD_VECTOR_SIZE) { +JoinHashTable::ProbeDictionaryState::ProbeDictionaryState() : unique_entries(STANDARD_VECTOR_SIZE) { } JoinHashTable::InsertState::InsertState(const JoinHashTable &ht) - : SharedState(), remaining_sel(STANDARD_VECTOR_SIZE), key_match_sel(STANDARD_VECTOR_SIZE), - rhs_row_locations(LogicalType::POINTER) { + : SharedState(), salt_v(LogicalType::UBIGINT), remaining_sel(STANDARD_VECTOR_SIZE), + key_match_sel(STANDARD_VECTOR_SIZE), rhs_row_locations(LogicalType::POINTER) { ht.data_collection->InitializeChunk(lhs_data, ht.equality_predicate_columns); ht.data_collection->InitializeChunkState(chunk_state, ht.equality_predicate_columns); } @@ -76,7 +111,7 @@ JoinHashTable::JoinHashTable(ClientContext &context_p, const PhysicalOperator &o unique_ptr residual_p, optional_ptr predicate_ptr, const vector &output_in_probe) : context(context_p), op(op_p), buffer_manager(BufferManager::GetBufferManager(context)), conditions(conditions_p), - build_types(std::move(btypes)), output_columns(output_columns_p), entry_size(0), tuple_size(0), + build_types(std::move(btypes)), output_columns(output_columns_p), tuple_size(0), vfound(Value::BOOLEAN(false), count_t(STANDARD_VECTOR_SIZE)), join_type(type_p), finalized(false), has_null(false), residual_predicate(predicate_ptr), radix_bits(initial_radix_bits) { // store residual predicate information @@ -132,11 +167,13 @@ void JoinHashTable::FinishInitWithLayout(shared_ptr published_l dict_info = std::move(dict_info_p); // A directory entry must identify an entire equality group. if (equality_types.size() == 1) { - const auto type = !insert_duplicate_keys && mark_join_info.correlated_types.empty() + const auto track_matches = (join_type == JoinType::RIGHT_SEMI || join_type == JoinType::RIGHT_ANTI) && + non_equality_predicates.empty() && !residual_predicate; + const auto type = track_matches || (!insert_duplicate_keys && mark_join_info.correlated_types.empty()) ? PerfectHashJoinTable::Type::BITMAP : PerfectHashJoinTable::Type::ROWS; - perfect_hash_candidate = - PerfectHashJoinTable::Create(equality_types[0].InternalType(), type, null_values_are_equal[0]); + perfect_hash_candidate = PerfectHashJoinTable::Create(equality_types[0].InternalType(), type, + null_values_are_equal[0], track_matches); } // Initialize the row matcher that are used for filtering during the probing only if there are non-equality preds @@ -161,15 +198,11 @@ void JoinHashTable::FinishInitWithLayout(shared_ptr published_l const auto &offsets = layout_ptr->GetOffsets(); tuple_size = offsets[condition_types.size() + build_types.size()]; pointer_offset = offsets.back(); - entry_size = layout_ptr->GetRowWidth(); data_collection = make_uniq(buffer_manager, layout_ptr, MemoryTag::HASH_TABLE, nullptr, context); sink_collection = make_uniq(buffer_manager, layout_ptr, MemoryTag::HASH_TABLE, radix_bits, layout_ptr->ColumnCount() - 1, context); - - dead_end = make_unsafe_uniq_array_uninitialized(layout_ptr->GetRowWidth()); - memset(dead_end.get(), 0, layout_ptr->GetRowWidth()); } JoinHashTable::~JoinHashTable() { @@ -210,9 +243,14 @@ void JoinHashTable::Merge(JoinHashTable &other) { } } - // every thread-local table shares this operator's filter - a different one here would mean its rows + // Every thread-local table shares this operator's filters - a different one here would mean its rows // never reached the filter that gets published - D_ASSERT(!other.bloom_filter || bloom_filter.get() == other.bloom_filter.get()); +#ifdef DEBUG + for (idx_t key_idx = 0; key_idx < other.bloom_filters.size(); key_idx++) { + D_ASSERT(!other.bloom_filters[key_idx] || + (key_idx < bloom_filters.size() && bloom_filters[key_idx] == other.bloom_filters[key_idx])); + } +#endif sink_collection->Combine(*other.sink_collection); @@ -479,56 +517,50 @@ static uint8_t DictIndexWidth(idx_t dict_size) { return sizeof(uint32_t); } -//! Materialise a flat width-INDEX_T index vector (allocation owned by `buffers`, view in `vectors`) from the -//! dict sel. UnsafeNumericCast is safe: the publisher sized the width to the dictionary, so every index fits. template -static void ScatterDictIndices(const SelectionVector &dict_sel, idx_t count, const LogicalType &index_type, - Allocator &allocator, vector &buffers, vector &vectors) { - buffers.emplace_back(allocator.Allocate(count * sizeof(INDEX_T))); - vectors.emplace_back(index_type, buffers.back().get(), count); - auto idx_data = FlatVector::GetDataMutable(vectors.back()); +static void ScatterDictIndices(const SelectionVector &dict_sel, idx_t count, Vector &result) { + auto idx_data = FlatVector::GetDataMutable(result); for (idx_t r = 0; r < count; r++) { idx_data[r] = UnsafeNumericCast(dict_sel.get_index(r)); } } -//! Dispatch on the chosen index width (1/2/4 B) to the matching templated ScatterDictIndices -static void ScatterDictIndices(uint8_t index_width, const SelectionVector &dict_sel, idx_t count, Allocator &allocator, - vector &buffers, vector &vectors) { +static void ScatterDictIndices(uint8_t index_width, const SelectionVector &dict_sel, idx_t count, Vector &result) { switch (index_width) { case sizeof(uint8_t): - ScatterDictIndices(dict_sel, count, LogicalType::UTINYINT, allocator, buffers, vectors); + ScatterDictIndices(dict_sel, count, result); break; case sizeof(uint16_t): - ScatterDictIndices(dict_sel, count, LogicalType::USMALLINT, allocator, buffers, vectors); + ScatterDictIndices(dict_sel, count, result); break; default: - ScatterDictIndices(dict_sel, count, LogicalType::UINTEGER, allocator, buffers, vectors); + ScatterDictIndices(dict_sel, count, result); break; } } //! Load the per-match dict index (width INDEX_T) from each matched row's slot at col_offset into build_sel_vec template -static void LoadDictIndices(const data_ptr_t *ptrs, const SelectionVector &ptr_sel, idx_t count, idx_t col_offset, +static void LoadDictIndices(const data_ptr_t *ptrs, const JoinBuildSelection &selection, idx_t col_offset, SelectionVector &build_sel_vec) { - for (idx_t i = 0; i < count; i++) { - build_sel_vec.set_index(i, Load(ptrs[ptr_sel.get_index(i)] + col_offset)); + for (idx_t i = 0; i < selection.match_count; i++) { + build_sel_vec.set_index(selection.output.get_index(i), + Load(ptrs[selection.rows.get_index(i)] + col_offset)); } } //! Dispatch on the chosen index width (1/2/4 B) to the matching templated LoadDictIndices -static void LoadDictIndices(uint8_t index_width, const data_ptr_t *ptrs, const SelectionVector &ptr_sel, idx_t count, +static void LoadDictIndices(uint8_t index_width, const data_ptr_t *ptrs, const JoinBuildSelection &selection, idx_t col_offset, SelectionVector &build_sel_vec) { switch (index_width) { case sizeof(uint8_t): - LoadDictIndices(ptrs, ptr_sel, count, col_offset, build_sel_vec); + LoadDictIndices(ptrs, selection, col_offset, build_sel_vec); break; case sizeof(uint16_t): - LoadDictIndices(ptrs, ptr_sel, count, col_offset, build_sel_vec); + LoadDictIndices(ptrs, selection, col_offset, build_sel_vec); break; default: - LoadDictIndices(ptrs, ptr_sel, count, col_offset, build_sel_vec); + LoadDictIndices(ptrs, selection, col_offset, build_sel_vec); break; } } @@ -605,7 +637,7 @@ DictSurvivingColumn JoinHashTable::CreateDictSurvivingColumn(const Vector &incom const auto &upstream_child = DictionaryVector::Child(incoming); const auto upstream_count = upstream_child.size(); // GetDictSurvivingIndexWidth sized the width to upstream_count + 1 - D_ASSERT(upstream_count < (idx_t(1) << (8 * index_width))); + D_ASSERT(upstream_count < (static_cast(1) << (8 * index_width))); DictSurvivingColumn column; column.index_width = index_width; // CreateReusableGlobalDictionary assigns a fresh id: this is a different dictionary than the upstream one (one @@ -620,8 +652,7 @@ DictSurvivingColumn JoinHashTable::CreateDictSurvivingColumn(const Vector &incom } void JoinHashTable::EncodeDictSurvivingColumn(const DictSurvivingColumn &column, idx_t build_col_idx, - const Vector &incoming, idx_t count, vector &buffers, - vector &vectors) { + const Vector &incoming, idx_t count, Vector &result) { if (incoming.GetVectorType() == VectorType::DICTIONARY_VECTOR) { // Slot was narrowed against one specific upstream dictionary; a different one would scatter foreign indices. if (DictionaryVector::DictionaryId(incoming) != column.upstream_id) { @@ -630,15 +661,14 @@ void JoinHashTable::EncodeDictSurvivingColumn(const DictSurvivingColumn &column, static_cast(build_col_idx)); } // Indices are < upstream size by construction, and the publisher sized the width to upstream size + 1 - ScatterDictIndices(column.index_width, DictionaryVector::SelVector(incoming), count, - buffer_manager.GetBufferAllocator(), buffers, vectors); + ScatterDictIndices(column.index_width, DictionaryVector::SelVector(incoming), count, result); return; } if (!VectorOperations::HasNotNull(incoming)) { // e.g. the unmatched-build scan of an upstream FULL/RIGHT join: every row stores the reserved NULL index const auto null_index = Value::Numeric(DictSurvivingInfo::IndexType(column.index_width), NumericCast(column.NullIndex())); - vectors.emplace_back(null_index, count_t(count)); + result.Reference(null_index, count_t(count)); return; } // There is no fallback for values that are not in the pinned dictionary. Throw, not D_ASSERT: storing the @@ -684,6 +714,13 @@ static bool MarkJoinKeysHaveNull(DataChunk &keys, optional_ptr rows_with_n return has_null; } +JoinHashTable::BuildState &JoinHashTable::GetBuildState() { + if (!build_state) { + build_state = make_uniq(*this); + } + return *build_state; +} + void JoinHashTable::Build(PartitionedTupleDataAppendState &append_state, DataChunk &keys, DataChunk &payload) { D_ASSERT(!finalized); D_ASSERT(keys.size() == payload.size()); @@ -721,17 +758,22 @@ void JoinHashTable::Build(PartitionedTupleDataAppendState &append_state, DataChu } // build a chunk to append to the data collection [keys, payload, (optional "found" boolean), hash] - DataChunk source_chunk; - source_chunk.InitializeEmpty(layout_ptr->GetTypes()); + auto &state = GetBuildState(); + state.source.Reset(); + state.hashes.Reset(); + state.dictionary_indices.Reset(); + auto &source_chunk = state.source; + struct ReleaseSource { + DataChunk &source; + ~ReleaseSource() { + source.Reset(); + } + } release {source_chunk}; for (idx_t i = 0; i < keys.ColumnCount(); i++) { source_chunk.data[i].Reference(keys.data[i]); } idx_t col_offset = keys.ColumnCount(); D_ASSERT(build_types.size() == payload.ColumnCount()); - // Scratch index vectors for narrowed columns, allocated via the buffer manager so the bytes are accounted. - // buffers own the bytes, vectors are flat views; both must outlive the ToUnifiedFormat / AppendUnified below. - vector dict_idx_buffers; - vector dict_idx_vectors; for (idx_t i = 0; i < payload.ColumnCount(); i++) { auto &incoming = payload.data[i]; auto dict_column = GetDictSurvivingColumn(i); @@ -740,8 +782,9 @@ void JoinHashTable::Build(PartitionedTupleDataAppendState &append_state, DataChu continue; } // Narrowed column: store dictionary indices (or the reserved NULL index) at the chosen width, not the value - EncodeDictSurvivingColumn(*dict_column, i, incoming, payload.size(), dict_idx_buffers, dict_idx_vectors); - source_chunk.data[col_offset + i].Reference(dict_idx_vectors.back()); + auto &indices = state.dictionary_indices.data[col_offset + i]; + EncodeDictSurvivingColumn(*dict_column, i, incoming, payload.size(), indices); + source_chunk.data[col_offset + i].Reference(indices); } col_offset += payload.ColumnCount(); if (PropagatesBuildSide(join_type)) { @@ -749,7 +792,7 @@ void JoinHashTable::Build(PartitionedTupleDataAppendState &append_state, DataChu source_chunk.data[col_offset].Reference(vfound); col_offset++; } - Vector hash_values(LogicalType::HASH); + auto &hash_values = state.hashes.data[0]; source_chunk.data[col_offset].Reference(hash_values); source_chunk.SetChildCardinality(keys.size()); @@ -758,7 +801,7 @@ void JoinHashTable::Build(PartitionedTupleDataAppendState &append_state, DataChu // prepare the keys for processing optional_ptr current_sel; - SelectionVector sel(STANDARD_VECTOR_SIZE); + auto &sel = state.selection; idx_t added_count = PrepareKeys(keys, append_state.chunk_state.vector_data, current_sel, sel, true); if (added_count < keys.size()) { has_null = true; @@ -770,8 +813,28 @@ void JoinHashTable::Build(PartitionedTupleDataAppendState &append_state, DataChu // hash the keys and obtain an entry in the list // note that we only hash the keys used in the equality comparison Hash(keys, *current_sel, added_count, hash_values); - if (bloom_filter) { - bloom_filter->InsertHashes(hash_values, *current_sel, added_count); + if (!bloom_filters.empty() && HasSingleEqualityKey()) { + // The hash-table hashes already describe this one key. + auto &filter = bloom_filters[0]; + if (filter) { + filter->InsertHashes(hash_values, *current_sel, added_count); + } + } else if (!bloom_filters.empty()) { + // the per-key-column filters of an external join with several equality keys + auto &key_hashes = state.hashes.data[1]; + for (idx_t key_idx = 0; key_idx < bloom_filters.size(); key_idx++) { + auto &filter = bloom_filters[key_idx]; + if (!filter) { + continue; + } + D_ASSERT(!filter->IsSealed()); + if (added_count == keys.size()) { + VectorOperations::Hash(keys.data[key_idx], key_hashes, added_count); + } else { + VectorOperations::Hash(keys.data[key_idx], key_hashes, *current_sel, added_count); + } + filter->InsertHashes(key_hashes, *current_sel, added_count); + } } // Re-reference and ToUnifiedFormat the hash column after computing it @@ -911,9 +974,6 @@ static inline void InsertMatchesAndIncrementMisses(unsafe_optional_ptr> entries, Ve void JoinHashTable::InsertHashes(Vector &hashes_v, TupleDataChunkState &chunk_state, InsertState &insert_state, bool parallel) { // a sealed filter was accumulated during Sink and is already complete; only a finalize-built one fills here - if (bloom_filter && !bloom_filter->IsSealed()) { - bloom_filter->InsertHashes(hashes_v); + if (!bloom_filters.empty() && HasSingleEqualityKey()) { + auto &filter = bloom_filters[0]; + if (filter && !filter->IsSealed()) { + filter->InsertHashes(hashes_v); + } } auto atomic_entries = GetAtomicEntries(); auto &row_locations = chunk_state.row_locations; @@ -1110,43 +1173,43 @@ idx_t JoinHashTable::GetPrefixRangeBuildStateSize() const { } void JoinHashTable::SetBuildBloomFilter(idx_t key_idx) { - if (HasSingleEqualityKey()) { - D_ASSERT(key_idx == 0); - should_build_bloom_filter = true; + D_ASSERT(key_idx < equality_predicate_columns.size()); + should_build_bloom_filters.resize(equality_predicate_columns.size(), false); + should_build_bloom_filters[key_idx] = true; +} + +void JoinHashTable::InitializeBloomFilters(const vector &key_idxs, idx_t build_estimate, idx_t memory_budget) { + bloom_filters.clear(); + if (key_idxs.empty()) { return; } - should_build_key_bloom_filters.resize(equality_predicate_columns.size(), false); - should_build_key_bloom_filters[key_idx] = true; + bloom_filters.resize(equality_predicate_columns.size()); + // The key columns share one bitmap budget. + const auto key_budget = memory_budget / key_idxs.size(); + for (auto &key_idx : key_idxs) { + auto &filter = bloom_filters[key_idx]; + filter = make_shared_ptr(); + filter->Initialize(context, build_estimate, key_budget); + } } -shared_ptr JoinHashTable::GetBloomFilter(idx_t key_idx) { - if (HasSingleEqualityKey()) { - D_ASSERT(key_idx == 0); - return bloom_filter; - } - return key_idx < key_bloom_filters.size() ? key_bloom_filters[key_idx] : nullptr; +shared_ptr JoinHashTable::GetBloomFilter(idx_t key_idx) const { + return key_idx < bloom_filters.size() ? bloom_filters[key_idx] : nullptr; } -void JoinHashTable::SealBloomFilter() { - if (bloom_filter) { - bloom_filter->Seal(context); - } - for (auto &key_bloom_filter : key_bloom_filters) { - if (key_bloom_filter && !key_bloom_filter->IsSealed()) { - key_bloom_filter->Seal(context); +void JoinHashTable::SealBloomFilters() { + for (auto &filter : bloom_filters) { + if (filter && !filter->IsSealed()) { + filter->Seal(context); } } } bool JoinHashTable::HasPublishableBloomFilter(idx_t key_idx) const { - if (HasSingleEqualityKey()) { - D_ASSERT(key_idx == 0); - return HasPublishableBloomFilter(); - } - if (key_idx >= key_bloom_filters.size()) { + if (key_idx >= bloom_filters.size()) { return false; } - auto &filter = key_bloom_filters[key_idx]; + auto &filter = bloom_filters[key_idx]; return filter && filter->IsSealed() && filter->IsUseful(); } @@ -1192,7 +1255,7 @@ void JoinHashTable::MergePrefixRangeBuildState(PrefixRangeBuildStates &states) { D_ASSERT(states.size() == prefix_range_filters.size()); for (idx_t key_idx = 0; key_idx < prefix_range_filters.size(); key_idx++) { if (prefix_range_filters[key_idx]) { - prefix_range_filters[key_idx]->MergeBuildState(*states[key_idx]); + prefix_range_filters[key_idx]->MergeBuildState(std::move(states[key_idx])); } } } @@ -1208,8 +1271,8 @@ JoinHashTable::KeyFilterBuildScratch::KeyFilterBuildScratch(JoinHashTable &ht) : void JoinHashTable::InsertKeyBloomFilterChunk(TupleDataChunkState &chunk_state, idx_t count, KeyFilterBuildScratch &scratch) { scratch.keys.Reset(); - for (idx_t key_idx = 0; key_idx < key_bloom_filters.size(); key_idx++) { - auto &filter = key_bloom_filters[key_idx]; + for (idx_t key_idx = 0; key_idx < bloom_filters.size(); key_idx++) { + auto &filter = bloom_filters[key_idx]; if (!filter || filter->IsSealed()) { continue; } @@ -1243,10 +1306,6 @@ bool JoinHashTable::TryInitializePerfectHashTable() { return perfect_hash_table != nullptr; } -bool JoinHashTable::SupportsCompressedProbe() const { - return !perfect_hash_table || perfect_hash_table->GetType() == PerfectHashJoinTable::Type::ROWS; -} - void JoinHashTable::AllocatePointerTable(bool use_radix_layout) { if (perfect_hash_table) { hash_map.Reset(); @@ -1255,9 +1314,10 @@ void JoinHashTable::AllocatePointerTable(bool use_radix_layout) { } else { AllocateHashMap(use_radix_layout); } + const auto lookup_size = perfect_hash_table ? perfect_hash_table->SizeInBytes() : capacity * sizeof(uint64_t); DUCKDB_LOG(context, PhysicalOperatorLogType, op, "JoinHashTable", "Build", {{"rows", to_string(data_collection->Count())}, - {"size", to_string(data_collection->SizeInBytes() + capacity * sizeof(uint64_t))}}); + {"size", to_string(data_collection->SizeInBytes() + lookup_size)}}); } void JoinHashTable::AllocateHashMap(bool use_radix_layout) { @@ -1269,18 +1329,19 @@ void JoinHashTable::AllocateHashMap(bool use_radix_layout) { throw InternalException("Hashtable capacity exceeds 48-bit limit (2^48 - 1)"); } - if (should_build_bloom_filter && (!bloom_filter || bloom_filter->IsSealed())) { - // (re)create the finalize-built filter now that the actual build count is known - bloom_filter = recycled_bloom_filter ? std::move(recycled_bloom_filter) : make_shared_ptr(); - bloom_filter->Initialize(context, MaxValue(Count(), 1)); + // filters accumulated during Sink stay in place + if (bloom_filters.size() < should_build_bloom_filters.size()) { + bloom_filters.resize(should_build_bloom_filters.size()); } - key_bloom_filters.resize(should_build_key_bloom_filters.size()); - // The key columns share one bitmap budget with prefix-range filters. - for (idx_t key_idx = 0; key_idx < should_build_key_bloom_filters.size(); key_idx++) { - auto &filter = key_bloom_filters[key_idx]; - if (should_build_key_bloom_filters[key_idx] && (!filter || filter->IsSealed())) { - filter = make_shared_ptr(); - filter->Initialize(context, MaxValue(Count(), 1), key_bloom_filter_budget); + const auto max_bitmap_bytes = HasSingleEqualityKey() ? NumericLimits::Maximum() : bloom_filter_budget; + for (idx_t key_idx = 0; key_idx < should_build_bloom_filters.size(); key_idx++) { + auto &filter = bloom_filters[key_idx]; + if (should_build_bloom_filters[key_idx] && (!filter || filter->IsSealed())) { + filter = HasSingleEqualityKey() && recycled_bloom_filter ? std::move(recycled_bloom_filter) + : make_shared_ptr(); + // Pointer-table initialization clears these buffers before any finalize task inserts keys. + filter->Initialize(context, MaxValue(Count(), 1), max_bitmap_bytes, + BloomFilter::Initialization::DEFERRED); } } @@ -1314,6 +1375,11 @@ void JoinHashTable::InitializePointerTable(idx_t entry_idx_from, idx_t entry_idx // initialize HT with all-zero entries auto entries = GetEntries(); std::fill_n(entries.get() + entry_idx_from, entry_idx_to - entry_idx_from, ht_entry_t()); + for (auto &filter : bloom_filters) { + if (filter) { + filter->InitializeRange(entry_idx_from, entry_idx_to, capacity); + } + } } void JoinHashTable::Finalize(idx_t chunk_idx_from, idx_t chunk_idx_to, bool parallel, @@ -1324,8 +1390,8 @@ void JoinHashTable::Finalize(idx_t chunk_idx_from, idx_t chunk_idx_to, bool para TupleDataChunkIterator iterator(*data_collection, TupleDataPinProperties::KEEP_EVERYTHING_PINNED, chunk_idx_from, chunk_idx_to, false); if (perfect_hash_table) { - // Perfect hash joins have a single key and no per-key Bloom filters. - D_ASSERT(key_bloom_filters.empty()); + // Perfect hash joins have one key; any Sink-built Bloom filter is already complete. + D_ASSERT(HasSingleEqualityKey()); unique_ptr key_filter_scratch; if (prefix_range_states) { key_filter_scratch = make_uniq(*this); @@ -1333,6 +1399,7 @@ void JoinHashTable::Finalize(idx_t chunk_idx_from, idx_t chunk_idx_to, bool para bool has_chains = false; do { auto &chunk_state = iterator.GetChunkState(); + InitializeMatchFlags(chunk_state.row_locations); has_chains |= perfect_hash_table->Insert(chunk_state.row_locations, *layout_ptr, pointer_offset, parallel); if (prefix_range_states) { InsertPrefixRangeChunk(chunk_state, iterator.GetCurrentChunkCount(), *prefix_range_states, @@ -1349,12 +1416,14 @@ void JoinHashTable::Finalize(idx_t chunk_idx_from, idx_t chunk_idx_to, bool para Vector hashes(LogicalType::HASH); InsertState insert_state(*this); unique_ptr key_filter_scratch; - if (!key_bloom_filters.empty() || prefix_range_states) { + const bool build_key_bloom_filters = !bloom_filters.empty() && !HasSingleEqualityKey(); + if (build_key_bloom_filters || prefix_range_states) { key_filter_scratch = make_uniq(*this); } do { const auto count = iterator.GetCurrentChunkCount(); TupleDataChunkState &chunk_state = iterator.GetChunkState(); + InitializeMatchFlags(chunk_state.row_locations); { auto hash_data = FlatVector::Writer(hashes, count_t(count)); @@ -1363,7 +1432,7 @@ void JoinHashTable::Finalize(idx_t chunk_idx_from, idx_t chunk_idx_to, bool para } } InsertHashes(hashes, chunk_state, insert_state, parallel); - if (!key_bloom_filters.empty()) { + if (build_key_bloom_filters) { InsertKeyBloomFilterChunk(chunk_state, count, *key_filter_scratch); } if (prefix_range_states) { @@ -1440,9 +1509,6 @@ bool JoinHashTable::TryProbePerfectHashTable(ScanStructure &scan_structure, Data void JoinHashTable::Probe(ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, ProbeState &probe_state, optional_ptr precomputed_hashes) { - if (TryProbePerfectHashTable(scan_structure, keys)) { - return; - } // Compressed probes resolve distinct keys instead of using hashes for the full chunk. if (probe_state.dict_state && !precomputed_hashes) { auto &lhs_key = keys.data[0]; @@ -1453,6 +1519,9 @@ void JoinHashTable::Probe(ScanStructure &scan_structure, DataChunk &keys, TupleD return; } } + if (TryProbePerfectHashTable(scan_structure, keys)) { + return; + } optional_ptr current_sel; InitializeScanStructure(scan_structure, keys, key_state, current_sel); @@ -1465,6 +1534,10 @@ void JoinHashTable::Probe(ScanStructure &scan_structure, DataChunk &keys, TupleD bool JoinHashTable::TryProbeDictionary(ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, ProbeState &probe_state) { + // Direct membership and dictionary loops do not need cached row resolution. + if (GetProbeResultType() != PerfectHashJoinTable::Type::ROWS) { + return false; + } static constexpr idx_t MAX_DICTIONARY_SIZE_THRESHOLD = 20000; static constexpr idx_t DICTIONARY_THRESHOLD = 2; @@ -1492,7 +1565,6 @@ bool JoinHashTable::TryProbeDictionary(ScanStructure &scan_structure, DataChunk return false; } if (dict_size == 0) { - // the cache below is never allocated for an empty dictionary - avoid dereferencing a null Vector return false; } @@ -1504,13 +1576,12 @@ bool JoinHashTable::TryProbeDictionary(ScanStructure &scan_structure, DataChunk if (dict_state.dictionary_id.empty() || dict_state.dictionary_id != dictionary_id) { // new dictionary - initialize the per-id cache if (dict_size > dict_state.capacity) { - dict_state.dictionary_pointers = make_uniq(LogicalType::POINTER, dict_size); + dict_state.dictionary_results = make_unsafe_uniq_array(dict_size); dict_state.found_entry = make_unsafe_uniq_array(dict_size); dict_state.capacity = dict_size; } memset(dict_state.found_entry.get(), 0, dict_size * sizeof(bool)); - // zero the cache - an unresolved slot reads back as nullptr, the miss sentinel - memset(FlatVector::GetDataMutable(*dict_state.dictionary_pointers), 0, dict_size * sizeof(data_ptr_t)); + memset(dict_state.dictionary_results.get(), 0, dict_size * sizeof(uint64_t)); dict_state.dictionary_id = dictionary_id; dict_state.resolved_count = 0; // storage dictionaries reserve a NULL sentinel slot that non-NULL probe rows never @@ -1552,52 +1623,16 @@ bool JoinHashTable::TryProbeDictionary(ScanStructure &scan_structure, DataChunk auto &unique_values = dict_state.unique_values; if (unique_values.ColumnCount() == 0) { unique_values.InitializeEmpty(vector {equality_types[0]}); - TupleDataCollection::InitializeChunkState(dict_state.unique_key_state, {equality_types[0]}); } unique_values.data[0].Slice(dictionary_vector, unique_entries, unique_count); unique_values.CheckCardinality(unique_count); - TupleDataCollection::ToUnifiedFormat(dict_state.unique_key_state, unique_values); - - idx_t count = unique_count; - GetRowPointers(unique_values, dict_state.unique_key_state, probe_state, nullptr, nullptr, count, - dict_state.new_dictionary_pointers, dict_state.match_sel, false); - - // remap hits from position to dict slot; missed slots stay nullptr from the rebind memset - const auto new_dict_ptrs = FlatVector::GetData(dict_state.new_dictionary_pointers); - auto unique_dict_ptrs = FlatVector::GetDataMutable(*dict_state.dictionary_pointers); - for (idx_t i = 0; i < count; i++) { - const auto position = dict_state.match_sel.get_index(i); - const auto dict_idx = unique_entries.get_index(position); - unique_dict_ptrs[dict_idx] = new_dict_ptrs[position]; - } + ResolveProbeKeys(scan_structure, unique_values, probe_state, {dict_state.dictionary_results.get(), dict_size}, + unique_entries); } - // fan out the cache into the scan_structure shape that Probe() produces - scan_structure.is_null = false; - scan_structure.finished = false; - if (join_type != JoinType::INNER) { - memset(scan_structure.found_match.get(), 0, sizeof(bool) * STANDARD_VECTOR_SIZE); - } - TupleDataCollection::ToUnifiedFormat(key_state, keys); - optional_ptr current_sel; - const idx_t prepared_count = - PrepareKeys(keys, key_state.vector_data, current_sel, scan_structure.sel_vector, false); - scan_structure.has_null_value_filter = prepared_count < keys.size(); - - auto scan_structure_ptrs = FlatVector::GetDataMutable(scan_structure.pointers); - const auto unique_dict_ptrs = FlatVector::GetData(*dict_state.dictionary_pointers); - idx_t kept = 0; - for (idx_t i = 0; i < prepared_count; i++) { - const auto row_index = current_sel->get_index(i); - const auto dict_idx = offsets.get_index(row_index); - const auto ptr = unique_dict_ptrs[dict_idx]; - scan_structure_ptrs[row_index] = ptr; - scan_structure.sel_vector.set_index(kept, row_index); - // miss rows leave a stale pointer, but Next() only reads pointers at positions in sel_vector[0..count) - kept += (ptr != nullptr); - } - scan_structure.count = kept; + ExpandProbeResults(scan_structure, keys, key_state, {dict_state.dictionary_results.get(), dict_size}, + offsets); return true; } @@ -1611,6 +1646,10 @@ bool JoinHashTable::TryProbeConstant(ScanStructure &scan_structure, DataChunk &k if (constant_col.GetVectorType() != VectorType::CONSTANT_VECTOR) { return false; } + // Direct membership and dictionary loops already read constant keys cheaply. + if (GetProbeResultType() != PerfectHashJoinTable::Type::ROWS) { + return false; + } #ifndef DEBUG if (keys.size() <= 1) { // resolving once only pays off when the result fans out to multiple probe rows @@ -1625,46 +1664,105 @@ bool JoinHashTable::TryProbeConstant(ScanStructure &scan_structure, DataChunk &k auto &unique_values = dict_state.unique_values; if (unique_values.ColumnCount() == 0) { unique_values.InitializeEmpty(vector {equality_types[0]}); - TupleDataCollection::InitializeChunkState(dict_state.unique_key_state, {equality_types[0]}); } SelectionVector sel(1); sel.set_index(0, 0); unique_values.data[0].Slice(constant_col, sel, 1); - unique_values.Flatten(); - TupleDataCollection::ToUnifiedFormat(dict_state.unique_key_state, unique_values); + uint64_t resolved = 0; + ResolveProbeKeys(scan_structure, unique_values, probe_state, {&resolved, 1}, sel); + ExpandProbeResults(scan_structure, keys, key_state, {&resolved, 1}, sel); + return true; +} - // Resolve the equality chain; Next() checks any additional predicates. - idx_t count = 1; - GetRowPointers(unique_values, dict_state.unique_key_state, probe_state, nullptr, nullptr, count, - dict_state.new_dictionary_pointers, dict_state.match_sel, false); - const auto resolved_ptr = - count == 0 ? nullptr : FlatVector::GetData(dict_state.new_dictionary_pointers)[0]; +PerfectHashJoinTable::Type JoinHashTable::GetProbeResultType() const { + return perfect_hash_table ? perfect_hash_table->GetType() : PerfectHashJoinTable::Type::ROWS; +} - // fan out the resolved pointer into the scan_structure shape that Probe() produces - scan_structure.is_null = false; - scan_structure.finished = false; - if (join_type != JoinType::INNER) { - memset(scan_structure.found_match.get(), 0, sizeof(bool) * STANDARD_VECTOR_SIZE); +void JoinHashTable::ResolveProbeKeys(ScanStructure &scan, DataChunk &keys, ProbeState &state, + array_ptr results, const SelectionVector &result_sel) { + auto count = keys.size(); + switch (GetProbeResultType()) { + case PerfectHashJoinTable::Type::ROWS: { + TupleDataCollection::ToUnifiedFormat(scan.key_state, keys); + GetRowPointers(keys, scan.key_state, state, nullptr, nullptr, count, scan.pointers, scan.sel_vector, false); + const auto pointers = FlatVector::GetData(scan.pointers); + for (idx_t i = 0; i < count; i++) { + const auto row = scan.sel_vector.get_index(i); + results[result_sel.get_index(row)] = cast_pointer_to_uint64(pointers[row]); + } + break; } - TupleDataCollection::ToUnifiedFormat(key_state, keys); - optional_ptr current_sel; - const idx_t prepared_count = - PrepareKeys(keys, key_state.vector_data, current_sel, scan_structure.sel_vector, false); - scan_structure.has_null_value_filter = prepared_count < keys.size(); + case PerfectHashJoinTable::Type::DICTIONARY: + if (!scan.dictionary_selection) { + scan.dictionary_selection = make_uniq(STANDARD_VECTOR_SIZE); + } + count = perfect_hash_table->ProbeDictionary(keys.data[0], scan.sel_vector, *scan.dictionary_selection); + for (idx_t i = 0; i < count; i++) { + results[result_sel.get_index(scan.sel_vector.get_index(i))] = scan.dictionary_selection->get_index(i) + 1; + } + break; + case PerfectHashJoinTable::Type::BITMAP: + perfect_hash_table->ProbeMembership(keys.data[0], scan.found_match); + for (idx_t i = 0; i < count; i++) { + results[result_sel.get_index(i)] = scan.found_match[i]; + } + break; + } +} - auto scan_structure_ptrs = FlatVector::GetDataMutable(scan_structure.pointers); - idx_t kept = 0; - if (resolved_ptr) { - // PrepareKeys dropped NULL probe rows - the rest all share the one resolved chain-head - for (idx_t i = 0; i < prepared_count; i++) { - const auto row_index = current_sel->get_index(i); - scan_structure_ptrs[row_index] = resolved_ptr; - scan_structure.sel_vector.set_index(kept++, row_index); +template +void JoinHashTable::ExpandProbeResults(ScanStructure &scan, DataChunk &keys, TupleDataChunkState &key_state, + array_ptr results, const SelectionVector &result_sel) { + scan.is_null = false; + scan.finished = false; + const auto constant_result = CONSTANT ? results[0] : 0; + D_ASSERT(!CONSTANT || GetProbeResultType() == PerfectHashJoinTable::Type::ROWS); + switch (GetProbeResultType()) { + case PerfectHashJoinTable::Type::BITMAP: { + scan.count = 0; + idx_t matches = 0; + for (idx_t i = 0; i < keys.size(); i++) { + scan.found_match[i] = results[result_sel.get_index(i)] != 0; + matches += scan.found_match[i]; + } + scan.local_probe_matches += matches; + return; + } + case PerfectHashJoinTable::Type::DICTIONARY: + if (!scan.dictionary_selection) { + scan.dictionary_selection = make_uniq(STANDARD_VECTOR_SIZE); } + scan.count = 0; + for (idx_t i = 0; i < keys.size(); i++) { + const auto position = results[result_sel.get_index(i)]; + if (position) { + scan.sel_vector.set_index(scan.count, i); + scan.dictionary_selection->set_index(scan.count++, position - 1); + } + } + scan.local_probe_matches += scan.count; + return; + case PerfectHashJoinTable::Type::ROWS: + break; } - scan_structure.count = kept; - return true; + + optional_ptr current_sel; + InitializeScanStructure(scan, keys, key_state, current_sel); + if (CONSTANT && !constant_result) { + scan.count = 0; + return; + } + auto pointers = FlatVector::GetDataMutable(scan.pointers); + idx_t count = 0; + for (idx_t i = 0; i < scan.count; i++) { + const auto row = current_sel->get_index(i); + const auto pointer = CONSTANT ? constant_result : results[result_sel.get_index(row)]; + pointers[row] = cast_uint64_to_pointer(pointer); + scan.sel_vector.set_index(count, row); + count += pointer != 0; + } + scan.count = count; } ScanStructure::ScanStructure(JoinHashTable &ht_p, TupleDataChunkState &key_state_p) @@ -1820,10 +1918,14 @@ void ScanStructure::FlushProbeMatches() { if (local_probe_matches == 0) { return; } - ht.total_probe_matches.fetch_add(local_probe_matches, std::memory_order_relaxed); + ht.probe_matches.Add(local_probe_matches); local_probe_matches = 0; } +idx_t JoinHashTable::GetTotalProbeMatches() const { + return probe_matches.GetTotal(); +} + idx_t ScanStructure::ApplyResidualPredicate(DataChunk &probe_data, SelectionVector &match_sel, idx_t match_count, optional_ptr no_match_sel, idx_t no_match_offset) { D_ASSERT(residual_state); @@ -1895,50 +1997,54 @@ idx_t ScanStructure::ScanInnerJoin(DataChunk &keys, DataChunk &probe_data, Selec } } -template -static void AdvancePointersLoop(JoinHashTable &ht, Vector &pointers, SelectionVector &out_sel, - const SelectionVector &sel, const idx_t sel_count, idx_t &out_count) { +template +data_ptr_t JoinHashTable::GetNextPointer(data_ptr_t row) const { + if (DICTIONARY) { + if (!materialized_dictionary->next_pointers.get()) { + return nullptr; + } + const auto links = reinterpret_cast(materialized_dictionary->next_pointers.get()); + return links[Load(row + pointer_offset)]; + } + return LoadPointer(row + pointer_offset); +} + +template +idx_t JoinHashTable::AdvancePointers(Vector &pointers, SelectionVector &out_sel, const SelectionVector &sel, + idx_t count) const { idx_t new_count = 0; auto ptrs = FlatVector::GetDataMutable(pointers); - for (idx_t i = 0; i < sel_count; i++) { - auto idx = sel.get_index(i); - ptrs[idx] = ht.GetNextPointer(ptrs[idx]); + for (idx_t i = 0; i < count; i++) { + const auto idx = sel.get_index(i); + ptrs[idx] = GetNextPointer(ptrs[idx]); if (ptrs[idx]) { out_sel.set_index(new_count++, idx); } } - out_count = new_count; + return new_count; } -void ScanStructure::AdvancePointers(const SelectionVector &sel, const idx_t sel_count) { - if (!ht.chains_longer_than_one.load(std::memory_order_relaxed)) { - this->count = 0; - return; - } - if (ht.use_dict_emission) { - AdvancePointersLoop(ht, pointers, sel_vector, sel, sel_count, count); - } else { - AdvancePointersLoop(ht, pointers, sel_vector, sel, sel_count, count); +idx_t JoinHashTable::AdvancePointers(Vector &pointers, SelectionVector &out_sel, const SelectionVector &sel, + idx_t count) const { + if (!chains_longer_than_one.load(std::memory_order_relaxed)) { + return 0; } + return materialized_dictionary ? AdvancePointers(pointers, out_sel, sel, count) + : AdvancePointers(pointers, out_sel, sel, count); } -void ScanStructure::AdvancePointers() { - AdvancePointers(this->sel_vector, this->count); +void ScanStructure::AdvancePointers(const SelectionVector &sel, idx_t sel_count) { + count = ht.AdvancePointers(pointers, sel_vector, sel, sel_count); } -void ScanStructure::GatherResult(Vector &result, const SelectionVector &result_vector, - const SelectionVector &sel_vector, const idx_t count, const idx_t col_no) { - ht.data_collection->Gather(pointers, sel_vector, count, col_no, result, result_vector, nullptr); +void ScanStructure::AdvancePointers() { + AdvancePointers(this->sel_vector, this->count); } void ScanStructure::GatherResult(Vector &result, const SelectionVector &sel_vector, const idx_t count, const idx_t col_idx) { - GatherResult(result, *FlatVector::IncrementalSelectionVector(), sel_vector, count, col_idx); -} - -void ScanStructure::GatherResult(Vector &result, const idx_t count, const idx_t col_idx) { - ht.data_collection->Gather(rhs_pointers, *FlatVector::IncrementalSelectionVector(), count, col_idx, result, - *FlatVector::IncrementalSelectionVector(), nullptr); + ht.data_collection->Gather(pointers, sel_vector, count, col_idx, result, *FlatVector::IncrementalSelectionVector(), + nullptr); } static bool HasNestedDictionary(const vector> &dictionaries) { @@ -1968,17 +2074,41 @@ static bool SelectionCoversDictionary(const data_ptr_t *row_ptrs, const Selectio void JoinHashTable::GatherRHS(Vector &row_ptrs, const SelectionVector &ptr_sel, const idx_t count, DataChunk &result, idx_t rhs_col_offset, DictionaryOwnershipCache &dictionary_state) const { - if (use_dict_emission) { - const auto ptrs = FlatVector::GetData(row_ptrs); + GatherRHS(row_ptrs, JoinBuildSelection(ptr_sel, count), result, rhs_col_offset, dictionary_state); +} + +void JoinHashTable::GatherRHS(Vector &row_ptrs, const JoinBuildSelection &selection, DataChunk &result, + idx_t rhs_col_offset, DictionaryOwnershipCache &dictionary_state) const { + const auto ptrs = FlatVector::GetData(row_ptrs); + if (materialized_dictionary) { // Nested consumers may process all backing children, including those absent from the selection. - if (!HasNestedDictionary(dict_arrays) || - SelectionCoversDictionary(ptrs, ptr_sel, count, pointer_offset, Count())) { - EmitDictVectors(ptrs, ptr_sel, count, result, rhs_col_offset, dictionary_state); + if (!HasNestedDictionary(materialized_dictionary->columns) || + (selection.match_count == selection.count && + SelectionCoversDictionary(ptrs, selection.rows, selection.match_count, pointer_offset, Count()))) { + EmitDictVectors(ptrs, selection, result, rhs_col_offset, dictionary_state); return; } } - const auto &result_sel = *FlatVector::IncrementalSelectionVector(); - const auto ptrs = FlatVector::GetData(row_ptrs); + + const auto null_count = selection.count - selection.match_count; + auto &null_sel = dictionary_state.GetNullSelection(null_count); + if (null_count > 0 && selection.match_count > 0) { + D_ASSERT(selection.count <= STANDARD_VECTOR_SIZE); + validity_t matched_entries[ValidityMask::STANDARD_ENTRY_COUNT]; + ValidityMask matched(matched_entries, STANDARD_VECTOR_SIZE); + matched.SetAllInvalid(selection.count); + for (idx_t i = 0; i < selection.match_count; i++) { + matched.SetValid(selection.output.get_index(i)); + } + idx_t null_idx = 0; + for (idx_t i = 0; i < selection.count; i++) { + if (!matched.RowIsValid(i)) { + null_sel.set_index(null_idx++, i); + } + } + D_ASSERT(null_idx == null_count); + } + const auto &null_rows = selection.match_count == 0 ? *FlatVector::IncrementalSelectionVector() : null_sel; const auto &offsets = layout_ptr->GetOffsets(); const auto cond_count = condition_types.size(); @@ -1991,24 +2121,34 @@ void JoinHashTable::GatherRHS(Vector &row_ptrs, const SelectionVector &ptr_sel, if (output_col_idx >= cond_count) { auto dict_column = GetDictSurvivingColumn(output_col_idx - cond_count); if (dict_column) { - SelectionVector build_sel_vec(count); + SelectionVector build_sel_vec(selection.count); + for (idx_t i = 0; i < null_count; i++) { + build_sel_vec.set_index(null_rows.get_index(i), dict_column->NullIndex()); + } const auto col_offset = offsets[output_col_idx]; - // Read the dict index at the width chosen at layout-publication time - LoadDictIndices(dict_column->index_width, ptrs, ptr_sel, count, col_offset, build_sel_vec); + LoadDictIndices(dict_column->index_width, ptrs, selection, col_offset, build_sel_vec); const auto &entry = dictionary_state.GetEntry(col_idx, dict_column->entry); - vector.Dictionary(entry, build_sel_vec, count); + vector.Dictionary(entry, build_sel_vec, selection.count); continue; } } D_ASSERT(vector.GetType() == layout_ptr->GetTypes()[output_col_idx]); + if (selection.match_count == 0) { + ConstantVector::SetNull(vector, count_t(selection.count)); + continue; + } // The native gather writes straight into a flat buffer. A reused output chunk (e.g. across recursive-CTE // iterations) may still hold a DICTIONARY_VECTOR left by a prior dict-emitting iteration; reset it to flat. if (vector.GetVectorType() != VectorType::FLAT_VECTOR) { vector.Initialize(); } - data_collection->Gather(row_ptrs, ptr_sel, count, output_col_idx, vector, result_sel, nullptr); - FlatVector::SetSize(vector, count_t(count)); + for (idx_t i = 0; i < null_count; i++) { + FlatVector::SetNull(vector, null_rows.get_index(i), true); + } + data_collection->Gather(row_ptrs, selection.rows, selection.match_count, output_col_idx, vector, + selection.output, nullptr); + FlatVector::SetSize(vector, count_t(selection.count)); } } @@ -2049,7 +2189,7 @@ void ScanStructure::ProjectProbeColumns(DataChunk &probe_data, const SelectionVe } void ScanStructure::NextDictionaryJoin(DataChunk &probe_data, DataChunk &result) { - D_ASSERT(ht.join_type == JoinType::INNER && ht.use_dict_emission); + D_ASSERT(ht.join_type == JoinType::INNER && ht.UsesDictionaryLookup()); D_ASSERT(result.ColumnCount() == ht.lhs_output_in_probe.size() + ht.output_columns.size()); if (count > 0) { ProjectProbeColumns(probe_data, sel_vector, count, result, count == probe_data.size()); @@ -2086,15 +2226,7 @@ void ScanStructure::NextInnerJoin(DataChunk &keys, DataChunk &probe_data, DataCh } if (PropagatesBuildSide(ht.join_type)) { - // full/right outer join: mark join matches as FOUND in the HT - auto ptrs = FlatVector::GetData(pointers); - for (idx_t i = 0; i < result_count; i++) { - auto idx = chain_match_sel_vector.get_index(i); - // NOTE: threadsan reports this as a data race because this can be set concurrently by separate - // threads Technically it is, but it does not matter, since the only value that can be written is - // "true" - Store(true, ptrs[idx] + ht.tuple_size); - } + ht.MarkMatchedRows(pointers, chain_match_sel_vector, result_count); } if (ht.join_type != JoinType::RIGHT_SEMI && ht.join_type != JoinType::RIGHT_ANTI) { @@ -2198,59 +2330,78 @@ void ScanStructure::NextAntiJoin(DataChunk &keys, DataChunk &probe_data, DataChu finished = true; } -template -static void MarkChainsAsFoundLoop(JoinHashTable &ht, data_ptr_t ptrs[], const SelectionVector &chain_match_sel_vector, - const idx_t result_count, const data_ptr_t dead_end_ptr) { - for (idx_t i = 0; i < result_count; i++) { - const auto idx = chain_match_sel_vector.get_index(i); - auto &ptr = ptrs[idx]; - if (Load(ptr + ht.tuple_size)) { // Early out: chain has been fully marked as found before - ptr = dead_end_ptr; +atomic &JoinHashTable::GetMatchFlag(data_ptr_t row) const { + return *reinterpret_cast *>(row + tuple_size); +} + +void JoinHashTable::InitializeMatchFlags(const Vector &rows) const { + if (!PropagatesBuildSide(join_type) || (perfect_hash_table && perfect_hash_table->TracksMatches())) { + return; + } + static_assert(sizeof(atomic) == sizeof(bool) && alignof(atomic) == 1, + "Atomic match flags must fit the packed row layout"); + // Finalize pins the rows before constructing flags; they cannot move during probe/source. + for (auto entry : rows.Values()) { + new (entry.GetValue() + tuple_size) atomic(false); + } +} + +void JoinHashTable::MarkMatchedRows(Vector &pointers, const SelectionVector &sel, idx_t count) const { + const auto rows = FlatVector::GetData(pointers); + for (idx_t i = 0; i < count; i++) { + GetMatchFlag(rows[sel.get_index(i)]).store(true, std::memory_order_relaxed); + } +} + +idx_t JoinHashTable::SelectBuildMatches(array_ptr rows, idx_t &offset, array_ptr result, + bool matched) const { + if (perfect_hash_table && perfect_hash_table->TracksMatches()) { + return perfect_hash_table->SelectMatches(rows, *layout_ptr, offset, result, matched); + } + idx_t count = 0; + while (offset < rows.size() && count < result.size()) { + const auto row = rows[offset++]; + result[count] = row; + count += GetMatchFlag(row).load(std::memory_order_relaxed) == matched; + } + return count; +} + +template +void JoinHashTable::MarkMatchedChains(Vector &pointers, const SelectionVector &sel, idx_t count) const { + const auto ptrs = FlatVector::GetData(pointers); + for (idx_t i = 0; i < count; i++) { + auto row = ptrs[sel.get_index(i)]; + if (GetMatchFlag(row).load(std::memory_order_relaxed)) { continue; } + do { + GetMatchFlag(row).store(true, std::memory_order_relaxed); + row = GetNextPointer(row); + } while (row); + } +} - // Fully mark chain as found - while (true) { - // NOTE: threadsan reports this as a data race because this can be set concurrently by separate - // threads Technically it is, but it does not matter, since the only value that can be written is - // "true" - Store(true, ptr + ht.tuple_size); - auto next_ptr = ht.GetNextPointer(ptr); - if (!next_ptr) { - break; - } - ptr = next_ptr; - } +void JoinHashTable::MarkMatchedChains(Vector &pointers, const SelectionVector &sel, idx_t count) const { + if (materialized_dictionary) { + MarkMatchedChains(pointers, sel, count); + } else { + MarkMatchedChains(pointers, sel, count); } } void ScanStructure::NextRightSemiOrAntiJoin(DataChunk &keys, DataChunk &probe_data) { - const auto ptrs = FlatVector::GetDataMutable(pointers); while (!PointersExhausted()) { - // resolve the equality_predicates for this set of keys - idx_t result_count = ResolvePredicates(keys, probe_data, chain_match_sel_vector, nullptr); - + const auto result_count = ResolvePredicates(keys, probe_data, chain_match_sel_vector, nullptr); if (ht.non_equality_predicates.empty() && !ht.residual_predicate) { - // we only have equality predicates - the match is found for the entire chain - const auto dead_end_ptr = ht.dead_end.get(); - if (ht.use_dict_emission) { - MarkChainsAsFoundLoop(ht, ptrs, chain_match_sel_vector, result_count, dead_end_ptr); - } else { - MarkChainsAsFoundLoop(ht, ptrs, chain_match_sel_vector, result_count, dead_end_ptr); - } + // Equality identifies a whole group; no further predicate evaluation is needed. + ht.MarkMatchedChains(pointers, chain_match_sel_vector, result_count); + count = 0; } else { - // we have non-equality predicates - we need to evaluate the join condition for every row - // for each match found in the current pass - mark the match as found - for (idx_t i = 0; i < result_count; i++) { - auto idx = chain_match_sel_vector.get_index(i); - Store(true, ptrs[idx] + ht.tuple_size); - } + ht.MarkMatchedRows(pointers, chain_match_sel_vector, result_count); + AdvancePointers(); } - - // check the next set of pointers - AdvancePointers(); } - finished = true; } @@ -2469,11 +2620,8 @@ void ScanStructure::NextLeftJoin(DataChunk &keys, DataChunk &probe_data, DataChu idx_t probe_col_idx = ht.lhs_output_in_probe[i]; result.data[i].Slice(probe_data.data[probe_col_idx], sel, remaining_count); } - // now set the right side to NULL - for (idx_t i = ht.lhs_output_in_probe.size(); i < result.ColumnCount(); i++) { - Vector &vec = result.data[i]; - ConstantVector::SetNull(vec, count_t(remaining_count)); - } + const JoinBuildSelection build_selection(sel, 0, sel, remaining_count); + ht.GatherRHS(pointers, build_selection, result, ht.lhs_output_in_probe.size(), dictionary_gather_state); } finished = true; } @@ -2506,20 +2654,8 @@ void ScanStructure::NextSingleJoin(DataChunk &keys, DataChunk &probe_data, DataC result.data[i].Reference(probe_data.data[probe_col_idx]); } - // now fetch the data from the RHS - for (idx_t i = 0; i < ht.output_columns.size(); i++) { - auto &vector = result.data[ht.lhs_output_in_probe.size() + i]; - // set NULL entries for every entry that was not found - for (idx_t j = 0; j < probe_data.size(); j++) { - if (!found_match[j]) { - FlatVector::SetNull(vector, j, true); - } - } - const auto output_col_idx = ht.output_columns[i]; - D_ASSERT(vector.GetType() == ht.layout_ptr->GetTypes()[output_col_idx]); - GatherResult(vector, result_sel, result_sel, result_count, output_col_idx); - FlatVector::SetSize(vector, count_t(probe_data.size())); - } + const JoinBuildSelection build_selection(result_sel, result_count, result_sel, probe_data.size()); + ht.GatherRHS(pointers, build_selection, result, ht.lhs_output_in_probe.size(), dictionary_gather_state); result.SetChildCardinality(probe_data.size()); // like the SEMI, ANTI and MARK join types, the SINGLE join only ever does one pass over the HT per input chunk @@ -2566,23 +2702,8 @@ void ScanStructure::NextUniqueLeftJoin(DataChunk &keys, DataChunk &probe_data, D result.data[i].Reference(probe_data.data[probe_col_idx]); } - // Fetch RHS data. If all rows matched we can skip NULL-setting and gather directly. - // Otherwise, mark unmatched rows as NULL before gathering matched rows. - const bool all_match = result_count == probe_size; - for (idx_t i = 0; i < ht.output_columns.size(); i++) { - auto &vector = result.data[ht.lhs_output_in_probe.size() + i]; - if (!all_match) { - for (idx_t j = 0; j < probe_size; j++) { - if (!found_match[j]) { - FlatVector::SetNull(vector, j, true); - } - } - } - const auto output_col_idx = ht.output_columns[i]; - D_ASSERT(vector.GetType() == ht.layout_ptr->GetTypes()[output_col_idx]); - GatherResult(vector, result_sel, result_sel, result_count, output_col_idx); - FlatVector::SetSize(vector, count_t(probe_size)); - } + const JoinBuildSelection build_selection(result_sel, result_count, result_sel, probe_size); + ht.GatherRHS(pointers, build_selection, result, ht.lhs_output_in_probe.size(), dictionary_gather_state); // single pass - done result.SetChildCardinality(probe_data.size()); @@ -2611,15 +2732,9 @@ void JoinHashTable::ScanFullOuter(JoinHTScanState &state, Vector &addresses, Dat do { const auto count = iterator.GetCurrentChunkCount(); idx_t i = state.offset_in_chunk; - while (i < count && found_entries < STANDARD_VECTOR_SIZE) { - // Leave room for a scratch write even when every scanned row matches. - const auto end = MinValue(count, i + STANDARD_VECTOR_SIZE - found_entries); - for (; i < end; i++) { - const auto row = row_locations[i]; - key_locations[found_entries] = row; - found_entries += Load(row + tuple_size) == match_propagation_value; - } - } + found_entries += SelectBuildMatches({row_locations, count}, i, + {key_locations + found_entries, STANDARD_VECTOR_SIZE - found_entries}, + match_propagation_value); if (found_entries == STANDARD_VECTOR_SIZE) { state.offset_in_chunk = i; break; @@ -2668,6 +2783,7 @@ idx_t JoinHashTable::FillWithHTOffsets(JoinHTScanState &state, Vector &addresses } 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; @@ -2681,6 +2797,7 @@ idx_t JoinHashTable::ScanKeyColumn(Vector &addresses, Vector &result, idx_t colu } 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; } @@ -2689,6 +2806,7 @@ idx_t JoinHashTable::GetTotalSize(const vector &partition_sizes, const ve const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits); const auto mark_join_size = mark_join_info.uncorrelated_condition_rows ? mark_join_info.uncorrelated_condition_rows->SizeInBytes() : 0; + const auto retained_size = mark_join_size + GetRetainedDictionarySize(); idx_t total_size = 0; idx_t total_count = 0; @@ -2708,22 +2826,51 @@ idx_t JoinHashTable::GetTotalSize(const vector &partition_sizes, const ve } if (total_count == 0) { - return mark_join_size; + return retained_size; } - return total_size + PointerTableSize(total_count) + mark_join_size; + return total_size + PointerTableSize(total_count) + retained_size; +} + +void JoinHashTable::MergePerfectHashBounds(const vector> &local_hts) { + if (!perfect_hash_candidate) { + return; + } + for (const auto &ht : local_hts) { + D_ASSERT(ht.get().perfect_hash_candidate); + perfect_hash_candidate->MergeBounds(*ht.get().perfect_hash_candidate); + } } idx_t JoinHashTable::GetTotalSize(const vector> &local_hts, idx_t &max_partition_size, - idx_t &max_partition_count) const { + idx_t &max_partition_count, LookupSizing lookup_sizing) const { const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits); vector partition_sizes(num_partitions, 0); vector partition_counts(num_partitions, 0); + idx_t allocated_size = 0; for (auto &ht : local_hts) { ht.get().GetSinkCollection().GetSizesAndCounts(partition_sizes, partition_counts); + allocated_size += ht.get().GetSinkCollection().GetAllocatedSizeInBytes(); } auto total_size = GetTotalSize(partition_sizes, partition_counts, max_partition_size, max_partition_count); + idx_t logical_size = 0; + for (const auto partition_size : partition_sizes) { + logical_size += partition_size; + } + // Pinning the whole build retains unused capacity in every producer's row and heap blocks. + total_size += allocated_size > logical_size ? allocated_size - logical_size : 0; + if (lookup_sizing == LookupSizing::SELECTED && perfect_hash_candidate) { + idx_t count = 0; + for (const auto partition_count : partition_counts) { + count += partition_count; + } + const auto pointer_size = PointerTableSize(count); + const auto perfect_size = perfect_hash_candidate->EstimateSize(count, pointer_size); + if (perfect_size) { + total_size = total_size - pointer_size + perfect_size; + } + } for (auto &ht : local_hts) { auto &condition_rows = ht.get().mark_join_info.uncorrelated_condition_rows; if (condition_rows) { @@ -2733,6 +2880,18 @@ idx_t JoinHashTable::GetTotalSize(const vector> &local_ return total_size; } +idx_t JoinHashTable::GetRetainedDictionarySize() const { + idx_t result = 0; + if (dict_info) { + for (const auto &column : dict_info->columns) { + if (column.index_width) { + result += column.entry->data.GetAllocationSize(); + } + } + } + return result; +} + idx_t JoinHashTable::GetRemainingSize() const { const auto num_partitions = RadixPartitioning::NumberOfPartitions(radix_bits); auto &partitions = sink_collection->GetPartitions(); @@ -2749,7 +2908,7 @@ idx_t JoinHashTable::GetRemainingSize() const { const auto mark_join_size = mark_join_info.uncorrelated_condition_rows ? mark_join_info.uncorrelated_condition_rows->SizeInBytes() : 0; - return data_size + PointerTableSize(count) + mark_join_size; + return data_size + PointerTableSize(count) + mark_join_size + GetRetainedDictionarySize(); } void JoinHashTable::Unpartition() { @@ -2820,6 +2979,7 @@ void JoinHashTable::Repartition(JoinHashTable &global_ht) { } void JoinHashTable::Reset() { + materialized_dictionary.reset(); bucket_shift = 0; data_collection->Reset(); hash_map.Reset(); @@ -2872,6 +3032,7 @@ void JoinHashTable::ResetForNewIterationSinglePartition() { // dictionary it indexes into cannot be carried over. layout_ptr.reset(); dict_info.reset(); + build_state.reset(); data_collection.reset(); sink_collection.reset(); capacity = DConstants::INVALID_INDEX; @@ -2880,22 +3041,15 @@ void JoinHashTable::ResetForNewIterationSinglePartition() { finalized = false; has_null = false; chains_longer_than_one.store(false, std::memory_order_relaxed); - total_probe_matches = 0; + probe_matches.Reset(); load_factor = DEFAULT_LOAD_FACTOR; - bloom_filter.reset(); - should_build_bloom_filter = false; - key_bloom_filters.clear(); - should_build_key_bloom_filters.clear(); - key_bloom_filter_budget = NumericLimits::Maximum(); + bloom_filters.clear(); + should_build_bloom_filters.clear(); + bloom_filter_budget = NumericLimits::Maximum(); prefix_range_filters.clear(); should_build_prefix_range_filter = false; ResetMarkJoinInfo(*this); - // The next iteration may rebuild a different small build side, so this iteration's dictionary - // state is stale. Keep in lock-step with BuildDictionaryArrays, which sets these four fields. - dict_arrays.clear(); - aux_next_ptrs.Reset(); - aux_next_ptrs_data = nullptr; - use_dict_emission = false; + materialized_dictionary.reset(); } bool JoinHashTable::PrepareExternalFinalize(const idx_t max_ht_size) { @@ -2963,20 +3117,27 @@ bool JoinHashTable::PrepareExternalFinalize(const idx_t max_ht_size) { void JoinHashTable::ProbeAndSpill(ScanStructure &scan_structure, DataChunk &probe_keys, TupleDataChunkState &key_state, ProbeState &probe_state, DataChunk &probe_chunk, ProbeSpill &probe_spill, ProbeSpillLocalAppendState &spill_state, DataChunk &spill_chunk) { - // hash all the keys - Vector hashes(LogicalType::HASH); + spill_chunk.Reset(); + if (!probe_state.spill_hashes) { + probe_state.spill_hashes = make_uniq(); + probe_state.spill_hashes->Initialize(buffer_manager.GetBufferAllocator(), {LogicalType::HASH}); + } + probe_state.spill_hashes->Reset(); + auto &hashes = probe_state.spill_hashes->data[0]; Hash(probe_keys, *FlatVector::IncrementalSelectionVector(), probe_keys.size(), hashes); - // find out which keys we can match with the current pinned partitions + // Probe keys and output can retain this selection until the next batch has already started. SelectionVector true_sel(STANDARD_VECTOR_SIZE); - SelectionVector false_sel(STANDARD_VECTOR_SIZE); + auto &false_sel = probe_state.spill_false_sel; + if (false_sel.sel_data().use_count() != 1) { + false_sel.Initialize(STANDARD_VECTOR_SIZE); + } const auto true_count = RadixPartitioning::Select(hashes, FlatVector::IncrementalSelectionVector(), probe_keys.size(), radix_bits, current_partitions, &true_sel, &false_sel); const auto false_count = probe_keys.size() - true_count; // can't probe these values right now, append to spill - spill_chunk.Reset(); spill_chunk.Reference(probe_chunk); spill_chunk.data.back().Reference(hashes); spill_chunk.Slice(false_sel, false_count); @@ -3067,34 +3228,43 @@ void ProbeSpill::PrepareNextProbe() { //===--------------------------------------------------------------------===// //! Threshold constants gating small-build-side dictionary emission struct DictionaryEmissionActivation { - //! Caps the dict_arrays allocation; 8 MiB keeps them in L3 and bounds aux_next_ptrs + //! Bounds the retained payload arrays static constexpr idx_t MAX_BUILD_PAYLOAD_BYTES = 8ULL * 1024ULL * 1024ULL; //! Below this ratio, per-row savings are unlikely to amortize the setup cost static constexpr idx_t PROBE_BUILD_RATIO = 100; + //! Conservative allowance for simultaneous gather/copy buffers, capacity rounding and string heaps. + static constexpr idx_t NESTED_ALLOCATION_FACTOR = 8; }; -idx_t JoinHashTable::ComputeBuildPayloadBytes(const vector &rhs_output_types) const { - D_ASSERT(Count() > 0); +//! Include default child capacities before allocating a nested dictionary. +static idx_t EstimateNestedDictionaryBuffers(const LogicalType &type, idx_t count) { const auto limit = DictionaryEmissionActivation::MAX_BUILD_PAYLOAD_BYTES; - idx_t payload_bytes = 0; - bool has_nested = false; - for (const auto &type : rhs_output_types) { - const auto row_size = GetTypeIdSize(type.InternalType()); - if (row_size > (limit - payload_bytes) / Count()) { - return limit + 1; - } - payload_bytes += row_size * Count(); - has_nested |= type.IsNested(); + count = MaxValue(count, STANDARD_VECTOR_SIZE); + if (count > limit) { + return limit + 1; } - // Nested gathers copy children; scalar strings continue to reference the pinned build heap. - if (has_nested) { - const auto collection_bytes = data_collection->SizeInBytes(); - if (collection_bytes > limit - payload_bytes) { + idx_t size = ((count + 63) / 64) * sizeof(validity_t); + switch (type.InternalType()) { + case PhysicalType::STRUCT: + for (const auto &child : StructType::GetChildTypes(type)) { + size += EstimateNestedDictionaryBuffers(child.second, count); + if (size > limit) { + return limit + 1; + } + } + return size; + case PhysicalType::ARRAY: + if (ArrayType::GetSize(type) > limit / count) { return limit + 1; } - payload_bytes += collection_bytes; + return size + EstimateNestedDictionaryBuffers(ArrayType::GetChildType(type), count * ArrayType::GetSize(type)); + case PhysicalType::LIST: + size += EstimateNestedDictionaryBuffers(ListType::GetChildType(type), STANDARD_VECTOR_SIZE); + break; + default: + break; } - return payload_bytes; + return size + count * GetTypeIdSize(type.InternalType()); } bool JoinHashTable::CanUsePerfectDictionaryLookup() const { @@ -3107,85 +3277,109 @@ bool JoinHashTable::UsesDictionaryLookup() const { return perfect_hash_table && perfect_hash_table->GetType() == PerfectHashJoinTable::Type::DICTIONARY; } -bool JoinHashTable::CanUseDictionaryEmission(const PhysicalHashJoin &op, bool external, idx_t probe_cardinality) const { - // external joins rebuild partitions, invalidating row pointers - if (external) { - return false; - } - // mutually exclusive with the dict-surviving path: that path narrows the payload slot to a 1/2/4-byte - // index, while NEXT_PTR embedding here overwrites a different field and assumes payload bytes are intact. - if (HasDictSurvivingColumns()) { - return false; - } - // SINGLE joins need FlatVector::SetNull for unmatched rows; dictionary vectors cannot supply it - if (join_type == JoinType::SINGLE) { - return false; - } - // Unique LEFT joins gather directly and never emit dictionaries. - if (join_type == JoinType::LEFT && !chains_longer_than_one.load(std::memory_order_relaxed)) { - return false; - } - if (op.rhs_output_columns.col_types.empty()) { - return false; +idx_t JoinHashTable::GetDictionaryReservationSize(const PhysicalHashJoin &op, bool external, + idx_t probe_cardinality) const { + // External rounds invalidate pointers; surviving dictionaries already own the payload representation. + if (external || HasDictSurvivingColumns() || op.rhs_output_columns.col_types.empty()) { + return 0; } if (Count() == 0 || Count() > NumericLimits::Maximum()) { - return false; + return 0; } if (probe_cardinality < Count() || (!CanUsePerfectDictionaryLookup() && probe_cardinality / DictionaryEmissionActivation::PROBE_BUILD_RATIO < Count())) { - return false; + return 0; } + + const auto limit = DictionaryEmissionActivation::MAX_BUILD_PAYLOAD_BYTES; + idx_t payload_bytes = 0; + idx_t size = Count() * sizeof(data_ptr_t); + if (chains_longer_than_one.load(std::memory_order_relaxed)) { + size += Count() * sizeof(data_ptr_t); + } + bool has_nested = false; for (const auto &type : op.rhs_output_columns.col_types) { - if (type.InternalType() == PhysicalType::STRUCT) { - // STRUCT vectors apply selections to their children instead of wrapping a dictionary. - return false; + if (type.InternalType() == PhysicalType::STRUCT || type.InternalType() == PhysicalType::ARRAY) { + // STRUCT applies selections to its children; ARRAY dictionary hashing loses child batching. + return 0; } - if (type.InternalType() == PhysicalType::ARRAY) { - // ARRAY dictionary hashing processes individual arrays instead of batching their children. - return false; + const auto needs_null = IsLeftOuterJoin(join_type) || join_type == JoinType::SINGLE; + const auto entries = Count() + (needs_null && !type.IsNested()); + const auto row_size = GetTypeIdSize(type.InternalType()); + if (row_size > (limit - payload_bytes) / entries) { + return 0; } - if (type.IsNested() && Count() > STANDARD_VECTOR_SIZE) { + payload_bytes += entries * row_size; + if (type.IsNested()) { // A chunk must be able to reference every nested dictionary entry. - return false; + if (Count() > STANDARD_VECTOR_SIZE) { + return 0; + } + const auto buffers = EstimateNestedDictionaryBuffers(type, Count()); + if (buffers > limit) { + return 0; + } + has_nested = true; + size += DictionaryEmissionActivation::NESTED_ALLOCATION_FACTOR * buffers; + } else { + const auto validity_capacity = MaxValue(entries, STANDARD_VECTOR_SIZE); + size += entries * row_size + ValidityMask::EntryCount(validity_capacity) * sizeof(validity_t); } } - if (ComputeBuildPayloadBytes(op.rhs_output_columns.col_types) > - DictionaryEmissionActivation::MAX_BUILD_PAYLOAD_BYTES) { - return false; + if (has_nested) { + const auto collection_bytes = data_collection->SizeInBytes(); + if (collection_bytes > limit - payload_bytes) { + return 0; + } + size += DictionaryEmissionActivation::NESTED_ALLOCATION_FACTOR * collection_bytes; } - // Count() fits in the uint32_t dict index stored into NEXT_PTR by BuildDictionaryArrays - D_ASSERT(Count() <= NumericLimits::Maximum()); - return true; + return size; } -void JoinHashTable::EmitDictVectors(const data_ptr_t *row_ptrs, const SelectionVector &ptr_sel, idx_t count, - DataChunk &result, idx_t rhs_col_offset, - DictionaryOwnershipCache &dictionary_state) const { - D_ASSERT(output_columns.size() == dict_arrays.size()); - SelectionVector build_sel_vec(count); - for (idx_t i = 0; i < count; i++) { - const auto idx = ptr_sel.get_index(i); - build_sel_vec.set_index(i, Load(row_ptrs[idx] + pointer_offset)); +idx_t JoinHashTable::GetMaterializedDictionarySize() const { + if (!materialized_dictionary) { + return 0; + } + idx_t size = materialized_dictionary->next_pointers.GetSize(); + for (const auto &column : materialized_dictionary->columns) { + size += column->data.GetAllocationSize(); + } + return size; +} + +void JoinHashTable::EmitDictVectors(const data_ptr_t *row_ptrs, const JoinBuildSelection &selection, DataChunk &result, + idx_t rhs_col_offset, DictionaryOwnershipCache &dictionary_state) const { + D_ASSERT(output_columns.size() == materialized_dictionary->columns.size()); + SelectionVector build_sel_vec(selection.count); + if (selection.match_count < selection.count) { + for (idx_t i = 0; i < selection.count; i++) { + build_sel_vec.set_index(i, Count()); + } } - EmitDictVectors(build_sel_vec, count, result, rhs_col_offset, dictionary_state); + for (idx_t i = 0; i < selection.match_count; i++) { + const auto idx = selection.rows.get_index(i); + build_sel_vec.set_index(selection.output.get_index(i), Load(row_ptrs[idx] + pointer_offset)); + } + EmitDictVectors(build_sel_vec, selection.count, result, rhs_col_offset, dictionary_state); } void JoinHashTable::EmitDictVectors(const SelectionVector &build_sel, idx_t count, DataChunk &result, idx_t rhs_col_offset, DictionaryOwnershipCache &dictionary_state) const { - D_ASSERT(output_columns.size() == dict_arrays.size()); + D_ASSERT(output_columns.size() == materialized_dictionary->columns.size()); for (idx_t col_idx = 0; col_idx < output_columns.size(); col_idx++) { auto &vector = result.data[rhs_col_offset + col_idx]; - vector.Dictionary(dictionary_state.GetEntry(col_idx, dict_arrays[col_idx]), build_sel, count); + vector.Dictionary(dictionary_state.GetEntry(col_idx, materialized_dictionary->columns[col_idx]), build_sel, + count); } } -void JoinHashTable::BuildDictionaryArrays(const PhysicalHashJoin &op) { +void JoinHashTable::BuildDictionaryArrays(const PhysicalHashJoin &op, idx_t reservation_size) { auto &collection = *data_collection; const auto build_count = collection.Count(); - // preconditions enforced by CanUseDictionaryEmission + // Preconditions enforced by GetDictionaryReservationSize. D_ASSERT(build_count > 0); - D_ASSERT(dict_arrays.empty()); + D_ASSERT(!materialized_dictionary); // dict index is a uint32_t; assert defensively if MAX_BUILD_PAYLOAD_BYTES is ever relaxed D_ASSERT(build_count <= NumericLimits::Maximum()); @@ -3199,8 +3393,8 @@ void JoinHashTable::BuildDictionaryArrays(const PhysicalHashJoin &op) { FlatVector::SetSize(row_pointer_vector, collected); const auto row_ptrs = FlatVector::GetData(row_pointer_vector); - // Outer joins and partial nested selections can produce chunks without these dictionaries. - bool dict_on_every_chunk = join_type != JoinType::LEFT && join_type != JoinType::OUTER; + // Partial nested selections can produce chunks without these dictionaries. + bool dict_on_every_chunk = true; for (const auto &type : op.rhs_output_columns.col_types) { dict_on_every_chunk &= !type.IsNested(); } @@ -3211,8 +3405,10 @@ void JoinHashTable::BuildDictionaryArrays(const PhysicalHashJoin &op) { vector> dictionaries; for (idx_t col_idx = 0; col_idx < op.rhs_output_columns.col_types.size(); col_idx++) { const auto &type = op.rhs_output_columns.col_types[col_idx]; - auto dict_entry = dict_on_every_chunk ? DictionaryVector::CreateReusableGlobalDictionary(type, build_count) - : DictionaryVector::CreateReusableDictionary(type, build_count); + const auto needs_null = IsLeftOuterJoin(join_type) || join_type == JoinType::SINGLE; + const auto entry_count = build_count + (needs_null && !type.IsNested()); + auto dict_entry = dict_on_every_chunk ? DictionaryVector::CreateReusableGlobalDictionary(type, entry_count) + : DictionaryVector::CreateReusableDictionary(type, entry_count); if (dict_entry->data.GetAllocationSize() > DictionaryEmissionActivation::MAX_BUILD_PAYLOAD_BYTES - dictionary_bytes) { return; @@ -3227,6 +3423,9 @@ void JoinHashTable::BuildDictionaryArrays(const PhysicalHashJoin &op) { VectorOperations::Copy(gathered, dict_entry->data, build_count, 0, 0); } else { collection.Gather(row_pointer_vector, sel, build_count, output_col_idx, dict_entry->data, sel, nullptr); + if (needs_null) { + FlatVector::SetNull(dict_entry->data, build_count, true); + } } const auto allocation_size = dict_entry->data.GetAllocationSize(); if (allocation_size > DictionaryEmissionActivation::MAX_BUILD_PAYLOAD_BYTES - dictionary_bytes) { @@ -3235,32 +3434,25 @@ void JoinHashTable::BuildDictionaryArrays(const PhysicalHashJoin &op) { dictionary_bytes += allocation_size; dictionaries.emplace_back(std::move(dict_entry)); } - dict_arrays = std::move(dictionaries); - - // save chain pointers before overwriting NEXT_PTR; GetNextPointer reads them back. - // One extra slot is reserved at the end and left null so that `dead_end` has an index - // that terminates a chain. Without it, `dead_end` is zeroed and therefore resolves to - // index 0, which belongs to a real row, and following it walks an unrelated chain. + auto state = make_uniq(); + state->columns = std::move(dictionaries); const auto has_chains = chains_longer_than_one.load(std::memory_order_relaxed); if (has_chains) { - aux_next_ptrs = buffer_manager.GetBufferAllocator().Allocate((build_count + 1) * sizeof(data_ptr_t)); - aux_next_ptrs_data = reinterpret_cast(aux_next_ptrs.get()); - aux_next_ptrs_data[build_count] = nullptr; - Store(static_cast(build_count), dead_end.get() + pointer_offset); + state->next_pointers = buffer_manager.GetBufferAllocator().Allocate(build_count * sizeof(data_ptr_t)); } - - // save the original NEXT_PTR into aux_next_ptrs (if chains exist) and embed the dict index + const auto links = reinterpret_cast(state->next_pointers.get()); for (idx_t i = 0; i < build_count; i++) { const auto next_ptr_location = row_ptrs[i] + pointer_offset; if (has_chains) { - aux_next_ptrs_data[i] = LoadPointer(next_ptr_location); + links[i] = LoadPointer(next_ptr_location); } Store(static_cast(i), next_ptr_location); } + materialized_dictionary = std::move(state); + D_ASSERT(GetMaterializedDictionarySize() + row_pointer_vector.GetAllocationSize() <= reservation_size); - use_dict_emission = true; // Nested output can fall back to native gathering, which needs the original row pointers. - if (CanUsePerfectDictionaryLookup() && !HasNestedDictionary(dict_arrays)) { + if (CanUsePerfectDictionaryLookup() && !HasNestedDictionary(materialized_dictionary->columns)) { perfect_hash_table->ConvertToDictionary(pointer_offset); DUCKDB_LOG(context, PhysicalOperatorLogType, op, "PhysicalHashJoin", "DictionaryLookup", {}); } diff --git a/src/duckdb/src/execution/nested_loop_join/nested_loop_join_mark.cpp b/src/duckdb/src/execution/nested_loop_join/nested_loop_join_mark.cpp index e5cb1499c..a13e780be 100644 --- a/src/duckdb/src/execution/nested_loop_join/nested_loop_join_mark.cpp +++ b/src/duckdb/src/execution/nested_loop_join/nested_loop_join_mark.cpp @@ -198,4 +198,9 @@ void NestedLoopJoinMark::Perform(DataChunk &left, ColumnDataCollection &right, b } } +void NestedLoopJoinMark::Perform(const Vector &left, const Vector &right, idx_t left_count, idx_t right_count, + bool found_match[], ExpressionType comparison) { + MarkJoinComparisonSwitch(left, right, left_count, right_count, found_match, comparison, nullptr); +} + } // namespace duckdb diff --git a/src/duckdb/src/execution/operator/aggregate/aggregate_object.cpp b/src/duckdb/src/execution/operator/aggregate/aggregate_object.cpp index 4f7733573..e51a98f5a 100644 --- a/src/duckdb/src/execution/operator/aggregate/aggregate_object.cpp +++ b/src/duckdb/src/execution/operator/aggregate/aggregate_object.cpp @@ -7,9 +7,9 @@ namespace duckdb { -AggregateObject::AggregateObject(BoundAggregateFunction function, FunctionData *bind_data, idx_t child_count, - idx_t payload_size, AggregateType aggr_type, PhysicalType return_type, - optional_ptr filter) +AggregateObject::AggregateObject(BoundAggregateFunction function, optional_ptr bind_data, + idx_t child_count, idx_t payload_size, AggregateType aggr_type, + PhysicalType return_type, optional_ptr filter) : function(std::move(function)), bind_data_wrapper(bind_data ? make_shared_ptr(bind_data->Copy()) : nullptr), child_count(child_count), payload_size(payload_size), aggr_type(aggr_type), return_type(return_type), @@ -48,13 +48,18 @@ AggregateFilterData::AggregateFilterData(ClientContext &context, const Expressio idx_t AggregateFilterData::Select(DataChunk &chunk) { selected_count = filter_executor.SelectExpression(chunk, true_sel); + all_selected = selected_count == chunk.size(); return selected_count; } idx_t AggregateFilterData::ApplyFilter(DataChunk &payload) { Select(payload); for (auto col_idx : sliced_columns) { - filtered_payload.data[col_idx].Slice(payload.data[col_idx], true_sel, selected_count); + if (all_selected) { + filtered_payload.data[col_idx].Reference(payload.data[col_idx]); + } else { + filtered_payload.data[col_idx].Slice(payload.data[col_idx], true_sel, selected_count); + } } return selected_count; } diff --git a/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp b/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp index 065de3a76..a60bfeef0 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp @@ -5,7 +5,6 @@ #include "duckdb/execution/expression_executor.hpp" #include "duckdb/function/aggregate_function.hpp" #include "duckdb/function/window_function.hpp" -#include "duckdb/function/window/window_executor.hpp" #include "duckdb/parallel/thread_context.hpp" #include "duckdb/planner/expression/bound_window_expression.hpp" @@ -13,9 +12,9 @@ namespace duckdb { PhysicalStreamingWindow::PhysicalStreamingWindow(PhysicalPlan &physical_plan, vector types, vector> select_list, - idx_t estimated_cardinality, PhysicalOperatorType type) - : PhysicalOperator(physical_plan, type, std::move(types), estimated_cardinality), - select_list(std::move(select_list)) { + idx_t estimated_cardinality, optional_idx partition_limit) + : PhysicalOperator(physical_plan, PhysicalOperatorType::STREAMING_WINDOW, std::move(types), estimated_cardinality), + select_list(std::move(select_list)), partition_limit(partition_limit) { } class StreamingWindowGlobalState : public GlobalOperatorState { @@ -89,7 +88,7 @@ class StreamingWindowState : public OperatorState { //! The state vector for the single state Vector statev; //! The aggregate binding data (if any) - FunctionData *bind_data = nullptr; + optional_ptr bind_data = nullptr; //! The aggregate state destructor (if any) aggregate_destructor_t dtor = nullptr; //! The inputs rows that pass the FILTER @@ -153,6 +152,22 @@ class StreamingWindowState : public OperatorState { chunk.Reset(); } + // Limit a returned data chunk + template + T Limit(DataChunk &output, optional_idx partition_limit, const T result) { + if (!partition_limit.IsValid()) { + return result; + } + + const auto remaining = partition_limit.GetIndex() - emitted_count; + if (remaining < output.size()) { + output.Slice(0, remaining); + } + emitted_count += output.size(); + + return output.size() ? result : T::FINISHED; + } + public: //! We can't initialise until we have an input chunk bool initialized; @@ -170,6 +185,8 @@ class StreamingWindowState : public OperatorState { //! Set when `delayed` has been flushed into the output by reference - we must defer resetting (resizing) it //! until the next call, by which point the referencing output chunk has been consumed. bool flushed_delayed = false; + //! The number of rows emitted (for limiting) + idx_t emitted_count = 0; }; StreamingWindowGlobalState::StreamingWindowGlobalState(ClientContext &client) { @@ -277,12 +294,13 @@ void StreamingWindowState::AggregateState::Execute(ExecutionContext &context, Da SelectionVector sel(&s, 1); auto &arg_cursor = aggr_state.arg_cursor; arg_cursor.Reset(); - // This doesn't work for STRUCTs because the SV - // is not copied to the children when you slice + // This doesn't work for STRUCTs and ARRAYs because + // slicing them does not keep a reference to the SV vector structs; for (column_t col_idx = 0; col_idx < arg_chunk.ColumnCount(); ++col_idx) { const auto &col_vec = arg_cursor.data[col_idx]; - if (col_vec.GetType().InternalType() == PhysicalType::STRUCT) { + const auto internal_type = col_vec.GetType().InternalType(); + if (internal_type == PhysicalType::STRUCT || internal_type == PhysicalType::ARRAY) { structs.emplace_back(col_idx); } else { arg_cursor.data[col_idx].Slice(arg_chunk.data[col_idx], sel, 1); @@ -294,10 +312,10 @@ void StreamingWindowState::AggregateState::Execute(ExecutionContext &context, Da aggr_state.arena_allocator); for (idx_t i = 0; i < count; ++i) { sel.set_index(0, i); - for (const auto struct_idx : structs) { - arg_cursor.data[struct_idx].Slice(arg_chunk.data[struct_idx], sel, 1); - } if (filter_mask.RowIsValid(i) && distinct_mask.RowIsValid(i)) { + for (const auto struct_idx : structs) { + arg_cursor.data[struct_idx].Slice(arg_chunk.data[struct_idx], sel, 1); + } aggregate.GetStateUpdateCallback()(arg_cursor.data.data(), aggr_input_data, arg_cursor.ColumnCount(), statev, 1); } @@ -305,6 +323,13 @@ void StreamingWindowState::AggregateState::Execute(ExecutionContext &context, Da } } +PipelineSourceConsumption PhysicalStreamingWindow::GetSourceConsumption() const { + if (partition_limit.IsValid()) { + return PipelineSourceConsumption::MAY_STOP_EARLY; + } + return PhysicalOperator::GetSourceConsumption(); +} + void PhysicalStreamingWindow::ExecuteFunctions(ExecutionContext &context, DataChunk &output, DataChunk &delayed, GlobalOperatorState &gstate_p) const { auto &gstate = gstate_p.Cast(); @@ -407,7 +432,7 @@ OperatorResultType PhysicalStreamingWindow::Execute(ExecutionContext &context, D // Without LEAD nothing is ever delayed (the delayed buffer is not even initialized), so emit the input // directly. ExecuteInput(context, delayed, input, output, gstate_p); - return OperatorResultType::NEED_MORE_INPUT; + return state.Limit(output, partition_limit, OperatorResultType::NEED_MORE_INPUT); } // We can Reset delayed now that no one can be referencing it (the previous output has been consumed). if (state.flushed_delayed) { @@ -421,14 +446,14 @@ OperatorResultType PhysicalStreamingWindow::Execute(ExecutionContext &context, D // then just delay more rows, return nothing // and ask for more data. delayed.Append(input); - return OperatorResultType::NEED_MORE_INPUT; + return state.Limit(output, partition_limit, OperatorResultType::NEED_MORE_INPUT); } else if (input.size() < delayed.size()) { // If we can't consume all of the delayed values, // we need to split them instead of referencing them all output.SetChildCardinality(input.size()); ExecuteShifted(context, delayed, input, output, gstate_p); // We delayed the unused input so ask for more - return OperatorResultType::NEED_MORE_INPUT; + return state.Limit(output, partition_limit, OperatorResultType::NEED_MORE_INPUT); } else if (delayed.size()) { // We have enough delayed rows so flush them ExecuteDelayed(context, delayed, input, output, gstate_p); @@ -436,11 +461,11 @@ OperatorResultType PhysicalStreamingWindow::Execute(ExecutionContext &context, D // output has been consumed), since resizing its buffers now would corrupt the referencing output chunk. state.flushed_delayed = true; // Come back to process the input - return OperatorResultType::HAVE_MORE_OUTPUT; + return state.Limit(output, partition_limit, OperatorResultType::HAVE_MORE_OUTPUT); } else { // No delayed rows, so emit what we can and delay the rest. ExecuteInput(context, delayed, input, output, gstate_p); - return OperatorResultType::NEED_MORE_INPUT; + return state.Limit(output, partition_limit, OperatorResultType::NEED_MORE_INPUT); } } @@ -459,7 +484,7 @@ OperatorFinalizeResultType PhysicalStreamingWindow::FinalExecute(ExecutionContex // More than one output buffer was delayed, so shift in what we can output.SetChildCardinality(STANDARD_VECTOR_SIZE); ExecuteShifted(context, delayed, input, output, gstate_p); - return OperatorFinalizeResultType::HAVE_MORE_OUTPUT; + return state.Limit(output, partition_limit, OperatorFinalizeResultType::HAVE_MORE_OUTPUT); } ExecuteDelayed(context, delayed, input, output, gstate_p); } @@ -477,6 +502,10 @@ InsertionOrderPreservingMap PhysicalStreamingWindow::ParamsToString() co projections += select_list[i]->GetName(); } result["Projections"] = projections; + if (partition_limit.IsValid()) { + result["Limit"] = to_string(partition_limit.GetIndex()); + } + SetEstimatedCardinality(result, estimated_cardinality); return result; } diff --git a/src/duckdb/src/execution/operator/aggregate/physical_ungrouped_aggregate.cpp b/src/duckdb/src/execution/operator/aggregate/physical_ungrouped_aggregate.cpp index a0aef15b0..ce25e845a 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_ungrouped_aggregate.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_ungrouped_aggregate.cpp @@ -233,7 +233,9 @@ void UngroupedAggregateExecuteState::Sink(LocalUngroupedAggregateState &state, D if (aggregate.GetFilter()) { auto &filtered_data = filter_set.GetFilterData(aggr_idx); chunk_count = filtered_data.selected_count; - sel = &filtered_data.true_sel; + if (!filtered_data.all_selected) { + sel = &filtered_data.true_sel; + } } if (chunk_count == 0) { continue; diff --git a/src/duckdb/src/execution/operator/aggregate/physical_window.cpp b/src/duckdb/src/execution/operator/aggregate/physical_window.cpp index fd67faea1..3b0c69684 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_window.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_window.cpp @@ -1,3 +1,4 @@ +#include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/execution/operator/aggregate/physical_window.hpp" #include "duckdb/common/once_flag.hpp" @@ -55,7 +56,7 @@ class WindowHashGroup { WindowHashGroup(WindowGlobalSinkState &gsink, const ChunkRow &chunk_row, idx_t group_idx, idx_t bin_idx); void AllocateMasks(); - void ComputeMasks(const idx_t begin_idx, const idx_t end_idx); + void ComputeMasks(const idx_t begin_idx, const idx_t end_idx, unordered_map &prefixes); ExecutorGlobalStates &GetGlobalStates(ClientContext &client); @@ -266,7 +267,7 @@ class WindowLocalSinkState : public LocalSinkState { }; // this implements a sorted window functions variant -PhysicalWindow::PhysicalWindow(PhysicalPlan &physical_plan, vector types, +PhysicalWindow::PhysicalWindow(PhysicalPlan &physical_plan, ClientContext &context, vector types, vector> select_list_p, idx_t estimated_cardinality, vector partitions) : PhysicalOperator(physical_plan, TYPE, std::move(types), estimated_cardinality), @@ -286,11 +287,36 @@ PhysicalWindow::PhysicalWindow(PhysicalPlan &physical_plan, vector max_orders = bound_window.OrderBy().size(); } } + + // the comparisons of the sorted partition and order keys + auto &sort_expr = select_list[order_idx]->Cast(); + vector key_types; + if (!partition_info.RequiresPartitionColumns()) { + for (auto &partition : sort_expr.Partitions()) { + key_types.push_back(partition->GetReturnType()); + } + } + const auto order_begin = key_types.size(); + for (auto &order : sort_expr.OrderBy()) { + key_types.push_back(order.expression->GetReturnType()); + } + auto create_distinct_from = [&](idx_t end, idx_t begin) { + auto type = WindowCollectionChunkScanner::PrefixStructType(key_types, end, begin); + return BoundComparisonExpression::CreateOnColumns(context, ExpressionType::COMPARE_DISTINCT_FROM, type, 0, type, + 1); + }; + partition_distinct_from = create_distinct_from(order_begin, 0); + for (auto &expr : select_list) { + const auto end = order_begin + expr->Cast().OrderBy().size(); + if (end > order_begin && !order_distinct_from.count(end)) { + order_distinct_from[end] = create_distinct_from(end, order_begin); + } + } } -PhysicalWindow::PhysicalWindow(PhysicalPlan &physical_plan, vector types, +PhysicalWindow::PhysicalWindow(PhysicalPlan &physical_plan, ClientContext &context, vector types, vector> select_list, idx_t estimated_cardinality) - : PhysicalWindow(physical_plan, std::move(types), std::move(select_list), estimated_cardinality, + : PhysicalWindow(physical_plan, context, std::move(types), std::move(select_list), estimated_cardinality, vector()) { } @@ -596,7 +622,8 @@ void WindowHashGroup::AllocateMasks() { }); } -void WindowHashGroup::ComputeMasks(const idx_t block_begin, const idx_t block_end) { +void WindowHashGroup::ComputeMasks(const idx_t block_begin, const idx_t block_end, + unordered_map &prefixes) { D_ASSERT(count > 0); // Initialise our range @@ -634,17 +661,24 @@ void WindowHashGroup::ComputeMasks(const idx_t block_begin, const idx_t block_en auto &collection = *rows; auto &scan_cols = gsink.sort_strategy->sort_ids; WindowCollectionChunkScanner scanner(collection, scan_cols, block_begin); - unordered_map prefixes; + unordered_map> distinct_from; for (auto &order_mask : order_masks) { D_ASSERT(order_mask.first >= order_begin); - auto order_type = scanner.PrefixStructType(order_mask.first, order_begin); - vector types(2, order_type); auto &keys = prefixes[order_mask.first]; - // We can't use InitializeEmpty here because it doesn't set up all of the STRUCT internals... - keys.Initialize(collection.GetAllocator(), types); + if (keys.ColumnCount() == 0) { + auto order_type = scanner.PrefixStructType(order_mask.first, order_begin); + vector types(2, order_type); + keys.Initialize(collection.GetAllocator(), types); + } + if (order_mask.first == order_begin) { + continue; + } + distinct_from[order_mask.first] = make_uniq( + gsink.client.GetContext(), *gsink.op.order_distinct_from.at(order_mask.first)); } - WindowDeltaScanner(collection, block_begin, block_end, scan_cols, order_begin, + WindowDeltaScanner(gsink.client.GetContext(), *gsink.op.partition_distinct_from, collection, block_begin, block_end, + scan_cols, order_begin, [&](const idx_t row_idx, DataChunk &prev, DataChunk &curr, const idx_t ndistinct, SelectionVector &distinct, const SelectionVector &matching) { // Process the partition boundaries @@ -678,16 +712,23 @@ void WindowHashGroup::ComputeMasks(const idx_t block_begin, const idx_t block_en if (ndistinct) { prefix.Slice(matching, nmatch); } else { - prefix.SetChildCardinality(nmatch); + // Slice instead of resizing: the vectors share their buffers with prev and curr + for (auto &vec : prefix.data) { + vec.Slice(Vector::Ref(vec), 0, nmatch); + } + prefix.CheckCardinality(nmatch); } - const auto m = VectorOperations::DistinctFrom(order_curr, order_prev, nullptr, nmatch, - &distinct, nullptr); + const auto m = distinct_from[order_mask.first]->SelectExpression( + prefix, &distinct, nullptr, nullptr, nmatch); for (idx_t i = 0; i < m; ++i) { const idx_t curr_index = row_idx + matching.get_index(distinct.get_index(i)); order_mask.second.SetValidUnsafe(curr_index); } } }); + for (auto &prefix : prefixes) { + prefix.second.Reset(); + } } // Per-thread scan state @@ -726,6 +767,7 @@ class WindowLocalSourceState : public LocalSourceState { unique_ptr scanner; //! Buffer for window results DataChunk output_chunk; + unordered_map boundary_prefixes; protected: //! Sort the partition @@ -806,7 +848,7 @@ void WindowLocalSourceState::Mask(ExecutionContext &context, InterruptState &int D_ASSERT(task); D_ASSERT(task->stage == WindowGroupStage::MASK); - window_hash_group->ComputeMasks(task->begin_idx, task->end_idx); + window_hash_group->ComputeMasks(task->begin_idx, task->end_idx, boundary_prefixes); // Mark this range as done window_hash_group->masked += (task->end_idx - task->begin_idx); diff --git a/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp b/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp index b11b77564..51a214bbe 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp @@ -2,9 +2,12 @@ #include "duckdb/catalog/catalog.hpp" #include "duckdb/common/exception.hpp" -#include "duckdb/main/config.hpp" +#include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp" +#include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" #include "duckdb/function/encoding_function.hpp" #include "duckdb/main/extension_helper.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" namespace duckdb { @@ -41,19 +44,13 @@ void CSVEncoderBuffer::Reset() { CSVEncoder::CSVEncoder(ClientContext &context_p, const string &encoding_name_to_find, idx_t buffer_size) : context(context_p), pass_on_byte(0) { - auto &config = DBConfig::GetConfig(context_p); encoding_name = StringUtil::Lower(encoding_name_to_find); - auto function = config.GetEncodeFunction(encoding_name_to_find); - if (!function) { - // Maybe we can try to auto-load from our encodings extension, if this somehow fails, we just error. - if (Catalog::TryAutoLoad(context_p, "encodings")) { - // If it successfully loaded, we can try to get our function again - function = config.GetEncodeFunction(encoding_name_to_find); - } + if (encoding_name == "utf-8") { + // UTF-8 is read straight into the CSV buffers (see CSVFileHandle::Read), the encoder buffers are never used + return; } - if (!function) { - // If at this point we still do not have a function we throw an error. - auto loaded_encodings = config.GetLoadedEncodedFunctions(); + auto entry = EncodingFunction::Find(context_p, encoding_name); + if (!entry) { std::ostringstream error; error << "The CSV Reader does not support the encoding: \"" << encoding_name_to_find << "\"\n"; if (!context_p.db->ExtensionIsLoaded("encodings")) { @@ -62,73 +59,113 @@ CSVEncoder::CSVEncoder(ClientContext &context_p, const string &encoding_name_to_ << "\n"; } error << "The currently supported encodings are: " << '\n'; - for (auto &encoding_function : loaded_encodings) { - error << "* " << encoding_function.get().GetName() << '\n'; + for (auto &name : EncodingFunction::GetEncodings(context_p)) { + error << "* " << name << '\n'; } throw InvalidInputException(error.str()); } - encoding_function = function; - if (encoding_name == "utf-8") { - // UTF-8 is read straight into the CSV buffers (see CSVFileHandle::Read), the encoder buffers are never used - return; + // Bind the streaming overload: decode_(encoded BLOB, is_last BOOLEAN) + auto function = entry->functions.GetFunctionByArguments(context_p, {LogicalType::BLOB, LogicalType::BOOLEAN}); + vector> children; + children.push_back(make_uniq(LogicalType::BLOB, 0)); + children.push_back(make_uniq(LogicalType::BOOLEAN, 1)); + decode_expression = function->Bind(context_p, std::move(children)); + decode_executor = make_uniq(context_p, *decode_expression); + decode_input.Initialize(context_p, {LogicalType::BLOB, LogicalType::BOOLEAN}, 1); + + auto window = function->GetProperties().GetProperty(EncodingFunction::MINIMUM_INPUT_WINDOW_PROPERTY); + if (window) { + minimum_input_window = MaxValue(window->GetValue(), 1); } - // The encoded buffer is even for the two byte lookup of utf-16, and fits a full lookup plus the probe byte - const idx_t lookup_bytes = function->GetLookupBytes(); - encoded_buffer.Initialize(MaxValue(buffer_size - buffer_size % 2, lookup_bytes + lookup_bytes % 2)); - remaining_bytes_buffer.Initialize(function->GetBytesPerIteration()); + // The encoded buffer is even for utf-16, and fits a full input window plus the probe byte + encoded_buffer.Initialize(MaxValue(buffer_size - buffer_size % 2, 2 * minimum_input_window + 2)); } void CSVEncoder::Reset() { encoded_buffer.Reset(); encoded_buffer.last_buffer = false; - remaining_bytes_buffer.Reset(); + pending_decoded.clear(); + pending_pos = 0; has_pass_on_byte = false; encoded_bytes_read = 0; } +idx_t CSVEncoder::Decode(const char *input, idx_t input_size, bool is_last, string &decoded) { + decode_input.Reset(); + decode_input.SetChildCardinality(1); + FlatVector::GetDataMutable(decode_input.data[0])[0] = + string_t(input, UnsafeNumericCast(input_size)); + FlatVector::GetDataMutable(decode_input.data[1])[0] = is_last; + Vector result(EncodingFunction::StreamResultType(), 1); + decode_executor->ExecuteExpression(decode_input, result); + auto values = result.Values>(); + auto entry = values[0]; + auto decoded_value = entry.GetChildValue<0>().GetValue(); + decoded.assign(decoded_value.GetData(), decoded_value.GetSize()); + return UnsafeNumericCast(entry.GetChildValue<1>().GetValue()); +} + +idx_t CSVEncoder::DecodeBuffer(char *output_buffer, idx_t output_pos, idx_t output_size) { + string decoded; + while (encoded_buffer.HasDataToRead() && output_pos < output_size) { + const idx_t available = encoded_buffer.GetSize() - encoded_buffer.cur_pos; + // Decode as much input as there is room in the output, extended until it holds a complete character + idx_t slice = MinValue(MaxValue(output_size - output_pos, minimum_input_window), available); + idx_t consumed = 0; + while (true) { + const bool is_last = encoded_buffer.last_buffer && slice == available; + consumed = Decode(encoded_buffer.Ptr() + encoded_buffer.cur_pos, slice, is_last, decoded); + if (consumed != 0 || slice == available) { + break; + } + slice = MinValue(slice * 2, available); + } + if (consumed == 0) { + // An incomplete character at the end of the buffer + break; + } + encoded_buffer.cur_pos += consumed; + const idx_t to_copy = MinValue(decoded.size(), output_size - output_pos); + memcpy(output_buffer + output_pos, decoded.data(), to_copy); // NOLINT(bugprone-not-null-terminated-result) + output_pos += to_copy; + if (to_copy < decoded.size()) { + pending_decoded.assign(decoded, to_copy, string::npos); + pending_pos = 0; + } + } + return output_pos; +} + idx_t CSVEncoder::Encode(FileHandle &file_handle_input, char *output_buffer, const idx_t decoded_buffer_size) { idx_t output_buffer_pos = 0; // Check if we have some left-overs. These can either be - // 1. missing decoded bytes - if (remaining_bytes_buffer.HasDataToRead()) { - D_ASSERT(remaining_bytes_buffer.cur_pos == 0); - const auto remaining_bytes_buffer_ptr = remaining_bytes_buffer.Ptr(); - for (; remaining_bytes_buffer.cur_pos < remaining_bytes_buffer.GetSize(); remaining_bytes_buffer.cur_pos++) { - output_buffer[output_buffer_pos++] = remaining_bytes_buffer_ptr[remaining_bytes_buffer.cur_pos]; - } - remaining_bytes_buffer.Reset(); + // 1. decoded bytes that did not fit the previous output buffer + if (pending_pos < pending_decoded.size()) { + const idx_t to_copy = MinValue(pending_decoded.size() - pending_pos, decoded_buffer_size); + memcpy(output_buffer, pending_decoded.data() + pending_pos, to_copy); + pending_pos += to_copy; + output_buffer_pos += to_copy; } // 2. remaining encoded buffer - if (encoded_buffer.HasDataToRead()) { - encoding_function->GetFunction()(encoded_buffer, output_buffer, output_buffer_pos, decoded_buffer_size, - remaining_bytes_buffer.Ptr(), - remaining_bytes_buffer.actual_encoded_buffer_size, encoding_function.get()); + if (pending_pos == pending_decoded.size()) { + output_buffer_pos = DecodeBuffer(output_buffer, output_buffer_pos, decoded_buffer_size); } // 3. a new encoded buffer from the file while (output_buffer_pos < decoded_buffer_size) { idx_t current_decoded_buffer_start = output_buffer_pos; - vector pass_on_buffer; - if (encoded_buffer.cur_pos != encoded_buffer.GetSize() && - encoding_function->GetLookupBytes() > encoded_buffer.GetSize() - encoded_buffer.cur_pos) { - // We don't have enough lookup bytes for it, if that's the case, we need to set off these bytes to the next - // buffer - for (idx_t i = encoded_buffer.cur_pos; i < encoded_buffer.GetSize(); i++) { - pass_on_buffer.push_back(encoded_buffer.Ptr()[i]); - } - } + // An incomplete character at the end of the buffer is moved to the start of the next buffer + const idx_t tail_size = encoded_buffer.GetSize() - encoded_buffer.cur_pos; + memmove(encoded_buffer.Ptr(), encoded_buffer.Ptr() + encoded_buffer.cur_pos, tail_size); encoded_buffer.Reset(); - for (idx_t i = 0; i < pass_on_buffer.size(); i++) { - encoded_buffer.Ptr()[i] = pass_on_buffer[i]; - } if (has_pass_on_byte) { - encoded_buffer.Ptr()[pass_on_buffer.size()] = pass_on_byte; + encoded_buffer.Ptr()[tail_size] = pass_on_byte; } - const idx_t bytes_to_read = encoded_buffer.GetCapacity() - pass_on_buffer.size() - has_pass_on_byte; - auto actual_encoded_bytes = static_cast(file_handle_input.Read( - context, encoded_buffer.Ptr() + pass_on_buffer.size() + has_pass_on_byte, bytes_to_read)); + const idx_t bytes_to_read = encoded_buffer.GetCapacity() - tail_size - has_pass_on_byte; + auto actual_encoded_bytes = static_cast( + file_handle_input.Read(context, encoded_buffer.Ptr() + tail_size + has_pass_on_byte, bytes_to_read)); encoded_bytes_read += actual_encoded_bytes; - encoded_buffer.SetSize(actual_encoded_bytes + pass_on_buffer.size() + has_pass_on_byte); + encoded_buffer.SetSize(actual_encoded_bytes + tail_size + has_pass_on_byte); if (actual_encoded_bytes < bytes_to_read) { encoded_buffer.last_buffer = true; has_pass_on_byte = false; @@ -142,9 +179,7 @@ idx_t CSVEncoder::Encode(FileHandle &file_handle_input, char *output_buffer, con has_pass_on_byte = true; } } - encoding_function->GetFunction()(encoded_buffer, output_buffer, output_buffer_pos, decoded_buffer_size, - remaining_bytes_buffer.Ptr(), - remaining_bytes_buffer.actual_encoded_buffer_size, encoding_function.get()); + output_buffer_pos = DecodeBuffer(output_buffer, output_buffer_pos, decoded_buffer_size); if (output_buffer_pos == current_decoded_buffer_start) { return output_buffer_pos; } diff --git a/src/duckdb/src/execution/operator/csv_scanner/scanner/column_count_scanner.cpp b/src/duckdb/src/execution/operator/csv_scanner/scanner/column_count_scanner.cpp index 693dbb496..346f98c74 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/scanner/column_count_scanner.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/scanner/column_count_scanner.cpp @@ -104,6 +104,8 @@ void ColumnCountResult::InvalidState(ColumnCountResult &result) { bool ColumnCountResult::EmptyLine(ColumnCountResult &result, idx_t buffer_pos) { result.empty_lines++; + // the next line starts behind the empty line, the empty lines before a row are not part of its size + result.last_position = {result.cur_buffer_idx, buffer_pos + 1, result.current_buffer_size}; return false; } diff --git a/src/duckdb/src/execution/operator/csv_scanner/scanner/skip_scanner.cpp b/src/duckdb/src/execution/operator/csv_scanner/scanner/skip_scanner.cpp index 03dc39b38..6507e864e 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/scanner/skip_scanner.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/scanner/skip_scanner.cpp @@ -20,7 +20,8 @@ void SkipResult::QuotedNewLine(SkipResult &result) { } void SkipResult::SetComment(SkipResult &result, idx_t buffer_pos) { - if (!result.states.WasStandard()) { + // The rule of the sniffer, which counts the lines to skip: a comment behind a delimiter does not start the line + if (!result.states.WasStandard() && !result.states.WasState(CSVState::DELIMITER)) { result.cur_line_starts_as_comment = true; } result.comment = true; diff --git a/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp b/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp index 300b05880..a4f18cbd2 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp @@ -225,11 +225,8 @@ bool StringValueResult::UnsetComment(StringValueResult &result, idx_t buffer_pos result.first_line_is_comment = true; } result.comment = false; - if (result.state_machine.dialect_options.state_machine_options.new_line.GetValue() != NewLineIdentifier::CARRY_ON) { - result.last_position.buffer_pos = buffer_pos + 1; - } else { - result.last_position.buffer_pos = buffer_pos + 2; - } + // The next line starts behind the line break that ended the comment + result.SetLastPositionAfterNewline(buffer_pos); LinePosition current_line_start = {result.iterator.pos.buffer_idx, result.iterator.pos.buffer_pos, result.buffer_size}; result.current_line_position.begin = result.current_line_position.end; @@ -1023,6 +1020,17 @@ void StringValueResult::InvalidState(StringValueResult &result) { } } +void StringValueResult::StartLineAfterEmptyLine() { + // The empty lines before a row are not part of its size: the next line starts at the last byte of this line break + idx_t line_break_pos = iterator.pos.buffer_pos; + if (states.IsCarriageReturn() && + state_machine.dialect_options.state_machine_options.new_line == NewLineIdentifier::CARRY_ON) { + line_break_pos++; + } + current_line_position.begin = current_line_position.end; + current_line_position.end = {iterator.pos.buffer_idx, line_break_pos, buffer_size}; +} + bool StringValueResult::EmptyLine(StringValueResult &result, const idx_t buffer_pos) { // We care about empty lines if this is a single column csv file result.last_position = {result.iterator.pos.buffer_idx, result.iterator.pos.buffer_pos + 1, result.buffer_size}; @@ -1030,6 +1038,7 @@ bool StringValueResult::EmptyLine(StringValueResult &result, const idx_t buffer_ result.state_machine.dialect_options.state_machine_options.new_line == NewLineIdentifier::CARRY_ON) { result.last_position.buffer_pos++; } + result.StartLineAfterEmptyLine(); if (result.number_of_columns == 1) { bool empty_is_null = false; for (idx_t i = 0; i < result.null_str_count && !empty_is_null; i++) { @@ -1484,7 +1493,9 @@ void StringValueScanner::ProcessOverBufferValue() { if (over_buffer_string.empty() && state_machine->dialect_options.state_machine_options.new_line == NewLineIdentifier::CARRY_ON) { if (!iterator.IsBoundarySet()) { - if (buffer_handle_ptr[iterator.pos.buffer_pos] == '\n') { + // Skip the line feed of a \r\n that the buffer end split, a line feed of its own ends a line + if (buffer_handle_ptr[iterator.pos.buffer_pos] == '\n' && previous_buffer_handle->actual_size > 0 && + previous_buffer[previous_buffer_handle->actual_size - 1] == '\r') { iterator.pos.buffer_pos++; } } else { @@ -1533,6 +1544,9 @@ void StringValueScanner::ProcessOverBufferValue() { if (state_machine->dialect_options.num_cols == 1) { break; } + if (result.cur_col_id == 0) { + result.StartLineAfterEmptyLine(); + } continue; } if (states.NewRow() || states.NewValue()) { diff --git a/src/duckdb/src/execution/operator/csv_scanner/table_function/global_csv_state.cpp b/src/duckdb/src/execution/operator/csv_scanner/table_function/global_csv_state.cpp index d29f7b133..b4994606a 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/table_function/global_csv_state.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/table_function/global_csv_state.cpp @@ -14,14 +14,14 @@ namespace duckdb { CSVGlobalState::CSVGlobalState(ClientContext &context_p, ReadCSVData &csv_data_p, - const vector &column_names_p, idx_t total_file_count_p, + const vector &column_names_p, idx_t file_count, optional_ptr scan_op_p) - : context(context_p), csv_data(csv_data_p), scan_op(scan_op_p), total_file_count(total_file_count_p), - column_names(column_names_p), sniffer_mismatch_error(csv_data_p.options.sniffer_user_mismatch_error) { + : context(context_p), csv_data(csv_data_p), scan_op(scan_op_p), column_names(column_names_p), + sniffer_mismatch_error(csv_data_p.options.sniffer_user_mismatch_error) { auto &options = csv_data.options; // There are situations where we only support single threaded scanning auto system_threads = context.db->NumberOfThreads(); - bool many_csv_files = total_file_count > 1 && total_file_count > system_threads * 2; + bool many_csv_files = file_count > 1 && file_count > system_threads * 2; single_threaded = many_csv_files || !options.parallel; scanner_idx = 0; initialized = false; @@ -237,11 +237,7 @@ void CSVGlobalState::FillRejectsTable(CSVFileScan &scan) { InternalAppender scans_appender(context, scans_table); idx_t scan_idx = context.transaction.GetActiveQuery(); - // the files of a scan report under a block of indexes, so that the index of a file within its scan identifies - // it - that keeps the indexes deterministic when files are read in parallel, and keeps the files of one scan - // apart from those of another scan in the same query - const idx_t rejects_file_idx = - rejects->GetFileIndexBase(scan_idx, scan_op.get(), total_file_count) + scan.GetFileIndex(); + const idx_t rejects_file_idx = rejects->GetFileIndex(scan_idx, scan_op, scan.GetFileIndex()); scan.error_handler->FillRejectsTable(errors_appender, rejects_file_idx, scan_idx, scan, *rejects, column_names, limit); if (rejects->count != 0) { diff --git a/src/duckdb/src/execution/operator/csv_scanner/table_function/read_single_csv_file.cpp b/src/duckdb/src/execution/operator/csv_scanner/table_function/read_single_csv_file.cpp index 0f768c747..e100ddc96 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/table_function/read_single_csv_file.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/table_function/read_single_csv_file.cpp @@ -6,6 +6,7 @@ #include "duckdb/execution/operator/csv_scanner/sniffer/csv_sniffer.hpp" #include "duckdb/execution/operator/persistent/csv_rejects_table.hpp" #include "duckdb/function/table/read_csv.hpp" +#include "duckdb/main/database.hpp" namespace duckdb { @@ -17,11 +18,20 @@ struct ReadSingleCSVFileData : public ReadCSVData { vector csv_types; }; +static idx_t GetCSVFileCount(ClientContext &context, const TableFunctionInitInput &input) { + auto &file_input = TableFunctionFileInitInput::Get(input); + if (!file_input.file_list) { + return 1; + } + // Parallelism only needs to know whether there are more than twice as many files as threads. + return file_input.file_list->GetFileCount(context.db->NumberOfThreads() * 2 + 1).count; +} + struct ReadSingleCSVFileGlobalState : public GlobalTableFunctionState { public: ReadSingleCSVFileGlobalState(ClientContext &context, ReadSingleCSVFileData &csv_data, const TableFunctionInitInput &input) - : state(context, csv_data, csv_data.csv_names, TableFunctionFileInitInput::Get(input).file_count, input.op) { + : state(context, csv_data, csv_data.csv_names, GetCSVFileCount(context, input), input.op) { } public: diff --git a/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp b/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp index 082dd992f..4595bec66 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp @@ -115,10 +115,6 @@ void CSVReaderOptions::SetCompression(const string &compression_p) { this->compression = FileCompressionType(compression_p); } -string CSVReaderOptions::GetEscape() const { - return std::string(1, this->dialect_options.state_machine_options.escape.GetValue()); -} - void CSVReaderOptions::SetEscape(const string &input) { auto escape_str = input; if (escape_str.size() > 1) { @@ -141,10 +137,6 @@ void CSVReaderOptions::SetSkipRows(int64_t skip_rows) { dialect_options.skip_rows.Set(NumericCast(skip_rows)); } -string CSVReaderOptions::GetDelimiter() const { - return this->dialect_options.state_machine_options.delimiter.GetValue(); -} - void CSVReaderOptions::SetDelimiter(const string &input) { auto delim_str = StringUtil::Replace(input, "\\t", "\t"); if (delim_str.size() > 4) { @@ -157,10 +149,6 @@ void CSVReaderOptions::SetDelimiter(const string &input) { this->dialect_options.state_machine_options.delimiter.Set(delim_str); } -string CSVReaderOptions::GetQuote() const { - return std::string(1, this->dialect_options.state_machine_options.quote.GetValue()); -} - void CSVReaderOptions::SetQuote(const string "e_p) { auto quote_str = quote_p; if (quote_str.size() > 1) { @@ -172,10 +160,6 @@ void CSVReaderOptions::SetQuote(const string "e_p) { this->dialect_options.state_machine_options.quote.Set(quote_str[0]); } -string CSVReaderOptions::GetComment() const { - return std::string(1, this->dialect_options.state_machine_options.comment.GetValue()); -} - void CSVReaderOptions::SetComment(const string &comment_p) { auto comment_str = comment_p; if (comment_str.size() > 1) { @@ -187,21 +171,6 @@ void CSVReaderOptions::SetComment(const string &comment_p) { this->dialect_options.state_machine_options.comment.Set(comment_str[0]); } -string CSVReaderOptions::GetNewline() const { - switch (dialect_options.state_machine_options.new_line.GetValue()) { - case NewLineIdentifier::CARRY_ON: - return "\\r\\n"; - case NewLineIdentifier::SINGLE_R: - return "\\r"; - case NewLineIdentifier::SINGLE_N: - return "\\n"; - case NewLineIdentifier::NOT_SET: - return ""; - default: - throw NotImplementedException("New line type not supported"); - } -} - void CSVReaderOptions::SetNewline(const string &input) { if (input == "\\n") { dialect_options.state_machine_options.new_line.Set(NewLineIdentifier::SINGLE_N); @@ -214,10 +183,6 @@ void CSVReaderOptions::SetNewline(const string &input) { } } -bool CSVReaderOptions::GetRFC4180() const { - return this->dialect_options.state_machine_options.strict_mode.GetValue(); -} - void CSVReaderOptions::SetRFC4180(bool input) { this->dialect_options.state_machine_options.strict_mode.Set(input); } @@ -552,15 +517,6 @@ string CSVReaderOptions::ToString(const String ¤t_file_path) const { return error; } -static Value StringVectorToValue(const vector &vec) { - vector content; - content.reserve(vec.size()); - for (auto &item : vec) { - content.push_back(Value(item)); - } - return Value::LIST(LogicalType::VARCHAR, std::move(content)); -} - static uint8_t GetCandidateSpecificity(const LogicalType &candidate_type) { //! Const ht with accepted auto_types and their weights in specificity const duckdb::unordered_map auto_type_candidates_specificity { @@ -857,56 +813,5 @@ void CSVReaderOptions::ParseOption(ClientContext &context, const Identifier &key SetReadOption(context.GetContext(), key, val, name_list); } } -//! This function is used to remember options set by the sniffer, for use in ReadCSVRelation -void CSVReaderOptions::ToNamedParameters(named_parameter_map_t &named_params) const { - auto &delimiter = dialect_options.state_machine_options.delimiter; - auto "e = dialect_options.state_machine_options.quote; - auto &escape = dialect_options.state_machine_options.escape; - auto &comment = dialect_options.state_machine_options.comment; - auto &strict_mode = dialect_options.state_machine_options.strict_mode; - auto &header = dialect_options.header; - if (delimiter.IsSetByUser()) { - named_params["delim"] = Value(GetDelimiter()); - } - if (dialect_options.state_machine_options.new_line.IsSetByUser()) { - named_params["new_line"] = Value(GetNewline()); - } - if (quote.IsSetByUser()) { - named_params["quote"] = Value(GetQuote()); - } - if (escape.IsSetByUser()) { - named_params["escape"] = Value(GetEscape()); - } - if (comment.IsSetByUser()) { - named_params["comment"] = Value(GetComment()); - } - if (header.IsSetByUser()) { - named_params["header"] = Value(GetHeader()); - } - if (strict_mode.IsSetByUser()) { - named_params["strict_mode"] = Value(GetRFC4180()); - } - named_params["max_line_size"] = Value::BIGINT(NumericCast(maximum_line_size.GetValue())); - if (dialect_options.skip_rows.IsSetByUser()) { - named_params["skip"] = Value::BIGINT(NumericCast(GetSkipRows())); - } - named_params["null_padding"] = Value::BOOLEAN(null_padding); - named_params["parallel"] = Value::BOOLEAN(parallel); - if (!dialect_options.date_format.at(LogicalType::DATE).GetValue().format_specifier.empty()) { - named_params["dateformat"] = - Value(dialect_options.date_format.at(LogicalType::DATE).GetValue().format_specifier); - } - if (!dialect_options.date_format.at(LogicalType::TIMESTAMP).GetValue().format_specifier.empty()) { - named_params["timestampformat"] = - Value(dialect_options.date_format.at(LogicalType::TIMESTAMP).GetValue().format_specifier); - } - - named_params["normalize_names"] = Value::BOOLEAN(normalize_names); - if (!name_list.empty() && !named_params.count("columns") && !named_params.count("column_names") && - !named_params.count("names")) { - named_params["column_names"] = StringVectorToValue(name_list); - } - named_params["all_varchar"] = Value::BOOLEAN(all_varchar); -} } // namespace duckdb diff --git a/src/duckdb/src/execution/operator/helper/physical_disconnect.cpp b/src/duckdb/src/execution/operator/helper/physical_disconnect.cpp index b048c4f44..54a32d6b0 100644 --- a/src/duckdb/src/execution/operator/helper/physical_disconnect.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_disconnect.cpp @@ -18,7 +18,10 @@ SourceResultType PhysicalDisconnect::GetDataInternal(ExecutionContext &context, client.DisconnectFromCatalog(); if (target && target->IsEphemeral()) { // `CONNECT ''` attached this hidden catalog implicitly; detach it now. - DatabaseManager::Get(client).DetachDatabase(client, target->GetName(), OnEntryNotFound::RETURN_NULL); + auto name = target->GetName(); + // release our reference first so that the detach closes the database + AttachedDatabase::InvokeCloseIfLastReference(target, client); + DatabaseManager::Get(client).DetachDatabase(client, name, OnEntryNotFound::RETURN_NULL); } return SourceResultType::FINISHED; } diff --git a/src/duckdb/src/execution/operator/helper/physical_reset.cpp b/src/duckdb/src/execution/operator/helper/physical_reset.cpp index 6d6430317..de9498afa 100644 --- a/src/duckdb/src/execution/operator/helper/physical_reset.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_reset.cpp @@ -52,15 +52,15 @@ SourceResultType PhysicalReset::GetDataInternal(ExecutionContext &context, DataC // Transform scope SetScope variable_scope = PhysicalSet::GetSettingScope(*option, scope); - if (option->default_value) { + if (option->IsGeneric()) { + auto setting_index = option->setting_idx.GetIndex(); if (option->set_callback) { + auto parameter_type = DBConfig::ParseLogicalType(option->parameter_type); + auto reset_val = option->GetDefaultValue(config).CastAs(context.client, parameter_type); SettingCallbackInfo info(context.client, variable_scope); info.is_reset = true; - auto parameter_type = DBConfig::ParseLogicalType(option->parameter_type); - Value reset_val = Value(option->default_value).CastAs(context.client, parameter_type); option->set_callback(info, reset_val); } - auto setting_index = option->setting_idx.GetIndex(); if (variable_scope == SetScope::SESSION) { auto &client_config = ClientConfig::GetConfig(context.client); client_config.user_settings.ClearSetting(setting_index); diff --git a/src/duckdb/src/execution/operator/helper/physical_set.cpp b/src/duckdb/src/execution/operator/helper/physical_set.cpp index 970d514ab..168c9aa7e 100644 --- a/src/duckdb/src/execution/operator/helper/physical_set.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_set.cpp @@ -96,7 +96,7 @@ void PhysicalSet::SetVariable(ClientContext &context, const Identifier &name, Se SetScope variable_scope = GetSettingScope(*option, scope); Value input_val = value.CastAs(context, DBConfig::ParseLogicalType(option->parameter_type)); - if (option->default_value) { + if (option->IsGeneric()) { SettingCallbackInfo info(context, variable_scope); if (option->set_callback) { option->set_callback(info, input_val); diff --git a/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp b/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp new file mode 100644 index 000000000..489955acd --- /dev/null +++ b/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp @@ -0,0 +1,1008 @@ +#include "duckdb/execution/operator/join/join_filter_pushdown.hpp" + +#include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" +#include "duckdb/execution/join_hashtable.hpp" +#include "duckdb/execution/operator/aggregate/ungrouped_aggregate_state.hpp" +#include "duckdb/execution/operator/join/physical_comparison_join.hpp" +#include "duckdb/logging/log_manager.hpp" +#include "duckdb/main/settings.hpp" +#include "duckdb/optimizer/filter_combiner.hpp" +#include "duckdb/parallel/base_pipeline_event.hpp" +#include "duckdb/parallel/executor_task.hpp" +#include "duckdb/parallel/pipeline.hpp" +#include "duckdb/parallel/task_scheduler.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/filter/table_filter_functions.hpp" +#include "duckdb/planner/table_filter_set.hpp" +#include "duckdb/planner/table_filter_state.hpp" +#include "duckdb/storage/block_allocator.hpp" +#include "duckdb/storage/buffer_manager.hpp" + +#include + +namespace duckdb { + +struct JoinFilterPushdownConfig { + //! Building the bloom filter is costly on the build side to make probing faster, + //! so only use it if there are less build tuples than probing tuples + static constexpr double BUILD_TO_PROBE_RATIO_THRESHOLD = 1.0; + //! If we have a build side without a filter, only build the bloom filter if the ratio/size is small enough + static constexpr double NON_FILTERING_RATIO_THRESHOLD = 0.1; + static constexpr idx_t NON_FILTERING_BUILD_SIDE_THRESHOLD = 4194304; + //! Max build/probe ratio at which a multi-key join builds per-key-column filters + static constexpr double MULTI_KEY_RATIO_THRESHOLD = 0.05; + //! A join is expected to stay in memory while its estimated build side is below this share of the memory budget + static constexpr idx_t LIKELY_IN_MEMORY_BUILD_MEMORY_FRACTION = 4; + static constexpr idx_t MAX_MEMORY_FRACTION = 64; + //! A build side with more rows than the threshold can still have few distinct values in one of its key columns, + //! e.g. the partition key of a multi-column join. Counting them requires a scan of the key column, so only build + //! sides up to this many rows are scanned. + static constexpr idx_t IN_FILTER_MAX_BUILD_SCAN_COUNT = 65536; + static constexpr idx_t SMALL_EXACT_PRF_BITS = 1ULL << 26; +}; + +idx_t JoinFilterPushdownInfo::GetMemoryBudget(ClientContext &context) { + return BufferManager::GetBufferManager(context).GetMaxMemory() / JoinFilterPushdownConfig::MAX_MEMORY_FRACTION; +} + +//! Whether the build side is expected to exceed the memory budget and spill +static bool JoinIsLikelyExternal(ClientContext &context, const PhysicalComparisonJoin &op) { + if (Settings::Get(context)) { + return true; + } + idx_t row_width = sizeof(data_ptr_t) + sizeof(hash_t); // per-row pointer table and hash overhead + for (auto &type : op.children[1].get().GetTypes()) { + row_width += GetTypeIdSize(type.InternalType()); + } + const auto build_size = op.children[1].get().estimated_cardinality * row_width; + const auto memory_budget = BufferManager::GetBufferManager(context).GetMaxMemory(); + return build_size > memory_budget / JoinFilterPushdownConfig::LIKELY_IN_MEMORY_BUILD_MEMORY_FRACTION; +} + +static bool IsEqualityComparison(ExpressionType cmp) { + return cmp == ExpressionType::COMPARE_EQUAL || cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM; +} + +//! Whether to accumulate bloom filters during Sink. Only an external join needs that: its finalize only ever +//! materializes some partitions, so a filter built there would be incomplete, while every row passes through +//! Sink. An in-memory join builds its filters during finalize instead, where the actual build count and the +//! competing filter choices are known. The estimate-based checks mirror CanUseBloomFilter, which decides +//! publication once the actual build count is known. +static bool ShouldBuildBloomFilterInSink(ClientContext &context, const PhysicalComparisonJoin &op) { + if (!op.filter_pushdown || op.filter_pushdown->probe_info.empty()) { + return false; + } + idx_t equality_count = 0; + for (auto &cond : op.conditions) { + if (IsEqualityComparison(cond.GetComparisonType())) { + equality_count++; + } + } + if (equality_count == 0) { + return false; + } + const auto build_estimate = static_cast(op.children[1].get().estimated_cardinality); + const auto probe_estimate = static_cast(op.children[0].get().estimated_cardinality); + if (build_estimate > JoinFilterPushdownConfig::BUILD_TO_PROBE_RATIO_THRESHOLD * probe_estimate) { + return false; + } + if (equality_count > 1 && build_estimate > JoinFilterPushdownConfig::MULTI_KEY_RATIO_THRESHOLD * probe_estimate) { + return false; + } + if (!op.filter_pushdown->build_side_has_filter && + build_estimate > JoinFilterPushdownConfig::NON_FILTERING_RATIO_THRESHOLD * probe_estimate && + build_estimate > JoinFilterPushdownConfig::NON_FILTERING_BUILD_SIDE_THRESHOLD) { + return false; + } + return JoinIsLikelyExternal(context, op); +} + +JoinFilterGlobalState::~JoinFilterGlobalState() { +} + +JoinFilterLocalState::~JoinFilterLocalState() { +} + +unique_ptr JoinFilterPushdownInfo::GetGlobalState(ClientContext &context, + const PhysicalOperator &op) const { + // clear any previously set filters + // we can have previous filters for this operator in case of e.g. recursive CTEs + for (auto &info : probe_info) { + info.dynamic_filters->ClearFilters(op); + } + auto result = make_uniq(); + result->global_aggregate_state = + make_uniq(BufferAllocator::Get(context), min_max_aggregates); + return result; +} + +unique_ptr JoinFilterPushdownInfo::GetLocalState(JoinFilterGlobalState &gstate) const { + auto result = make_uniq(); + result->local_aggregate_state = make_uniq(*gstate.global_aggregate_state); + return result; +} + +void JoinFilterPushdownInfo::InitializeBloomFilters(ClientContext &context, const PhysicalComparisonJoin &op, + JoinHashTable &ht, shared_ptr recycled_filter) { + // a published filter is shared with probe-side scans and immutable, so it cannot be reused + if (recycled_filter && recycled_filter->IsPublished()) { + recycled_filter.reset(); + } + if (!ShouldBuildBloomFilterInSink(context, op)) { + ht.SetBloomFilters({}); + // an in-memory join builds its filter during finalize, which can still reuse the allocation; + // an iteration without a filter must not clear a slot that finalize has not consumed yet + if (recycled_filter) { + ht.SetRecycledBloomFilter(std::move(recycled_filter)); + } + return; + } + const auto build_estimate = MaxValue(op.children[1].get().estimated_cardinality, 1); + if (!ht.HasSingleEqualityKey()) { + // the hash table hashes all keys together, so each pushed key column gets a filter of its own + vector key_idxs; + for (auto &info : op.filter_pushdown->probe_info) { + for (auto &column : info.columns) { + const auto key_idx = op.filter_pushdown->join_condition[column.join_filter_idx]; + if (IsEqualityComparison(op.conditions[key_idx].GetComparisonType()) && + column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION && + std::find(key_idxs.begin(), key_idxs.end(), key_idx) == key_idxs.end()) { + key_idxs.push_back(key_idx); + } + } + } + ht.InitializeBloomFilters(key_idxs, build_estimate, GetMemoryBudget(context)); + return; + } + if (!recycled_filter) { + recycled_filter = make_shared_ptr(); + } + recycled_filter->Initialize(context, build_estimate); + ht.SetBloomFilter(0, std::move(recycled_filter)); +} + +void JoinFilterPushdownInfo::Sink(DataChunk &chunk, JoinFilterLocalState &lstate) const { + // if we are pushing any filters into a probe-side, compute the min/max over the columns that we are pushing + for (idx_t pushdown_idx = 0; pushdown_idx < join_condition.size(); pushdown_idx++) { + auto join_condition_idx = join_condition[pushdown_idx]; + for (idx_t i = 0; i < 2; i++) { + idx_t aggr_idx = pushdown_idx * 2 + i; + lstate.local_aggregate_state->Sink(chunk, join_condition_idx, aggr_idx, chunk.size()); + } + } +} + +void JoinFilterPushdownInfo::Combine(JoinFilterGlobalState &gstate, JoinFilterLocalState &lstate) const { + gstate.global_aggregate_state->Combine(*lstate.local_aggregate_state); +} + +static idx_t InFilterMaxBuildScanCount(idx_t dynamic_or_filter_threshold) { + return MaxValue(dynamic_or_filter_threshold, JoinFilterPushdownConfig::IN_FILTER_MAX_BUILD_SCAN_COUNT); +} + +bool JoinFilterPushdownInfo::CanUseInFilter(const ClientContext &context, optional_ptr ht, + const ExpressionType &cmp) const { + auto dynamic_or_filter_threshold = Settings::Get(context); + if (dynamic_or_filter_threshold <= 1) { + return false; + } + return ht && ht->Count() > 1 && ht->Count() <= InFilterMaxBuildScanCount(dynamic_or_filter_threshold) && + (cmp == ExpressionType::COMPARE_EQUAL || cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM); +} + +bool JoinFilterPushdownInfo::CanUseBloomFilter(const JoinFilterPushdownFilter &info, const ClientContext &context, + const PhysicalComparisonJoin &op, const ExpressionType &cmp, + optional_ptr ht) const { + if (!ht) { + return false; + } + + // bf is only supported for equality conditions + if (cmp != ExpressionType::COMPARE_EQUAL && cmp != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + return false; + } + + auto build_count = ht->Count(); + if (build_count == 0) { + build_count = ht->GetSinkCollection().Count(); + } + auto probe_cardinality = op.children[0].get().estimated_cardinality; + if (build_side_has_filter) { + probe_cardinality = MaxValue(info.estimated_scan_cardinality, probe_cardinality); + } + const double build_to_probe_ratio = static_cast(build_count) / static_cast(probe_cardinality); + if (build_to_probe_ratio > JoinFilterPushdownConfig::BUILD_TO_PROBE_RATIO_THRESHOLD) { + return false; + } + + // if we have a build side without a filter, only build the bloom filter if the ratio/size is small enough + if (!build_side_has_filter && build_to_probe_ratio > JoinFilterPushdownConfig::NON_FILTERING_RATIO_THRESHOLD && + build_count > JoinFilterPushdownConfig::NON_FILTERING_BUILD_SIDE_THRESHOLD) { + return false; + } + + // per-key filters only pay off when the build side is much smaller than the probe side + if (!ht->HasSingleEqualityKey() && build_to_probe_ratio > JoinFilterPushdownConfig::MULTI_KEY_RATIO_THRESHOLD) { + return false; + } + + return true; +} + +struct RuntimeFilterInput { + unique_ptr expression; + bool preserves_cast_errors; +}; + +static RuntimeFilterInput CreateRuntimeFilterInputExpression(ClientContext &context, + const JoinFilterPushdownColumn &column, + const LogicalType &runtime_type) { + bool preserves_cast_errors = false; + auto expression = RuntimeFilterCastUtil::CreateRuntimeFilterInputExpression(context, column, preserves_cast_errors); + D_ASSERT(expression->GetReturnType() == RuntimeFilterCastUtil::GetRuntimeFilterInputType(column, runtime_type)); + return {std::move(expression), preserves_cast_errors}; +} + +static unique_ptr RetainRuntimeFilterNulls(unique_ptr filter_expr, + unique_ptr null_check_input) { + if (!null_check_input) { + return filter_expr; + } + // Retain NULL join keys and inputs whose original cast can fail. + auto null_check = + ExpressionFilter::CreateNullCheckExpression(std::move(null_check_input), ExpressionType::OPERATOR_IS_NULL); + return make_uniq(ExpressionType::CONJUNCTION_OR, std::move(null_check), + std::move(filter_expr)); +} + +void JoinFilterPushdownInfo::DeferRuntimeFilter(DeferredRuntimeFilterType type, const PhysicalOperator &op, + const JoinFilterPushdownFilter &info, + const JoinFilterPushdownColumn &column, ProjectionIndex filter_col_idx, + idx_t key_idx, JoinFilterGlobalState &gstate) const { + gstate.deferred_runtime_filters.push_back({type, &op, info.dynamic_filters, column, filter_col_idx, key_idx}); +} + +bool JoinFilterPushdownInfo::TryRegisterPrefixRangeFilter(const JoinFilterPushdownFilter &info, ClientContext &context, + JoinHashTable &ht, const PhysicalOperator &op, + const JoinFilterPushdownColumn &column, + ProjectionIndex filter_col_idx, idx_t key_idx, + const Value &min_val, const Value &max_val, idx_t max_bits, + JoinFilterGlobalState &gstate) const { + if (!ht.GetPrefixRangeFilter(key_idx)) { + const auto key_type = ht.conditions[key_idx].GetLHS().GetReturnType(); + auto prefix_filter = PrefixRangeFilter::CreatePrefixRangeFilter(key_type); + prefix_filter->Initialize(context, ht.Count(), min_val, max_val, max_bits); + ht.SetPrefixRangeFilter(key_idx, std::move(prefix_filter)); + ht.SetBuildPrefixRangeFilter(); + } + + DeferRuntimeFilter(DeferredRuntimeFilterType::PREFIX_RANGE, op, info, column, filter_col_idx, key_idx, gstate); + return true; +} + +unique_ptr JoinFilterPushdownInfo::FinalizeMinMax(JoinFilterGlobalState &gstate) const { + // finalize the min/max aggregates + vector min_max_types; + for (auto &aggr_expr : min_max_aggregates) { + min_max_types.push_back(aggr_expr->GetReturnType()); + } + auto final_min_max = make_uniq(); + final_min_max->Initialize(Allocator::DefaultAllocator(), min_max_types); + + gstate.global_aggregate_state->Finalize(*final_min_max); + return final_min_max; +} + +static SelectivityOptionalFilterType GetSelectivityOptionalFilterType(DeferredRuntimeFilterType type) { + switch (type) { + case DeferredRuntimeFilterType::BLOOM_FILTER: + return SelectivityOptionalFilterType::BF; + case DeferredRuntimeFilterType::PREFIX_RANGE: + return SelectivityOptionalFilterType::PRF; + default: + throw InternalException("Unknown deferred runtime filter type"); + } +} + +static const char *GetRuntimeFilterTypeName(DeferredRuntimeFilterType type) { + switch (type) { + case DeferredRuntimeFilterType::BLOOM_FILTER: + return "BLOOM_FILTER"; + case DeferredRuntimeFilterType::PREFIX_RANGE: + return "PREFIX_RANGE"; + default: + throw InternalException("Unknown deferred runtime filter type"); + } +} + +static const char *GetRuntimeFilterReconstructionModeName(JoinFilterPushdownMode mode) { + switch (mode) { + case JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION: + return "RECONSTRUCT_EXPRESSION"; + case JoinFilterPushdownMode::STORAGE_ONLY: + return "STORAGE_ONLY"; + default: + throw InternalException("Unknown join filter pushdown mode"); + } +} + +static unique_ptr CreateRuntimeFilterExpression(ClientContext &context, JoinHashTable &ht, + const DeferredRuntimeFilterPushdown &deferred, + float selectivity_threshold, idx_t n_vectors_to_check, + const BloomFilterReadLocality &locality) { + const auto key_idx = deferred.key_idx; + const auto key_name = ht.conditions[key_idx].GetRHS().ToString(); + const auto key_type = ht.conditions[key_idx].GetLHS().GetReturnType(); + auto filter_input_type = RuntimeFilterCastUtil::GetRuntimeFilterInputType(deferred.column, key_type); + auto input = CreateRuntimeFilterInputExpression(context, deferred.column, key_type); + const auto filters_null_values = !input.preserves_cast_errors && !ht.NullValuesAreEqual(key_idx); + vector> children; + children.push_back(std::move(input.expression)); + + unique_ptr filter_expr; + switch (deferred.type) { + case DeferredRuntimeFilterType::BLOOM_FILTER: { + // a filter that is not sealed does not describe the complete build side - publishing it would drop + // rows - and a filter that saturated is not worth the hashing it costs the scan + if (!ht.HasPublishableBloomFilter(key_idx)) { + return nullptr; + } + auto bloom_filter = ht.GetBloomFilter(key_idx); + // the filter escapes to probe-side scans here, so a later recursive iteration must not reuse it + bloom_filter->MarkPublished(); + filter_expr = make_uniq( + BoundScalarFunction(BloomFilterScalarFun::GetFunction(filter_input_type)), std::move(children), + make_uniq(std::move(bloom_filter), filters_null_values, key_name, key_type, + selectivity_threshold, n_vectors_to_check, locality)); + break; + } + case DeferredRuntimeFilterType::PREFIX_RANGE: { + auto prefix_range_filter = ht.GetPrefixRangeFilter(key_idx); + D_ASSERT(prefix_range_filter && prefix_range_filter->IsInitialized()); + if (!prefix_range_filter || !prefix_range_filter->IsInitialized()) { + return nullptr; + } + prefix_range_filter->MarkPublished(); + filter_expr = make_uniq( + BoundScalarFunction(PrefixRangeScalarFun::GetFunction(filter_input_type)), std::move(children), + make_uniq(prefix_range_filter, filters_null_values, key_name, key_type, + selectivity_threshold, n_vectors_to_check)); + break; + } + default: + throw InternalException("Unknown deferred runtime filter type"); + } + return filter_expr; +} + +static void PublishDeferredRuntimeFilters(ClientContext &context, JoinHashTable &ht, JoinFilterGlobalState &gstate, + const vector &localities = {}) { + if (gstate.deferred_runtime_filters.empty()) { + return; + } + for (auto &deferred : gstate.deferred_runtime_filters) { + D_ASSERT(deferred.op); + if (!deferred.op || !deferred.dynamic_filters) { + continue; + } + const auto filter_type = GetSelectivityOptionalFilterType(deferred.type); + float selectivity_threshold; + idx_t n_vectors_to_check; + GetThresholdAndVectorsToCheck(filter_type, selectivity_threshold, n_vectors_to_check); + const auto locality = + deferred.key_idx < localities.size() ? localities[deferred.key_idx] : BloomFilterReadLocality(); + auto filter_expr = + CreateRuntimeFilterExpression(context, ht, deferred, selectivity_threshold, n_vectors_to_check, locality); + if (!filter_expr) { + continue; + } + deferred.dynamic_filters->PushFilter(*deferred.op, deferred.filter_col_idx, + ExpressionFilter::CreateSelectivityOptionalFilter( + std::move(filter_expr), deferred.column.storage_type, filter_type)); + DUCKDB_LOG(context, PhysicalOperatorLogType, *deferred.op, "PhysicalHashJoin", "PublishRuntimeFilter", + {{"kind", GetRuntimeFilterTypeName(deferred.type)}, + {"storage_type", deferred.column.storage_type.ToString()}, + {"reconstruction_mode", GetRuntimeFilterReconstructionModeName(deferred.column.mode)}, + {"uses_try_cast", to_string(RuntimeFilterCastUtil::RuntimeFilterUsesTryCast(deferred.column))}}); + } + gstate.deferred_runtime_filters.clear(); +} + +static void CreateDynamicMinMaxFilter(const PhysicalComparisonJoin &op, const JoinFilterPushdownFilter &info, + const ProjectionIndex &filter_col_idx, unique_ptr filter_expr, + const LogicalType &column_type, bool selectivity_optional) { + if (!filter_expr) { + return; + } + if (selectivity_optional) { + info.dynamic_filters->PushFilter( + op, filter_col_idx, + ExpressionFilter::CreateSelectivityOptionalFilter(std::move(filter_expr), column_type, + SelectivityOptionalFilterType::MIN_MAX)); + } else { + info.dynamic_filters->PushFilter( + op, filter_col_idx, + make_uniq(CreateOptionalFilterExpression(std::move(filter_expr), column_type))); + } +} + +static unique_ptr CreateComparisonExpressionFilter(ExpressionType comparison_type, + unique_ptr input, const Value &constant, + const LogicalType &comparison_logical_type) { + auto constant_value = constant.DefaultTryCastAs(comparison_logical_type); + if (!constant_value) { + return nullptr; + } + return BoundComparisonExpression::Create(comparison_type, std::move(input), + make_uniq(std::move(*constant_value))); +} + +static unique_ptr CreateComparisonExpressionFilter(ExpressionType comparison_type, const Value &constant, + const LogicalType &column_type) { + auto column = make_uniq(column_type, 0ULL); + return CreateComparisonExpressionFilter(comparison_type, std::move(column), constant, column_type); +} + +static unique_ptr CreateJoinFilterComparisonExpression( + ClientContext &context, const JoinFilterPushdownColumn &column, ExpressionType comparison_type, + const Value &constant, const LogicalType &comparison_logical_type, bool reconstruct_expression, bool retain_nulls) { + if (!reconstruct_expression) { + D_ASSERT(!retain_nulls); + return CreateComparisonExpressionFilter(comparison_type, constant, comparison_logical_type); + } + auto input = CreateRuntimeFilterInputExpression(context, column, comparison_logical_type); + auto input_type = input.expression->GetReturnType(); + unique_ptr null_check_input; + if (input.preserves_cast_errors || retain_nulls) { + null_check_input = input.expression->Copy(); + } + auto filter_expr = + CreateComparisonExpressionFilter(comparison_type, std::move(input.expression), constant, input_type); + if (!filter_expr) { + return nullptr; + } + 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) { + 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); + keys.Reset(); + input.Slice(build_vector, offset, offset + count); + if (build_vector.GetType() == filter_input_type) { + keys.data[0].Reference(input); + } else { + string error; + if (!VectorOperations::TryCast(cast_functions, cast_input, input, keys.data[0], count, &error)) { + return false; + } + } + keys.CheckCardinality(count); + const auto new_count = distinct_keys.FindOrCreateGroups(keys, addresses, new_groups); + for (idx_t i = 0; i < new_count; i++) { + auto value = keys.data[0].GetValue(new_groups.get_index(i)); + if (value.IsNull()) { + if (retain_nulls) { + continue; + } + return false; + } + in_list.push_back(std::move(value)); + if (in_list.size() > threshold) { + return false; + } + } + } + return true; +} + +bool JoinFilterPushdownInfo::PushInFilter(ClientContext &context, const JoinFilterPushdownFilter &info, + const JoinFilterPushdownColumn &column, JoinHashTable &ht, + const PhysicalOperator &op, idx_t filter_idx, ProjectionIndex filter_col_idx, + InFilterMode mode) const { + // 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 = + retain_nulls || RuntimeFilterCastUtil::RequiresRuntimeFilterExpressionReconstruction(column, runtime_type); + auto filter_input_type = column.storage_type; + unique_ptr filter_input; + unique_ptr null_check_input; + if (reconstruct_expression) { + auto input = CreateRuntimeFilterInputExpression(context, column, runtime_type); + filter_input_type = input.expression->GetReturnType(); + if (input.preserves_cast_errors || retain_nulls) { + null_check_input = input.expression->Copy(); + } + filter_input = std::move(input.expression); + } else { + filter_input = make_uniq(column.storage_type, static_cast(0)); + } + + 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)) { + return false; + } + + // An IN filter is only useful when the values are not dense. + if (in_list.empty() || FilterCombiner::IsDenseRange(in_list)) { + return false; + } + + auto in_expr = ExpressionFilter::CreateInExpression(std::move(filter_input), std::move(in_list)); + in_expr = RetainRuntimeFilterNulls(std::move(in_expr), std::move(null_check_input)); + if (mode == InFilterMode::ADAPTIVE_ROW_FILTERING && column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION && + ExpressionFilterExecutor::TryCreate(*in_expr)) { + auto filter = ExpressionFilter::CreateSelectivityOptionalFilter(std::move(in_expr), column.storage_type, + SelectivityOptionalFilterType::IN_FILTER); + info.dynamic_filters->PushFilter(op, filter_col_idx, std::move(filter)); + return true; + } + auto filter = make_uniq(CreateOptionalFilterExpression(std::move(in_expr), column.storage_type)); + info.dynamic_filters->PushFilter(op, filter_col_idx, std::move(filter)); + return true; +} + +static void CreateDynamicMinMaxFilters(const PhysicalComparisonJoin &op, const JoinFilterPushdownFilter &info, + ClientContext &context, const JoinFilterPushdownColumn &column, + ProjectionIndex filter_col_idx, ExpressionType cmp, const Value &min_val, + const Value &max_val, const LogicalType &condition_type, + bool reconstruct_expression, bool selectivity_optional) { + auto filter_column_type = reconstruct_expression ? column.storage_type : condition_type; + const auto retain_nulls = cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM; + switch (cmp) { + case ExpressionType::COMPARE_EQUAL: + case ExpressionType::COMPARE_NOT_DISTINCT_FROM: + case ExpressionType::COMPARE_GREATERTHAN: + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: { + CreateDynamicMinMaxFilter( + op, info, filter_col_idx, + CreateJoinFilterComparisonExpression(context, column, ExpressionType::COMPARE_GREATERTHANOREQUALTO, min_val, + condition_type, reconstruct_expression, retain_nulls), + filter_column_type, selectivity_optional); + break; + } + default: + break; + } + switch (cmp) { + case ExpressionType::COMPARE_EQUAL: + case ExpressionType::COMPARE_NOT_DISTINCT_FROM: + case ExpressionType::COMPARE_LESSTHAN: + case ExpressionType::COMPARE_LESSTHANOREQUALTO: { + CreateDynamicMinMaxFilter( + op, info, filter_col_idx, + CreateJoinFilterComparisonExpression(context, column, ExpressionType::COMPARE_LESSTHANOREQUALTO, max_val, + condition_type, reconstruct_expression, retain_nulls), + filter_column_type, selectivity_optional); + break; + } + default: + break; + } +} + +static idx_t BloomFilterBitBudget(idx_t ht_count) { + return BloomFilter::GetNumberOfSectors(ht_count) * 64; +} + +struct JoinFilterPushdownCandidate { + const JoinFilterPushdownFilter &info; + const JoinFilterPushdownColumn &column; + Value min_val; + Value max_val; + bool reconstruct_expression; + bool can_emit_runtime_filter; +}; + +struct JoinFilterPushdownInfo::FilterFinalizer { + const JoinFilterPushdownInfo &pushdown; + ClientContext &context; + const PhysicalComparisonJoin &op; + DataChunk &final_min_max; + optional_ptr ht; + optional_ptr gstate; + bool allow_bloom_filters; + bool allow_prefix_range_filters; + +public: + vector PrepareCandidates() const; + //! A zero bit budget disables runtime filters when the per-key share is too small. + idx_t SetRuntimeFilterBudget(const vector &candidates); + void FinalizeCandidate(const JoinFilterPushdownCandidate &candidate, idx_t prefix_range_bit_budget); +}; + +vector JoinFilterPushdownInfo::FilterFinalizer::PrepareCandidates() const { + vector candidates; + // Prepare each destination once before dividing the budget among distinct keys. + for (auto &info : pushdown.probe_info) { + for (auto &pushdown_column : info.columns) { + auto filter_idx = pushdown_column.join_filter_idx; + D_ASSERT(filter_idx != DConstants::INVALID_INDEX); + D_ASSERT(filter_idx < pushdown.join_condition.size()); + const auto key_idx = pushdown.join_condition[filter_idx]; + const auto cmp = op.conditions[key_idx].GetComparisonType(); + auto min_idx = filter_idx * 2; + auto max_idx = min_idx + 1; + + auto min_val_before_cast = final_min_max.data[min_idx].GetValue(0); + auto max_val_before_cast = final_min_max.data[max_idx].GetValue(0); + + auto min_val = min_val_before_cast; + auto max_val = max_val_before_cast; + const bool retain_nulls = cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM; + const bool reconstruct_filter_expression = + retain_nulls || RuntimeFilterCastUtil::RequiresRuntimeFilterExpressionReconstruction( + pushdown_column, min_val_before_cast.type()); + + // Cast to storage type, skip if fails + if (pushdown_column.storage_type.IsValid() && !reconstruct_filter_expression) { + auto cast_min = min_val.DefaultTryCastAs(pushdown_column.storage_type); + auto cast_max = max_val.DefaultTryCastAs(pushdown_column.storage_type); + if (!cast_min || !cast_max) { + continue; + } + min_val = std::move(*cast_min); + max_val = std::move(*cast_max); + } + + if (min_val.IsNull() || max_val.IsNull()) { + // min/max is NULL + // this can happen in case all values in the RHS column are NULL, but they are still pushed into the + // hash table e.g. because they are part of a RIGHT join + continue; + } + + auto condition_type = min_val.type(); + auto runtime_filter_input_type = + RuntimeFilterCastUtil::GetRuntimeFilterInputType(pushdown_column, condition_type); + const bool can_emit_runtime_filter = + ht && gstate && (allow_bloom_filters || allow_prefix_range_filters) && + pushdown_column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION && + runtime_filter_input_type == ht->conditions[key_idx].GetLHS().GetReturnType() && + !Value::NotDistinctFrom(min_val, max_val) && pushdown.CanUseBloomFilter(info, context, op, cmp, ht); + candidates.push_back({info, pushdown_column, std::move(min_val), std::move(max_val), + reconstruct_filter_expression, can_emit_runtime_filter}); + } + } + return candidates; +} + +idx_t JoinFilterPushdownInfo::FilterFinalizer::SetRuntimeFilterBudget( + const vector &candidates) { + if (!ht || ht->HasSingleEqualityKey()) { + return NumericLimits::Maximum(); + } + + vector runtime_filter_keys(op.conditions.size(), false); + idx_t runtime_filter_count = 0; + for (auto &candidate : candidates) { + const auto key_idx = pushdown.join_condition[candidate.column.join_filter_idx]; + if (candidate.can_emit_runtime_filter && !runtime_filter_keys[key_idx]) { + runtime_filter_keys[key_idx] = true; + runtime_filter_count++; + } + } + const auto budget_share = MaxValue(runtime_filter_count, 1); + const auto memory_budget = GetMemoryBudget(context); + ht->SetBloomFilterBudget(memory_budget / budget_share); + // Leave room for at least one complete build lane as well as the published bitmaps. + const auto prefix_range_budget = MinValue(memory_budget, MAX_PREFIX_RANGE_BUILD_MEMORY); + const auto column_budget = prefix_range_budget / budget_share; + return column_budget >= 128 ? ((column_budget - 64) / 8) * 64 : 0; +} + +void JoinFilterPushdownInfo::FilterFinalizer::FinalizeCandidate(const JoinFilterPushdownCandidate &candidate, + idx_t prefix_range_bit_budget) { + auto &info = candidate.info; + auto &pushdown_column = candidate.column; + const auto filter_idx = pushdown_column.join_filter_idx; + const auto key_idx = pushdown.join_condition[filter_idx]; + const auto cmp = op.conditions[key_idx].GetComparisonType(); + auto &filter_col_idx = pushdown_column.probe_column_index.column_index; + auto &min_val = candidate.min_val; + auto &max_val = candidate.max_val; + const auto &condition_type = min_val.type(); + const bool retain_nulls = cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM; + const auto reconstruct_filter_expression = candidate.reconstruct_expression; + const auto can_emit_runtime_filters = prefix_range_bit_budget > 0 && candidate.can_emit_runtime_filter; + if (Value::NotDistinctFrom(min_val, max_val)) { + // A single build value produces one comparison, including for non-equality joins. + auto filter_expr = CreateJoinFilterComparisonExpression(context, pushdown_column, cmp, min_val, condition_type, + reconstruct_filter_expression, retain_nulls); + if (filter_expr) { + info.dynamic_filters->PushFilter(op, filter_col_idx, make_uniq(std::move(filter_expr))); + } + return; + } + if (cmp != ExpressionType::COMPARE_EQUAL && !retain_nulls) { + // Non-equality comparisons need a half-open range. + CreateDynamicMinMaxFilters(op, info, context, pushdown_column, filter_col_idx, cmp, min_val, max_val, + condition_type, reconstruct_filter_expression, true); + return; + } + + auto min_val_before_cast = final_min_max.data[filter_idx * 2].GetValue(0); + auto max_val_before_cast = final_min_max.data[filter_idx * 2 + 1].GetValue(0); + uhugeint_t span; + const auto can_compute_span = PrefixRangeFilter::TryComputeSpan(min_val_before_cast, max_val_before_cast, span); + const auto can_emit_prf = allow_prefix_range_filters && can_emit_runtime_filters && + PrefixRangeFilter::SupportedType(ht->conditions[key_idx].GetLHS().GetReturnType()) && + can_compute_span; + + const auto exact_prf_bits = + MinValue(JoinFilterPushdownConfig::SMALL_EXACT_PRF_BITS, prefix_range_bit_budget); + bool registered_prf = + can_emit_prf && span < exact_prf_bits && + pushdown.TryRegisterPrefixRangeFilter(info, context, *ht, op, pushdown_column, filter_col_idx, key_idx, + min_val_before_cast, max_val_before_cast, exact_prf_bits, *gstate); + + if (can_emit_prf && !registered_prf) { + auto build_count = ht->Count(); + if (build_count == 0) { + build_count = ht->GetSinkCollection().Count(); + } + const auto bloom_filter_bits = MinValue(BloomFilterBitBudget(build_count), prefix_range_bit_budget); + registered_prf = + span <= bloom_filter_bits && + pushdown.TryRegisterPrefixRangeFilter(info, context, *ht, op, pushdown_column, filter_col_idx, key_idx, + min_val_before_cast, max_val_before_cast, bloom_filter_bits, *gstate); + } + const auto can_use_bloom = !registered_prf && allow_bloom_filters && can_emit_runtime_filters && + (ht->HasPublishableBloomFilter(key_idx) || allow_prefix_range_filters); + bool pushed_in_filter = false; + if (pushdown.CanUseInFilter(context, ht, cmp)) { + // String prefixes can leave false positives that a small IN filter removes. + const auto prefer_prf = + registered_prf && ht->conditions[key_idx].GetLHS().GetReturnType().InternalType() != PhysicalType::VARCHAR; + const auto mode = + prefer_prf || can_use_bloom ? InFilterMode::PRUNING_ONLY : InFilterMode::ADAPTIVE_ROW_FILTERING; + pushed_in_filter = + pushdown.PushInFilter(context, info, pushdown_column, *ht, op, filter_idx, filter_col_idx, mode); + } + // Keep multi-key min/max filters for their complementary statistics pruning. + if (registered_prf && ht->HasSingleEqualityKey()) { + return; + } + + if (!pushed_in_filter) { + CreateDynamicMinMaxFilters(op, info, context, pushdown_column, filter_col_idx, cmp, min_val, max_val, + condition_type, reconstruct_filter_expression, true); + } + if (can_use_bloom) { + if (ht->HasPublishableBloomFilter(key_idx)) { + // A complete filter was accumulated during Sink (external joins build it there). + pushdown.DeferRuntimeFilter(DeferredRuntimeFilterType::BLOOM_FILTER, op, info, pushdown_column, + filter_col_idx, key_idx, *gstate); + } else if (allow_prefix_range_filters) { + // Build during finalize only when it materializes the whole build side; external finalize does not. + ht->SetBuildBloomFilter(key_idx); + pushdown.DeferRuntimeFilter(DeferredRuntimeFilterType::BLOOM_FILTER, op, info, pushdown_column, + filter_col_idx, key_idx, *gstate); + } + } +} + +unique_ptr JoinFilterPushdownInfo::FinalizeFilters(ClientContext &context, const PhysicalComparisonJoin &op, + unique_ptr final_min_max, + optional_ptr ht, bool allow_bloom_filters, + bool allow_prefix_range_filters, + optional_ptr gstate) const { + if (probe_info.empty()) { + return final_min_max; + } + + FilterFinalizer finalizer { + *this, context, op, *final_min_max, ht, gstate, allow_bloom_filters, allow_prefix_range_filters}; + auto candidates = finalizer.PrepareCandidates(); + const auto prefix_range_bit_budget = finalizer.SetRuntimeFilterBudget(candidates); + for (auto &candidate : candidates) { + finalizer.FinalizeCandidate(candidate, prefix_range_bit_budget); + } + return final_min_max; +} + +unique_ptr JoinFilterPushdownInfo::Finalize(ClientContext &context, JoinFilterGlobalState &gstate, + const PhysicalComparisonJoin &op, + optional_ptr ht) const { + auto final_min_max = FinalizeMinMax(gstate); + return FinalizeFilters(context, op, std::move(final_min_max), ht, true, true, &gstate); +} + +enum class HashJoinFilterCopyPhase { PRIMARY, REPLICA }; + +struct HashJoinFilterCopy { + HashJoinFilterCopy(idx_t key_idx, shared_ptr filter) : key_idx(key_idx), filter(std::move(filter)) { + } + + idx_t key_idx; + shared_ptr filter; + HugeAllocation buffer; + optional_idx replica_group; + atomic claimed {false}; +}; + +struct HashJoinFilterCopies { + explicit HashJoinFilterCopies(idx_t shard_count) : shard_count(shard_count) { + } + + idx_t shard_count; + vector> filters; +}; + +class HashJoinFilterCopyTask : public ExecutorTask { +public: + HashJoinFilterCopyTask(ClientContext &context, const PhysicalOperator &op, shared_ptr event, + HashJoinFilterCopy ©, idx_t shard_count, HashJoinFilterCopyPhase phase) + : ExecutorTask(context, std::move(event), op), context(context), copy(copy), shard_count(shard_count), + phase(phase) { + } + + TaskExecutionResult ExecuteTask(TaskExecutionMode mode) override { + const auto group = BlockAllocator::GetLocalShardGroup(shard_count); + const auto force = Settings::Get(context); + if (phase == HashJoinFilterCopyPhase::PRIMARY || ((force || group == copy.replica_group.GetIndex()) && + !copy.claimed.exchange(true, std::memory_order_relaxed))) { + try { + auto buffer = copy.filter->CopyBuffer(context); + const auto home = buffer.GetAllocationShard(); + if (force || home.IsValid()) { + const auto buffer_group = + force ? group : BlockAllocator::GetShardGroup(home.GetIndex(), shard_count); + if (phase == HashJoinFilterCopyPhase::PRIMARY) { + copy.replica_group = optional_idx(force ? group : 1 - buffer_group); + copy.buffer = std::move(buffer); + } else if (force || buffer_group == copy.replica_group.GetIndex()) { + copy.buffer = std::move(buffer); + } + } + } catch (const OutOfMemoryException &) { + // Optional copies may fail; the completed primary remains readable. + } catch (const std::bad_alloc &) { + } + } + event->FinishTask(); + return TaskExecutionResult::TASK_FINISHED; + } + + string TaskType() const override { + return "HashJoinFilterCopy"; + } + +private: + ClientContext &context; + HashJoinFilterCopy © + idx_t shard_count; + HashJoinFilterCopyPhase phase; +}; + +class HashJoinFilterCopyEvent : public BasePipelineEvent { +public: + HashJoinFilterCopyEvent(Pipeline &pipeline, const PhysicalOperator &op, JoinHashTable &ht, + JoinFilterGlobalState &filters, shared_ptr copies, + HashJoinFilterCopyPhase phase = HashJoinFilterCopyPhase::PRIMARY) + : BasePipelineEvent(pipeline), op(op), ht(ht), filters(filters), copies(std::move(copies)), phase(phase) { + } + + void Schedule() override { + vector> tasks; + for (auto © : copies->filters) { + if (phase == HashJoinFilterCopyPhase::REPLICA && !copy->replica_group.IsValid()) { + continue; + } + // Bounded opportunities on the other group; never wait for a particular worker. + const idx_t task_count = phase == HashJoinFilterCopyPhase::PRIMARY ? 1 : 16; + for (idx_t i = 0; i < task_count; i++) { + tasks.push_back(make_uniq(pipeline->GetClientContext(), op, shared_from_this(), + *copy, copies->shard_count, phase)); + } + } + SetTasks(std::move(tasks)); + } + + void FinishEvent() override { + vector localities(ht.GetBloomFilters().size()); + bool replaced_primary = false; + for (auto © : copies->filters) { + if (!copy->buffer.IsSet()) { + continue; + } + if (phase == HashJoinFilterCopyPhase::PRIMARY) { + copy->filter->ReplaceBuffer(std::move(copy->buffer)); + replaced_primary = true; + } else { + copy->filter->InstallReadCopy(std::move(copy->buffer)); + localities[copy->key_idx] = {copies->shard_count, copy->replica_group}; + } + } + if (replaced_primary) { + // All old primaries have been released before a second buffer can be allocated. + InsertEvent(make_shared_ptr(*pipeline, op, ht, filters, copies, + HashJoinFilterCopyPhase::REPLICA)); + return; + } + PublishDeferredRuntimeFilters(pipeline->GetClientContext(), ht, filters, localities); + ht.finalized = true; + } + +private: + const PhysicalOperator &op; + JoinHashTable &ht; + JoinFilterGlobalState &filters; + shared_ptr copies; + HashJoinFilterCopyPhase phase; +}; + +void JoinFilterPushdownInfo::FinalizeRuntimeFilters(Pipeline &pipeline, Event &event, const PhysicalOperator &op, + JoinHashTable &ht, optional_ptr filter_state, + idx_t num_threads) { + auto &context = pipeline.GetClientContext(); + if (filter_state) { + ht.SealBloomFilters(); + auto &gstate = *filter_state; + const auto shard_count = BlockAllocator::Get(*context.db).GetFallbackShardCount(); + const auto force = Settings::Get(context); + if ((force || (num_threads > 128 && shard_count > 32)) && !gstate.deferred_runtime_filters.empty()) { + auto copies = make_shared_ptr(shard_count); + vector considered(ht.GetBloomFilters().size(), false); + auto remaining = GetMemoryBudget(context); + for (auto &filter : ht.GetBloomFilters()) { + if (filter) { + remaining -= MinValue(remaining, filter->GetAllocationSize()); + } + } + for (auto &deferred : gstate.deferred_runtime_filters) { + if (deferred.type != DeferredRuntimeFilterType::BLOOM_FILTER || considered[deferred.key_idx]) { + continue; + } + considered[deferred.key_idx] = true; + auto filter = ht.GetBloomFilter(deferred.key_idx); + if (!filter || filter->IsPublished() || !ht.HasPublishableBloomFilter(deferred.key_idx)) { + continue; + } + const auto bytes = filter->GetBitmapSize(); + const auto budget = filter->GetMemoryBudget(); + if ((!force && bytes < (1ULL << 20)) || bytes > (256ULL << 20) || bytes > budget / 2 || + filter->GetAllocationSize() > budget - bytes || bytes > remaining) { + continue; + } + remaining -= bytes; + copies->filters.push_back(make_uniq(deferred.key_idx, std::move(filter))); + } + if (!copies->filters.empty()) { + event.InsertEvent( + make_shared_ptr(pipeline, op, ht, gstate, std::move(copies))); + return; + } + } + PublishDeferredRuntimeFilters(context, ht, gstate); + } + ht.finalized = true; +} + +} // namespace duckdb diff --git a/src/duckdb/src/execution/operator/join/outer_join_marker.cpp b/src/duckdb/src/execution/operator/join/outer_join_marker.cpp index d0b3872a7..065b96792 100644 --- a/src/duckdb/src/execution/operator/join/outer_join_marker.cpp +++ b/src/duckdb/src/execution/operator/join/outer_join_marker.cpp @@ -92,14 +92,15 @@ void OuterJoinMarker::InitializeScan(OuterJoinGlobalScanState &gstate, OuterJoin gstate.data->InitializeScanChunk(lstate.scan_chunk); } -void OuterJoinMarker::Scan(OuterJoinGlobalScanState &gstate, OuterJoinLocalScanState &lstate, DataChunk &result) { +void OuterJoinMarker::Scan(OuterJoinGlobalScanState &gstate, OuterJoinLocalScanState &lstate, DataChunk &result, + bool matched) { D_ASSERT(gstate.data); // fill in NULL values for the LHS while (gstate.data->Scan(gstate.global_scan, lstate.local_scan, lstate.scan_chunk)) { idx_t result_count = 0; - // figure out which tuples didn't find a match in the RHS + // figure out which tuples did (not) find a match in the RHS for (idx_t i = 0; i < lstate.scan_chunk.size(); i++) { - if (!found_match[lstate.local_scan.current_row_index + i]) { + if (found_match[lstate.local_scan.current_row_index + i] == matched) { lstate.match_sel.set_index(result_count++, i); } } diff --git a/src/duckdb/src/execution/operator/join/physical_hash_join.cpp b/src/duckdb/src/execution/operator/join/physical_hash_join.cpp index 80d06361c..9b1474b05 100644 --- a/src/duckdb/src/execution/operator/join/physical_hash_join.cpp +++ b/src/duckdb/src/execution/operator/join/physical_hash_join.cpp @@ -7,13 +7,14 @@ #include "duckdb/common/projection_index.hpp" #include "duckdb/common/radix_partitioning.hpp" #include "duckdb/common/types.hpp" -#include "duckdb/common/types/value_map.hpp" #include "duckdb/common/uhugeint.hpp" #include "duckdb/common/types/uhugeint.hpp" #include "duckdb/common/vector/dictionary_vector.hpp" +#include "duckdb/common/vector/vector_iterator.hpp" +#include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/execution/aggregate_hashtable.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/execution/join_hashtable.hpp" -#include "duckdb/execution/operator/aggregate/ungrouped_aggregate_state.hpp" #include "duckdb/execution/operator/join/physical_delim_join.hpp" #include "duckdb/function/aggregate/distributive_function_utils.hpp" #include "duckdb/function/aggregate/distributive_functions.hpp" @@ -21,7 +22,6 @@ #include "duckdb/main/client_context.hpp" #include "duckdb/main/query_profiler.hpp" #include "duckdb/main/settings.hpp" -#include "duckdb/optimizer/filter_combiner.hpp" #include "duckdb/parallel/base_pipeline_event.hpp" #include "duckdb/parallel/executor_task.hpp" #include "duckdb/parallel/interrupt.hpp" @@ -30,17 +30,9 @@ #include "duckdb/parallel/task_scheduler.hpp" #include #include "duckdb/planner/expression/bound_aggregate_expression.hpp" -#include "duckdb/planner/expression/bound_cast_expression.hpp" -#include "duckdb/planner/expression/bound_comparison_expression.hpp" -#include "duckdb/planner/expression/bound_conjunction_expression.hpp" -#include "duckdb/planner/expression/bound_constant_expression.hpp" -#include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/execution/operator/projection/physical_projection.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" -#include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/filter/table_filter_functions.hpp" -#include "duckdb/planner/table_filter.hpp" -#include "duckdb/planner/table_filter_set.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/temporary_memory_manager.hpp" #include "duckdb/planner/expression_iterator.hpp" @@ -271,25 +263,6 @@ void PhysicalHashJoin::MapResidualBuildColumns(const vector &lhs_in //===--------------------------------------------------------------------===// // Sink //===--------------------------------------------------------------------===// -JoinFilterGlobalState::~JoinFilterGlobalState() { -} - -JoinFilterLocalState::~JoinFilterLocalState() { -} - -unique_ptr JoinFilterPushdownInfo::GetGlobalState(ClientContext &context, - const PhysicalOperator &op) const { - // clear any previously set filters - // we can have previous filters for this operator in case of e.g. recursive CTEs - for (auto &info : probe_info) { - info.dynamic_filters->ClearFilters(op); - } - auto result = make_uniq(); - result->global_aggregate_state = - make_uniq(BufferAllocator::Get(context), min_max_aggregates); - return result; -} - //! Check for producers that can change a build column's dictionary between chunks. static bool BuildSideHasMultipleSources(const PhysicalOperator &op) { switch (op.type) { @@ -370,69 +343,6 @@ struct LayoutGate { static idx_t GetBuildSpaceRequirement(ClientContext &context, const JoinHashTable &ht, idx_t num_threads); -//! Building the bloom filter is costly on the build side to make probing faster, -//! so only use it if there are less build tuples than probing tuples -static constexpr double BUILD_TO_PROBE_RATIO_THRESHOLD = 1.0; -//! If we have a build side without a filter, only build the bloom filter if the ratio/size is small enough -static constexpr double NON_FILTERING_RATIO_THRESHOLD = 0.1; -static constexpr idx_t NON_FILTERING_BUILD_SIDE_THRESHOLD = 4194304; -//! Max build/probe ratio at which a multi-key join builds per-key-column filters -static constexpr double MULTI_KEY_RATIO_THRESHOLD = 0.05; -//! A join is expected to stay in memory while its estimated build side is below this share of the memory budget -static constexpr idx_t LIKELY_IN_MEMORY_BUILD_MEMORY_FRACTION = 4; -//! Bound replicated prefix-range filter state independently of the radix partitions -static constexpr idx_t MAX_PREFIX_RANGE_BUILD_MEMORY = 16ULL * 1024ULL * 1024ULL; - -static idx_t GetJoinRuntimeFilterMemoryBudget(ClientContext &context) { - static constexpr idx_t MAX_MEMORY_FRACTION = 64; - return BufferManager::GetBufferManager(context).GetMaxMemory() / MAX_MEMORY_FRACTION; -} - -//! Whether the build side is expected to exceed the memory budget and spill -static bool JoinIsLikelyExternal(ClientContext &context, const PhysicalHashJoin &op) { - if (Settings::Get(context)) { - return true; - } - idx_t row_width = sizeof(data_ptr_t) + sizeof(hash_t); // per-row pointer table and hash overhead - for (auto &type : op.children[1].get().GetTypes()) { - row_width += GetTypeIdSize(type.InternalType()); - } - const auto build_size = op.children[1].get().estimated_cardinality * row_width; - const auto memory_budget = BufferManager::GetBufferManager(context).GetMaxMemory(); - return build_size > memory_budget / LIKELY_IN_MEMORY_BUILD_MEMORY_FRACTION; -} - -//! Whether to accumulate a bloom filter during Sink. Only an external join needs that: its finalize only ever -//! materializes some partitions, so a filter built there would be incomplete, while every row passes through -//! Sink. An in-memory join builds its filter during finalize instead, where the actual build count and the -//! competing filter choices are known. The estimate-based checks mirror CanUseBloomFilter, which decides -//! publication once the actual build count is known. -static bool ShouldBuildBloomFilterInSink(ClientContext &context, const PhysicalHashJoin &op) { - if (!op.filter_pushdown || op.filter_pushdown->probe_info.empty()) { - return false; - } - idx_t equality_count = 0; - for (auto &cond : op.conditions) { - const auto cmp = cond.GetComparisonType(); - if (cmp == ExpressionType::COMPARE_EQUAL || cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM) { - equality_count++; - } - } - if (equality_count != 1) { - return false; - } - const auto build_estimate = static_cast(op.children[1].get().estimated_cardinality); - const auto probe_estimate = static_cast(op.children[0].get().estimated_cardinality); - if (build_estimate > BUILD_TO_PROBE_RATIO_THRESHOLD * probe_estimate) { - return false; - } - if (!op.filter_pushdown->build_side_has_filter && build_estimate > NON_FILTERING_RATIO_THRESHOLD * probe_estimate && - build_estimate > NON_FILTERING_BUILD_SIDE_THRESHOLD) { - return false; - } - return JoinIsLikelyExternal(context, op); -} - class HashJoinGlobalSinkState : public GlobalSinkState { public: HashJoinGlobalSinkState(const PhysicalHashJoin &op_p, ClientContext &context_p) @@ -468,35 +378,12 @@ class HashJoinGlobalSinkState : public GlobalSinkState { if (op.filter_pushdown && !op.filter_pushdown->probe_info.empty()) { global_filter_state = op.filter_pushdown->GetGlobalState(context, op); } - InitializeBloomFilter(std::move(recycled_filter)); - } - - //! Creates the bloom filter that every thread-local hash table inserts into during Sink. - //! A filter recycled from the previous recursive iteration is reused unless it was published. - void InitializeBloomFilter(shared_ptr recycled_filter = nullptr) { - // a published filter is shared with probe-side scans and immutable, so it cannot be reused - if (recycled_filter && recycled_filter->IsPublished()) { - recycled_filter.reset(); - } - if (!ShouldBuildBloomFilterInSink(context, op)) { - hash_table->SetBloomFilter(nullptr); - // an in-memory join builds its filter during finalize, which can still reuse the allocation; - // an iteration without a filter must not clear a slot that finalize has not consumed yet - if (recycled_filter) { - hash_table->SetRecycledBloomFilter(std::move(recycled_filter)); - } - return; - } - if (!recycled_filter) { - recycled_filter = make_shared_ptr(); - } - recycled_filter->Initialize(context, MaxValue(op.children[1].get().estimated_cardinality, 1)); - hash_table->SetBloomFilter(std::move(recycled_filter)); + JoinFilterPushdownInfo::InitializeBloomFilters(context, op, *hash_table, std::move(recycled_filter)); } ~HashJoinGlobalSinkState() override { DUCKDB_LOG(context, PhysicalOperatorLogType, op, "PhysicalHashJoin", "GetData", - {{"total_probe_matches", to_string(hash_table->total_probe_matches)}}); + {{"total_probe_matches", to_string(hash_table->GetTotalProbeMatches())}}); } void ScheduleFinalize(Pipeline &pipeline, Event &event); @@ -511,7 +398,7 @@ class HashJoinGlobalSinkState : public GlobalSinkState { void Reset(ClientContext &context) override { // Keep the previous iteration's bloom filter so its allocation can be reused. - auto recycled_bloom_filter = hash_table->GetBloomFilter(); + auto recycled_bloom_filter = hash_table->HasSingleEqualityKey() ? hash_table->GetBloomFilter(0) : nullptr; // Use single-partition mode on subsequent iterations to avoid 16-partition overhead for small joins. hash_table->ResetForNewIterationSinglePartition(); finalized = false; @@ -555,7 +442,14 @@ class HashJoinGlobalSinkState : public GlobalSinkState { //! The memory available to the hash table: the reservation minus what partitioning the probe side requires idx_t GetMaxExternalHTSize() const { const auto reservation = temporary_memory_state->GetReservation(); - return reservation > probe_side_requirement ? reservation - probe_side_requirement : 0; + const auto retained_size = probe_side_requirement + hash_table->GetRetainedDictionarySize(); + return reservation > retained_size ? reservation - retained_size : 0; + } + + idx_t GetMaxInMemoryHTSize() const { + // The external minimum reservation can exceed the memory limit. + return MinValue(temporary_memory_state->GetReservation(), + BufferManager::GetBufferManager(context).GetMaxMemory()); } //! Whether we are doing an external + some sizes @@ -591,12 +485,6 @@ class HashJoinGlobalSinkState : public GlobalSinkState { vector computed_build_columns; }; -unique_ptr JoinFilterPushdownInfo::GetLocalState(JoinFilterGlobalState &gstate) const { - auto result = make_uniq(); - result->local_aggregate_state = make_uniq(*gstate.global_aggregate_state); - return result; -} - class HashJoinLocalSinkState : public LocalSinkState { public: HashJoinLocalSinkState(const PhysicalHashJoin &op, ClientContext &context, HashJoinGlobalSinkState &gstate) @@ -613,8 +501,8 @@ class HashJoinLocalSinkState : public LocalSinkState { } hash_table = op.InitializeHashTable(context, gstate.hash_table->GetRadixBits()); - // every thread inserts into this one filter - InsertOne is an atomic fetch_or, so it needs no lock - hash_table->SetBloomFilter(gstate.hash_table->GetBloomFilter()); + // All threads share these filters; insertion uses atomic updates. + hash_table->SetBloomFilters(gstate.hash_table->GetBloomFilters()); // sink_collection exists only after the layout is published on the first build chunk, so // InitializeAppendState runs lazily inside Sink. keep_hash_table = gstate.keep_local_hash_tables; @@ -661,9 +549,8 @@ class HashJoinLocalSinkState : public LocalSinkState { hash_table = op.InitializeHashTable(context.client, gstate.hash_table->GetRadixBits()); } append_state_initialised = false; - // the global state resets before any local one, so the filter this picks up is always a fresh one - D_ASSERT(!gstate.hash_table->GetBloomFilter() || !gstate.hash_table->GetBloomFilter()->IsSealed()); - hash_table->SetBloomFilter(gstate.hash_table->GetBloomFilter()); + // The global state resets before any local one, so these filters belong to the new iteration. + hash_table->SetBloomFilters(gstate.hash_table->GetBloomFilters()); keep_hash_table = gstate.keep_local_hash_tables; gstate.active_local_states++; if (gstate.global_filter_state) { @@ -699,7 +586,7 @@ static shared_ptr BuildJoinLayout(const vector &co } //! Join-level eligibility for preserving build-side dictionary slots. -static bool CanUseDictSurvivingJoin(const PhysicalHashJoin &op, const JoinHashTable &ht, bool build_side_multi_source) { +static bool CanUseDictSurvivingJoin(const PhysicalHashJoin &op, bool build_side_multi_source) { // external is safe here: the dictionary is an in-memory self-owned copy and the index is a plain row-store // column, so a spill/repartition preserves both (unlike the pointer-embedding dict-emission/compressed-probe paths) // a multi-source build (UNION ALL, CTE) can deliver a later chunk flat or as a different dictionary under the @@ -709,20 +596,6 @@ static bool CanUseDictSurvivingJoin(const PhysicalHashJoin &op, const JoinHashTa if (build_side_multi_source) { return false; } - // SINGLE joins need FlatVector::SetNull on unmatched rows; dictionary vectors cannot supply it - if (ht.join_type == JoinType::SINGLE) { - return false; - } - // LEFT may dispatch into NextUniqueLeftJoin, which gathers payload via ScanStructure::GatherResult and - // bypasses GatherRHS' dict branch; the narrowed slot would be read as native type and trip the gather type check. - if (ht.join_type == JoinType::LEFT) { - return false; - } - // OUTER fills unmatched-probe rows with CONSTANT_NULL (NextLeftJoin), mixing dict chunks with flat fill chunks; - // admitting it would re-emit a falsely global dictionary a downstream consumer cannot trust. - if (ht.join_type == JoinType::OUTER) { - return false; - } if (op.rhs_output_columns.col_types.empty()) { return false; } @@ -735,7 +608,7 @@ void HashJoinGlobalSinkState::PublishLayoutIfFirst(HashJoinLocalSinkState &lstat const auto &build_types = lstate.hash_table->build_types; shared_ptr dict_info; - if (CanUseDictSurvivingJoin(op, *lstate.hash_table, build_side_multi_source)) { + if (CanUseDictSurvivingJoin(op, build_side_multi_source)) { // Per-column width decision lives on the JHT (GetDictSurvivingIndexWidth); feed it each arriving vector. // The dictionary a narrowed slot indexes into is created here, once, and handed to every thread with the // layout: a later chunk may carry no dictionary at all (NULL-only), so no thread can pin it lazily. @@ -861,17 +734,6 @@ bool PhysicalHashJoin::CanPreserveBuildForRecursiveReuse() const { return state.preserve_build_for_reuse && !state.external; } -void JoinFilterPushdownInfo::Sink(DataChunk &chunk, JoinFilterLocalState &lstate) const { - // if we are pushing any filters into a probe-side, compute the min/max over the columns that we are pushing - for (idx_t pushdown_idx = 0; pushdown_idx < join_condition.size(); pushdown_idx++) { - auto join_condition_idx = join_condition[pushdown_idx]; - for (idx_t i = 0; i < 2; i++) { - idx_t aggr_idx = pushdown_idx * 2 + i; - lstate.local_aggregate_state->Sink(chunk, join_condition_idx, aggr_idx, chunk.size()); - } - } -} - SinkResultType PhysicalHashJoin::Sink(ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input) const { auto &gstate = input.global_state.Cast(); auto &lstate = input.local_state.Cast(); @@ -906,10 +768,6 @@ SinkResultType PhysicalHashJoin::Sink(ExecutionContext &context, DataChunk &chun return SinkResultType::NEED_MORE_INPUT; } -void JoinFilterPushdownInfo::Combine(JoinFilterGlobalState &gstate, JoinFilterLocalState &lstate) const { - gstate.global_aggregate_state->Combine(*lstate.local_aggregate_state); -} - SinkCombineResultType PhysicalHashJoin::Combine(ExecutionContext &context, OperatorSinkCombineInput &input) const { auto &gstate = input.global_state.Cast(); auto &lstate = input.local_state.Cast(); @@ -1040,15 +898,17 @@ void PhysicalHashJoin::PrepareFinalize(ClientContext &context, GlobalSinkState & } gstate.layout_gate.layout_ptr = std::move(layout); }); - const auto &ht = *gstate.hash_table; + auto &ht = *gstate.hash_table; + ht.MergePerfectHashBounds(gstate.local_hash_tables); gstate.total_size = ht.GetTotalSize(gstate.local_hash_tables, gstate.max_partition_size, gstate.max_partition_count); gstate.probe_side_requirement = GetPartitioningSpaceRequirement(context, gstate.probe_types, ht.GetRadixBits(), gstate.num_threads); const auto max_partition_ht_size = gstate.max_partition_size + gstate.hash_table->PointerTableSize(gstate.max_partition_count); - gstate.temporary_memory_state->SetMinimumReservation(max_partition_ht_size + gstate.probe_side_requirement); + gstate.temporary_memory_state->SetMinimumReservation(max_partition_ht_size + gstate.probe_side_requirement + + ht.GetRetainedDictionarySize()); bool all_constant; gstate.temporary_memory_state->SetMaterializationPenalty(GetTupleWidth(gstate.probe_types, all_constant)); @@ -1083,8 +943,6 @@ static void ExecuteHashJoinFinalizeTask(HashJoinGlobalSinkState &sink, const Joi sink.hash_table->Finalize(chunk_range.begin, chunk_range.end, parallel, prefix_range_states, prefix_range_parallel); } -static void PublishDeferredRuntimeFilters(ClientContext &context, JoinHashTable &ht, JoinFilterGlobalState &gstate); - //! Event-owned ranges, consumed near their preferred CPU group before stealing. class JoinBuildQueue { public: @@ -1156,7 +1014,7 @@ class HashJoinTableInitTask : public ExecutorTask { idx_t pass = 0; JoinBuildRange range; while (queue.Next(start, pass, range)) { - sink.context.InterruptCheck(); + sink.context.FastInterruptCheck(); ExecuteHashJoinTableInitTask(sink, range.begin, range.end); } event->FinishTask(); @@ -1233,7 +1091,7 @@ class HashJoinFinalizeTask : public ExecutorTask { idx_t pass = 0; JoinBuildRange range; while (queue.Next(start, pass, range)) { - sink.context.InterruptCheck(); + sink.context.FastInterruptCheck(); ExecuteHashJoinFinalizeTask(sink, range, parallel, prefix_range_lane); } event->FinishTask(); @@ -1296,7 +1154,7 @@ class HashJoinFinalizeEvent : public BasePipelineEvent { return finalize_tasks; } - void ExecuteDirectly() { + void ExecuteDirectly(Event &event) { auto &ht = *sink.hash_table; InitializePrefixRangeLanes(ht, 1); optional_ptr lane; @@ -1305,7 +1163,7 @@ class HashJoinFinalizeEvent : public BasePipelineEvent { lane->task_count = 1; } ExecuteHashJoinFinalizeTask(sink, {0, ht.GetDataCollection().ChunkCount()}, false, lane); - FinishTasks(); + FinishTasks(event); } void Schedule() override { @@ -1313,13 +1171,13 @@ class HashJoinFinalizeEvent : public BasePipelineEvent { } void FinishEvent() override { - FinishTasks(); + FinishTasks(*this); } static constexpr idx_t CHUNKS_PER_TASK = 64; private: - void FinishTasks() { + void FinishTasks(Event &event) { for (auto &lane : prefix_range_lanes) { sink.hash_table->MergePrefixRangeBuildState(lane->states); } @@ -1327,18 +1185,22 @@ class HashJoinFinalizeEvent : public BasePipelineEvent { // Both finalize paths finish writing the chains before reaching here, // so dictionary emission is safe on either path - if (sink.hash_table->CanUseDictionaryEmission(sink.op, sink.external, - sink.op.children[0].get().estimated_cardinality)) { - sink.hash_table->BuildDictionaryArrays(sink.op); + const auto dictionary_size = sink.hash_table->GetDictionaryReservationSize( + sink.op, sink.external, sink.op.children[0].get().estimated_cardinality); + if (dictionary_size > 0) { + auto &memory = *sink.temporary_memory_state; + const auto requested_size = sink.total_size + dictionary_size; + memory.SetRemainingSizeAndUpdateReservation(sink.context.GetContext(), requested_size); + if (sink.GetMaxInMemoryHTSize() >= requested_size) { + sink.hash_table->BuildDictionaryArrays(sink.op, dictionary_size); + } + const auto retained_size = sink.total_size + sink.hash_table->GetMaterializedDictionarySize(); + memory.SetMinimumReservation(retained_size); + memory.SetRemainingSizeAndUpdateReservation(sink.context.GetContext(), retained_size); } - if (sink.global_filter_state) { - // a finalize-built bloom filter is complete once the tasks are done; a sink-built one is - // already sealed and this is a no-op - sink.hash_table->SealBloomFilter(); - PublishDeferredRuntimeFilters(sink.context, *sink.hash_table, *sink.global_filter_state); - } - sink.hash_table->finalized = true; + JoinFilterPushdownInfo::FinalizeRuntimeFilters(*pipeline, event, sink.op, *sink.hash_table, + sink.global_filter_state, sink.num_threads); } void InitializePrefixRangeLanes(JoinHashTable &ht, idx_t task_count) { @@ -1347,9 +1209,10 @@ class HashJoinFinalizeEvent : public BasePipelineEvent { } const auto state_size = ht.GetPrefixRangeBuildStateSize(); D_ASSERT(state_size > 0); - const auto memory_budget = GetJoinRuntimeFilterMemoryBudget(sink.context); - const auto build_budget = ht.HasSingleEqualityKey() ? MAX_PREFIX_RANGE_BUILD_MEMORY - : MinValue(MAX_PREFIX_RANGE_BUILD_MEMORY, memory_budget); + const auto memory_budget = JoinFilterPushdownInfo::GetMemoryBudget(sink.context); + const auto build_budget = ht.HasSingleEqualityKey() + ? JoinFilterPushdownInfo::MAX_PREFIX_RANGE_BUILD_MEMORY + : MinValue(JoinFilterPushdownInfo::MAX_PREFIX_RANGE_BUILD_MEMORY, memory_budget); const auto lanes_within_budget = MaxValue(build_budget / state_size, 1); const auto lane_count = MinValue(task_count, lanes_within_budget); prefix_range_lanes.reserve(lane_count); @@ -1373,7 +1236,7 @@ void HashJoinGlobalSinkState::ScheduleFinalize(Pipeline &pipeline, Event &event) if (FinalizeSingleThreaded(*this)) { new_init_event->ExecuteDirectly(); auto new_finalize_event = make_shared_ptr(pipeline, *this); - new_finalize_event->ExecuteDirectly(); + new_finalize_event->ExecuteDirectly(event); return; } event.InsertEvent(new_init_event); @@ -1491,14 +1354,16 @@ class HashJoinRepartitionEvent : public BasePipelineEvent { const auto num_partitions = RadixPartitioning::NumberOfPartitions(sink.hash_table->GetRadixBits()); vector partition_sizes(num_partitions, 0); vector partition_counts(num_partitions, 0); + sink.hash_table->GetSinkCollection().GetSizesAndCounts(partition_sizes, partition_counts); sink.total_size = sink.hash_table->GetTotalSize(partition_sizes, partition_counts, sink.max_partition_size, sink.max_partition_count); sink.probe_side_requirement = GetPartitioningSpaceRequirement(sink.context, op.types, sink.hash_table->GetRadixBits(), sink.num_threads); - sink.temporary_memory_state->SetMinimumReservation(sink.max_partition_size + - sink.hash_table->PointerTableSize(sink.max_partition_count) + - sink.probe_side_requirement); + sink.temporary_memory_state->SetMinimumReservation( + sink.max_partition_size + sink.hash_table->PointerTableSize(sink.max_partition_count) + + sink.probe_side_requirement + sink.hash_table->GetRetainedDictionarySize()); + sink.temporary_memory_state->SetRemainingSize(sink.total_size); sink.temporary_memory_state->UpdateReservation(executor.context.GetContext()); FinalizeExternalRuntimeFilters(sink.context, op, sink); @@ -1508,621 +1373,17 @@ class HashJoinRepartitionEvent : public BasePipelineEvent { } }; -bool JoinFilterPushdownInfo::CanUseInFilter(const ClientContext &context, optional_ptr ht, - const ExpressionType &cmp) const { - auto dynamic_or_filter_threshold = Settings::Get(context); - return ht && ht->Count() > 1 && ht->Count() <= dynamic_or_filter_threshold && - (cmp == ExpressionType::COMPARE_EQUAL || cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM); -} - -bool JoinFilterPushdownInfo::CanUseBloomFilter(const JoinFilterPushdownFilter &info, const ClientContext &context, - const PhysicalComparisonJoin &op, const ExpressionType &cmp, - optional_ptr ht) const { - if (!ht) { - return false; - } - - // bf is only supported for equality conditions - if (cmp != ExpressionType::COMPARE_EQUAL && cmp != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { - return false; - } - - auto build_count = ht->Count(); - if (build_count == 0) { - build_count = ht->GetSinkCollection().Count(); - } - auto probe_cardinality = op.children[0].get().estimated_cardinality; - if (build_side_has_filter) { - probe_cardinality = MaxValue(info.estimated_scan_cardinality, probe_cardinality); - } - const double build_to_probe_ratio = static_cast(build_count) / static_cast(probe_cardinality); - if (build_to_probe_ratio > BUILD_TO_PROBE_RATIO_THRESHOLD) { - return false; - } - - // if we have a build side without a filter, only build the bloom filter if the ratio/size is small enough - if (!build_side_has_filter && build_to_probe_ratio > NON_FILTERING_RATIO_THRESHOLD && - build_count > NON_FILTERING_BUILD_SIDE_THRESHOLD) { - return false; - } - - // per-key filters only pay off when the build side is much smaller than the probe side - if (!ht->HasSingleEqualityKey() && build_to_probe_ratio > MULTI_KEY_RATIO_THRESHOLD) { - return false; - } - - return true; -} - -static unique_ptr CreateSelectivityOptionalExpressionFilter(unique_ptr child_expr, - const LogicalType &column_type, - SelectivityOptionalFilterType type); - -struct RuntimeFilterInput { - unique_ptr expression; - bool preserves_cast_errors; -}; - -static RuntimeFilterInput CreateRuntimeFilterInputExpression(ClientContext &context, - const JoinFilterPushdownColumn &column, - const LogicalType &runtime_type) { - bool preserves_cast_errors = false; - auto expression = RuntimeFilterCastUtil::CreateRuntimeFilterInputExpression(context, column, preserves_cast_errors); - D_ASSERT(expression->GetReturnType() == RuntimeFilterCastUtil::GetRuntimeFilterInputType(column, runtime_type)); - return {std::move(expression), preserves_cast_errors}; -} - -static unique_ptr RetainRuntimeFilterNulls(unique_ptr filter_expr, - unique_ptr null_check_input) { - if (!null_check_input) { - return filter_expr; - } - // Retain NULL join keys and inputs whose original cast can fail. - auto null_check = - ExpressionFilter::CreateNullCheckExpression(std::move(null_check_input), ExpressionType::OPERATOR_IS_NULL); - return make_uniq(ExpressionType::CONJUNCTION_OR, std::move(null_check), - std::move(filter_expr)); -} - -void JoinFilterPushdownInfo::DeferRuntimeFilter(DeferredRuntimeFilterType type, const PhysicalOperator &op, - const JoinFilterPushdownFilter &info, - const JoinFilterPushdownColumn &column, ProjectionIndex filter_col_idx, - idx_t key_idx, JoinFilterGlobalState &gstate) const { - gstate.deferred_runtime_filters.push_back({type, &op, info.dynamic_filters, column, filter_col_idx, key_idx}); -} - -bool JoinFilterPushdownInfo::TryRegisterPrefixRangeFilter(const JoinFilterPushdownFilter &info, ClientContext &context, - JoinHashTable &ht, const PhysicalOperator &op, - const JoinFilterPushdownColumn &column, - ProjectionIndex filter_col_idx, idx_t key_idx, - const Value &min_val, const Value &max_val, idx_t max_bits, - JoinFilterGlobalState &gstate) const { - if (!ht.GetPrefixRangeFilter(key_idx)) { - const auto key_type = ht.conditions[key_idx].GetLHS().GetReturnType(); - auto prefix_filter = PrefixRangeFilter::CreatePrefixRangeFilter(key_type); - prefix_filter->Initialize(context, ht.Count(), min_val, max_val, max_bits); - ht.SetPrefixRangeFilter(key_idx, std::move(prefix_filter)); - ht.SetBuildPrefixRangeFilter(); - } - - DeferRuntimeFilter(DeferredRuntimeFilterType::PREFIX_RANGE, op, info, column, filter_col_idx, key_idx, gstate); - return true; -} - -unique_ptr JoinFilterPushdownInfo::FinalizeMinMax(JoinFilterGlobalState &gstate) const { - // finalize the min/max aggregates - vector min_max_types; - for (auto &aggr_expr : min_max_aggregates) { - min_max_types.push_back(aggr_expr->GetReturnType()); - } - auto final_min_max = make_uniq(); - final_min_max->Initialize(Allocator::DefaultAllocator(), min_max_types); - - gstate.global_aggregate_state->Finalize(*final_min_max); - return final_min_max; -} - -static unique_ptr CreateSelectivityOptionalExpressionFilter(unique_ptr child_expr, - const LogicalType &column_type, - SelectivityOptionalFilterType type) { - float selectivity_threshold; - idx_t n_vectors_to_check; - GetThresholdAndVectorsToCheck(type, selectivity_threshold, n_vectors_to_check); - return make_uniq(CreateSelectivityOptionalFilterExpression( - std::move(child_expr), column_type, selectivity_threshold, n_vectors_to_check)); -} - -static SelectivityOptionalFilterType GetSelectivityOptionalFilterType(DeferredRuntimeFilterType type) { - switch (type) { - case DeferredRuntimeFilterType::BLOOM_FILTER: - return SelectivityOptionalFilterType::BF; - case DeferredRuntimeFilterType::PREFIX_RANGE: - return SelectivityOptionalFilterType::PRF; - default: - throw InternalException("Unknown deferred runtime filter type"); - } -} - -static const char *GetRuntimeFilterTypeName(DeferredRuntimeFilterType type) { - switch (type) { - case DeferredRuntimeFilterType::BLOOM_FILTER: - return "BLOOM_FILTER"; - case DeferredRuntimeFilterType::PREFIX_RANGE: - return "PREFIX_RANGE"; - default: - throw InternalException("Unknown deferred runtime filter type"); - } -} - -static const char *GetRuntimeFilterReconstructionModeName(JoinFilterPushdownMode mode) { - switch (mode) { - case JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION: - return "RECONSTRUCT_EXPRESSION"; - case JoinFilterPushdownMode::STORAGE_ONLY: - return "STORAGE_ONLY"; - default: - throw InternalException("Unknown join filter pushdown mode"); - } -} - -static unique_ptr CreateRuntimeFilterExpression(ClientContext &context, JoinHashTable &ht, - const DeferredRuntimeFilterPushdown &deferred, - float selectivity_threshold, idx_t n_vectors_to_check) { - const auto key_idx = deferred.key_idx; - const auto key_name = ht.conditions[key_idx].GetRHS().ToString(); - const auto key_type = ht.conditions[key_idx].GetLHS().GetReturnType(); - auto filter_input_type = RuntimeFilterCastUtil::GetRuntimeFilterInputType(deferred.column, key_type); - auto input = CreateRuntimeFilterInputExpression(context, deferred.column, key_type); - const auto filters_null_values = !input.preserves_cast_errors && !ht.NullValuesAreEqual(key_idx); - vector> children; - children.push_back(std::move(input.expression)); - - unique_ptr filter_expr; - switch (deferred.type) { - case DeferredRuntimeFilterType::BLOOM_FILTER: { - // a filter that is not sealed does not describe the complete build side - publishing it would drop - // rows - and a filter that saturated is not worth the hashing it costs the scan - if (!ht.HasPublishableBloomFilter(key_idx)) { - return nullptr; - } - auto bloom_filter = ht.GetBloomFilter(key_idx); - // the filter escapes to probe-side scans here, so a later recursive iteration must not reuse it - bloom_filter->MarkPublished(); - filter_expr = make_uniq( - BoundScalarFunction(BloomFilterScalarFun::GetFunction(filter_input_type)), std::move(children), - make_uniq(std::move(bloom_filter), filters_null_values, key_name, key_type, - selectivity_threshold, n_vectors_to_check)); - break; - } - case DeferredRuntimeFilterType::PREFIX_RANGE: { - auto prefix_range_filter = ht.GetPrefixRangeFilter(key_idx); - D_ASSERT(prefix_range_filter && prefix_range_filter->IsInitialized()); - if (!prefix_range_filter || !prefix_range_filter->IsInitialized()) { - return nullptr; - } - filter_expr = make_uniq( - BoundScalarFunction(PrefixRangeScalarFun::GetFunction(filter_input_type)), std::move(children), - make_uniq(prefix_range_filter, filters_null_values, key_name, key_type, - selectivity_threshold, n_vectors_to_check)); - break; - } - default: - throw InternalException("Unknown deferred runtime filter type"); - } - return filter_expr; -} - -static void PublishDeferredRuntimeFilters(ClientContext &context, JoinHashTable &ht, JoinFilterGlobalState &gstate) { - if (gstate.deferred_runtime_filters.empty()) { - return; - } - for (auto &deferred : gstate.deferred_runtime_filters) { - D_ASSERT(deferred.op); - if (!deferred.op || !deferred.dynamic_filters) { - continue; - } - const auto filter_type = GetSelectivityOptionalFilterType(deferred.type); - float selectivity_threshold; - idx_t n_vectors_to_check; - GetThresholdAndVectorsToCheck(filter_type, selectivity_threshold, n_vectors_to_check); - auto filter_expr = - CreateRuntimeFilterExpression(context, ht, deferred, selectivity_threshold, n_vectors_to_check); - if (!filter_expr) { - continue; - } - deferred.dynamic_filters->PushFilter(*deferred.op, deferred.filter_col_idx, - CreateSelectivityOptionalExpressionFilter( - std::move(filter_expr), deferred.column.storage_type, filter_type)); - DUCKDB_LOG(context, PhysicalOperatorLogType, *deferred.op, "PhysicalHashJoin", "PublishRuntimeFilter", - {{"kind", GetRuntimeFilterTypeName(deferred.type)}, - {"storage_type", deferred.column.storage_type.ToString()}, - {"reconstruction_mode", GetRuntimeFilterReconstructionModeName(deferred.column.mode)}, - {"uses_try_cast", to_string(RuntimeFilterCastUtil::RuntimeFilterUsesTryCast(deferred.column))}}); - } - gstate.deferred_runtime_filters.clear(); -} - -static void CreateDynamicMinMaxFilter(const PhysicalComparisonJoin &op, const JoinFilterPushdownFilter &info, - const ProjectionIndex &filter_col_idx, unique_ptr filter_expr, - const LogicalType &column_type, bool selectivity_optional) { - if (!filter_expr) { - return; - } - if (selectivity_optional) { - info.dynamic_filters->PushFilter( - op, filter_col_idx, - CreateSelectivityOptionalExpressionFilter(std::move(filter_expr), column_type, - SelectivityOptionalFilterType::MIN_MAX)); - } else { - info.dynamic_filters->PushFilter( - op, filter_col_idx, - make_uniq(CreateOptionalFilterExpression(std::move(filter_expr), column_type))); - } -} - -static unique_ptr CreateComparisonExpressionFilter(ExpressionType comparison_type, - unique_ptr input, const Value &constant, - const LogicalType &comparison_logical_type) { - auto constant_value = constant.DefaultTryCastAs(comparison_logical_type); - if (!constant_value) { - return nullptr; - } - return BoundComparisonExpression::Create(comparison_type, std::move(input), - make_uniq(std::move(*constant_value))); -} - -static unique_ptr CreateComparisonExpressionFilter(ExpressionType comparison_type, const Value &constant, - const LogicalType &column_type) { - auto column = make_uniq(column_type, 0ULL); - return CreateComparisonExpressionFilter(comparison_type, std::move(column), constant, column_type); -} - -static unique_ptr CreateJoinFilterComparisonExpression( - ClientContext &context, const JoinFilterPushdownColumn &column, ExpressionType comparison_type, - const Value &constant, const LogicalType &comparison_logical_type, bool reconstruct_expression, bool retain_nulls) { - if (!reconstruct_expression) { - D_ASSERT(!retain_nulls); - return CreateComparisonExpressionFilter(comparison_type, constant, comparison_logical_type); - } - auto input = CreateRuntimeFilterInputExpression(context, column, comparison_logical_type); - auto input_type = input.expression->GetReturnType(); - unique_ptr null_check_input; - if (input.preserves_cast_errors || retain_nulls) { - null_check_input = input.expression->Copy(); - } - auto filter_expr = - CreateComparisonExpressionFilter(comparison_type, std::move(input.expression), constant, input_type); - if (!filter_expr) { - return nullptr; - } - return RetainRuntimeFilterNulls(std::move(filter_expr), std::move(null_check_input)); -} - -bool JoinFilterPushdownInfo::PushInFilter(ClientContext &context, const JoinFilterPushdownFilter &info, - const JoinFilterPushdownColumn &column, JoinHashTable &ht, - const PhysicalOperator &op, idx_t filter_idx, - ProjectionIndex filter_col_idx) const { - // 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) { - return false; - } - - const auto retain_nulls = ht.conditions[build_idx].GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM; - const auto reconstruct_expression = - retain_nulls || RuntimeFilterCastUtil::RequiresRuntimeFilterExpressionReconstruction(column, runtime_type); - auto filter_input_type = column.storage_type; - unique_ptr filter_input; - unique_ptr null_check_input; - if (reconstruct_expression) { - auto input = CreateRuntimeFilterInputExpression(context, column, runtime_type); - filter_input_type = input.expression->GetReturnType(); - if (input.preserves_cast_errors || retain_nulls) { - null_check_input = input.expression->Copy(); - } - filter_input = std::move(input.expression); - } else { - filter_input = make_uniq(column.storage_type, idx_t(0)); - } - - value_set_t unique_ht_values; - for (idx_t k = 0; k < key_count; k++) { - auto value = build_vector.GetValue(k).DefaultTryCastAs(filter_input_type); - if (!value) { - return false; - } - if (retain_nulls && value->IsNull()) { - continue; - } - unique_ht_values.insert(std::move(*value)); - } - vector in_list(unique_ht_values.begin(), unique_ht_values.end()); - - // An IN filter is only useful when the values are neither null nor dense. - if (in_list.empty() || FilterCombiner::ContainsNull(in_list) || FilterCombiner::IsDenseRange(in_list)) { - return false; - } - - auto in_expr = ExpressionFilter::CreateInExpression(std::move(filter_input), std::move(in_list)); - in_expr = RetainRuntimeFilterNulls(std::move(in_expr), std::move(null_check_input)); - auto filter = make_uniq(CreateOptionalFilterExpression(std::move(in_expr), column.storage_type)); - info.dynamic_filters->PushFilter(op, filter_col_idx, std::move(filter)); - return true; -} - -static void CreateDynamicMinMaxFilters(const PhysicalComparisonJoin &op, const JoinFilterPushdownFilter &info, - ClientContext &context, const JoinFilterPushdownColumn &column, - ProjectionIndex filter_col_idx, ExpressionType cmp, const Value &min_val, - const Value &max_val, const LogicalType &condition_type, - bool reconstruct_expression, bool selectivity_optional) { - auto filter_column_type = reconstruct_expression ? column.storage_type : condition_type; - const auto retain_nulls = cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM; - switch (cmp) { - case ExpressionType::COMPARE_EQUAL: - case ExpressionType::COMPARE_NOT_DISTINCT_FROM: - case ExpressionType::COMPARE_GREATERTHAN: - case ExpressionType::COMPARE_GREATERTHANOREQUALTO: { - CreateDynamicMinMaxFilter( - op, info, filter_col_idx, - CreateJoinFilterComparisonExpression(context, column, ExpressionType::COMPARE_GREATERTHANOREQUALTO, min_val, - condition_type, reconstruct_expression, retain_nulls), - filter_column_type, selectivity_optional); - break; - } - default: - break; - } - switch (cmp) { - case ExpressionType::COMPARE_EQUAL: - case ExpressionType::COMPARE_NOT_DISTINCT_FROM: - case ExpressionType::COMPARE_LESSTHAN: - case ExpressionType::COMPARE_LESSTHANOREQUALTO: { - CreateDynamicMinMaxFilter( - op, info, filter_col_idx, - CreateJoinFilterComparisonExpression(context, column, ExpressionType::COMPARE_LESSTHANOREQUALTO, max_val, - condition_type, reconstruct_expression, retain_nulls), - filter_column_type, selectivity_optional); - break; - } - default: - break; - } -} - -static idx_t BloomFilterBitBudget(idx_t ht_count) { - return BloomFilter::GetNumberOfSectors(ht_count) * 64; -} - -struct JoinFilterPushdownCandidate { - const JoinFilterPushdownFilter &info; - const JoinFilterPushdownColumn &column; - Value min_val; - Value max_val; - bool reconstruct_expression; - bool can_emit_runtime_filter; -}; - -struct JoinFilterPushdownInfo::FilterFinalizer { - const JoinFilterPushdownInfo &pushdown; - ClientContext &context; - const PhysicalComparisonJoin &op; - DataChunk &final_min_max; - optional_ptr ht; - optional_ptr gstate; - bool allow_bloom_filters; - bool allow_prefix_range_filters; - -public: - vector PrepareCandidates() const; - //! A zero bit budget disables runtime filters when the per-key share is too small. - idx_t SetRuntimeFilterBudget(const vector &candidates); - void FinalizeCandidate(const JoinFilterPushdownCandidate &candidate, idx_t prefix_range_bit_budget); -}; - -vector JoinFilterPushdownInfo::FilterFinalizer::PrepareCandidates() const { - vector candidates; - // Prepare each destination once before dividing the budget among distinct keys. - for (auto &info : pushdown.probe_info) { - for (auto &pushdown_column : info.columns) { - auto filter_idx = pushdown_column.join_filter_idx; - D_ASSERT(filter_idx != DConstants::INVALID_INDEX); - D_ASSERT(filter_idx < pushdown.join_condition.size()); - const auto key_idx = pushdown.join_condition[filter_idx]; - const auto cmp = op.conditions[key_idx].GetComparisonType(); - auto min_idx = filter_idx * 2; - auto max_idx = min_idx + 1; - - auto min_val_before_cast = final_min_max.data[min_idx].GetValue(0); - auto max_val_before_cast = final_min_max.data[max_idx].GetValue(0); - - auto min_val = min_val_before_cast; - auto max_val = max_val_before_cast; - const bool retain_nulls = cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM; - const bool reconstruct_filter_expression = - retain_nulls || RuntimeFilterCastUtil::RequiresRuntimeFilterExpressionReconstruction( - pushdown_column, min_val_before_cast.type()); - - // Cast to storage type, skip if fails - if (pushdown_column.storage_type.IsValid() && !reconstruct_filter_expression) { - auto cast_min = min_val.DefaultTryCastAs(pushdown_column.storage_type); - auto cast_max = max_val.DefaultTryCastAs(pushdown_column.storage_type); - if (!cast_min || !cast_max) { - continue; - } - min_val = std::move(*cast_min); - max_val = std::move(*cast_max); - } - - if (min_val.IsNull() || max_val.IsNull()) { - // min/max is NULL - // this can happen in case all values in the RHS column are NULL, but they are still pushed into the - // hash table e.g. because they are part of a RIGHT join - continue; - } - - auto condition_type = min_val.type(); - auto runtime_filter_input_type = - RuntimeFilterCastUtil::GetRuntimeFilterInputType(pushdown_column, condition_type); - const bool can_emit_runtime_filter = - ht && gstate && (allow_bloom_filters || allow_prefix_range_filters) && - pushdown_column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION && - runtime_filter_input_type == ht->conditions[key_idx].GetLHS().GetReturnType() && - !Value::NotDistinctFrom(min_val, max_val) && pushdown.CanUseBloomFilter(info, context, op, cmp, ht); - candidates.push_back({info, pushdown_column, std::move(min_val), std::move(max_val), - reconstruct_filter_expression, can_emit_runtime_filter}); - } - } - return candidates; -} - -idx_t JoinFilterPushdownInfo::FilterFinalizer::SetRuntimeFilterBudget( - const vector &candidates) { - if (!ht || ht->HasSingleEqualityKey()) { - return NumericLimits::Maximum(); - } - - vector runtime_filter_keys(op.conditions.size(), false); - idx_t runtime_filter_count = 0; - for (auto &candidate : candidates) { - const auto key_idx = pushdown.join_condition[candidate.column.join_filter_idx]; - if (candidate.can_emit_runtime_filter && !runtime_filter_keys[key_idx]) { - runtime_filter_keys[key_idx] = true; - runtime_filter_count++; - } - } - const auto budget_share = MaxValue(runtime_filter_count, 1); - const auto memory_budget = GetJoinRuntimeFilterMemoryBudget(context); - ht->SetKeyBloomFilterBudget(memory_budget / budget_share); - // Leave room for at least one complete build lane as well as the published bitmaps. - const auto prefix_range_budget = MinValue(memory_budget, MAX_PREFIX_RANGE_BUILD_MEMORY); - const auto column_budget = prefix_range_budget / budget_share; - return column_budget >= 128 ? ((column_budget - 64) / 8) * 64 : 0; -} - -void JoinFilterPushdownInfo::FilterFinalizer::FinalizeCandidate(const JoinFilterPushdownCandidate &candidate, - idx_t prefix_range_bit_budget) { - auto &info = candidate.info; - auto &pushdown_column = candidate.column; - const auto filter_idx = pushdown_column.join_filter_idx; - const auto key_idx = pushdown.join_condition[filter_idx]; - const auto cmp = op.conditions[key_idx].GetComparisonType(); - auto &filter_col_idx = pushdown_column.probe_column_index.column_index; - auto &min_val = candidate.min_val; - auto &max_val = candidate.max_val; - const auto &condition_type = min_val.type(); - const bool retain_nulls = cmp == ExpressionType::COMPARE_NOT_DISTINCT_FROM; - const auto reconstruct_filter_expression = candidate.reconstruct_expression; - const auto can_emit_runtime_filters = prefix_range_bit_budget > 0 && candidate.can_emit_runtime_filter; - if (Value::NotDistinctFrom(min_val, max_val)) { - // A single build value produces one comparison, including for non-equality joins. - auto filter_expr = CreateJoinFilterComparisonExpression(context, pushdown_column, cmp, min_val, condition_type, - reconstruct_filter_expression, retain_nulls); - if (filter_expr) { - info.dynamic_filters->PushFilter(op, filter_col_idx, make_uniq(std::move(filter_expr))); - } - return; - } - if (cmp != ExpressionType::COMPARE_EQUAL && !retain_nulls) { - // Non-equality comparisons need a half-open range. - CreateDynamicMinMaxFilters(op, info, context, pushdown_column, filter_col_idx, cmp, min_val, max_val, - condition_type, reconstruct_filter_expression, true); - return; - } - - auto min_val_before_cast = final_min_max.data[filter_idx * 2].GetValue(0); - auto max_val_before_cast = final_min_max.data[filter_idx * 2 + 1].GetValue(0); - uhugeint_t span; - const auto can_compute_span = PrefixRangeFilter::TryComputeSpan(min_val_before_cast, max_val_before_cast, span); - const auto can_emit_prf = allow_prefix_range_filters && can_emit_runtime_filters && - PrefixRangeFilter::SupportedType(ht->conditions[key_idx].GetLHS().GetReturnType()) && - can_compute_span; - - bool pushed_in_filter = false; - if (pushdown.CanUseInFilter(context, ht, cmp)) { - pushed_in_filter = pushdown.PushInFilter(context, info, pushdown_column, *ht, op, filter_idx, filter_col_idx); - } - - static constexpr idx_t SMALL_EXACT_PRF_BITS = 1ULL << 26; - const auto exact_prf_bits = MinValue(SMALL_EXACT_PRF_BITS, prefix_range_bit_budget); - bool registered_prf = - can_emit_prf && span < exact_prf_bits && - pushdown.TryRegisterPrefixRangeFilter(info, context, *ht, op, pushdown_column, filter_col_idx, key_idx, - min_val_before_cast, max_val_before_cast, exact_prf_bits, *gstate); - - if (can_emit_prf && !registered_prf) { - auto build_count = ht->Count(); - if (build_count == 0) { - build_count = ht->GetSinkCollection().Count(); - } - const auto bloom_filter_bits = MinValue(BloomFilterBitBudget(build_count), prefix_range_bit_budget); - registered_prf = - span <= bloom_filter_bits && - pushdown.TryRegisterPrefixRangeFilter(info, context, *ht, op, pushdown_column, filter_col_idx, key_idx, - min_val_before_cast, max_val_before_cast, bloom_filter_bits, *gstate); - } - // Keep multi-key min/max filters for their complementary statistics pruning. - if (registered_prf && ht->HasSingleEqualityKey()) { - return; - } - - if (!pushed_in_filter) { - CreateDynamicMinMaxFilters(op, info, context, pushdown_column, filter_col_idx, cmp, min_val, max_val, - condition_type, reconstruct_filter_expression, false); - } - if (!registered_prf && allow_bloom_filters && can_emit_runtime_filters) { - if (ht->HasPublishableBloomFilter(key_idx)) { - // A complete filter was accumulated during Sink (external joins build it there). - pushdown.DeferRuntimeFilter(DeferredRuntimeFilterType::BLOOM_FILTER, op, info, pushdown_column, - filter_col_idx, key_idx, *gstate); - } else if (allow_prefix_range_filters) { - // Build during finalize only when it materializes the whole build side; external finalize does not. - ht->SetBuildBloomFilter(key_idx); - pushdown.DeferRuntimeFilter(DeferredRuntimeFilterType::BLOOM_FILTER, op, info, pushdown_column, - filter_col_idx, key_idx, *gstate); - } - } -} - -unique_ptr JoinFilterPushdownInfo::FinalizeFilters(ClientContext &context, const PhysicalComparisonJoin &op, - unique_ptr final_min_max, - optional_ptr ht, bool allow_bloom_filters, - bool allow_prefix_range_filters, - optional_ptr gstate) const { - if (probe_info.empty()) { - return final_min_max; - } - - FilterFinalizer finalizer { - *this, context, op, *final_min_max, ht, gstate, allow_bloom_filters, allow_prefix_range_filters}; - auto candidates = finalizer.PrepareCandidates(); - const auto prefix_range_bit_budget = finalizer.SetRuntimeFilterBudget(candidates); - for (auto &candidate : candidates) { - finalizer.FinalizeCandidate(candidate, prefix_range_bit_budget); - } - return final_min_max; -} - -unique_ptr JoinFilterPushdownInfo::Finalize(ClientContext &context, JoinFilterGlobalState &gstate, - const PhysicalComparisonJoin &op, - optional_ptr ht) const { - auto final_min_max = FinalizeMinMax(gstate); - return FinalizeFilters(context, op, std::move(final_min_max), ht, true, true, &gstate); -} - +//! The IN filter threshold limits the number of distinct values of a key column, not the number of build rows. SinkFinalizeType PhysicalHashJoin::Finalize(Pipeline &pipeline, Event &event, ClientContext &context, OperatorSinkFinalizeInput &input) const { auto &sink = input.global_state.Cast(); auto &ht = *sink.hash_table; // the filter covers the whole build side once Sink is done - ht.SealBloomFilter(); + ht.SealBloomFilters(); sink.temporary_memory_state->UpdateReservation(context.GetContext()); - sink.external = sink.temporary_memory_state->GetReservation() < sink.total_size; + sink.external = sink.GetMaxInMemoryHTSize() < sink.total_size; if (sink.external) { // For external join we reduce the load factor, this may even prevent the external join altogether ht.load_factor = JoinHashTable::EXTERNAL_LOAD_FACTOR; @@ -2132,7 +1393,7 @@ SinkFinalizeType PhysicalHashJoin::Finalize(Pipeline &pipeline, Event &event, Cl idx_t temp_total_size = ht.GetTotalSize(sink.local_hash_tables, temp_max_partition_size, temp_max_partition_count); - if (temp_total_size < sink.temporary_memory_state->GetReservation()) { + if (temp_total_size <= sink.GetMaxInMemoryHTSize()) { // We prevented the external join by reducing the load factor. Update the state accordingly sink.temporary_memory_state->SetMinimumReservation(temp_total_size); sink.temporary_memory_state->SetRemainingSizeAndUpdateReservation(context.GetContext(), temp_total_size); @@ -2145,19 +1406,23 @@ SinkFinalizeType PhysicalHashJoin::Finalize(Pipeline &pipeline, Event &event, Cl } } DUCKDB_LOG(context, PhysicalOperatorLogType, *this, "PhysicalHashJoin", "Finalize", - {{"external", to_string(sink.external)}}); + {{"external", to_string(sink.external)}, + {"build_size", to_string(sink.total_size)}, + {"reservation", to_string(sink.temporary_memory_state->GetReservation())}}); if (sink.external) { // External Hash Join // Recursive preserved-build reuse only applies to the in-memory finalized HT. External hash join // runs through repeated build/probe rounds with partition/probe-spill state, so it cannot be // treated as a stable materialized build that later recursive iterations may skip entirely. sink.preserve_build_for_reuse = false; + sink.total_size = ht.GetTotalSize(sink.local_hash_tables, sink.max_partition_size, sink.max_partition_count, + JoinHashTable::LookupSizing::HASH_ONLY); + sink.temporary_memory_state->SetRemainingSizeAndUpdateReservation(context.GetContext(), sink.total_size); const auto max_partition_ht_size = sink.max_partition_size + ht.PointerTableSize(sink.max_partition_count); const auto very_very_skewed = // No point in repartitioning if it's this skewed static_cast(max_partition_ht_size) >= 0.8 * static_cast(sink.total_size); - if (!very_very_skewed && - (max_partition_ht_size + sink.probe_side_requirement) > sink.temporary_memory_state->GetReservation()) { + if (!very_very_skewed && max_partition_ht_size > sink.GetMaxExternalHTSize()) { // We have to repartition const auto radix_bits_before = ht.GetRadixBits(); ht.SetRepartitionRadixBits(sink.GetMaxExternalHTSize(), sink.max_partition_size, sink.max_partition_count); @@ -2182,6 +1447,7 @@ SinkFinalizeType PhysicalHashJoin::Finalize(Pipeline &pipeline, Event &event, Cl } // In-memory Hash Join + sink.temporary_memory_state->SetMinimumReservation(sink.total_size); for (auto &local_ht : sink.local_hash_tables) { ht.Merge(local_ht.get()); } @@ -2215,9 +1481,6 @@ static bool CanUseCompressedProbe(const HashJoinGlobalSinkState &sink, const vec // external joins re-finalize the HT mid-probe, invalidating the per-id pointer cache return false; } - if (!sink.hash_table->SupportsCompressedProbe()) { - return false; - } if (conditions.size() != 1) { return false; } @@ -2275,8 +1538,8 @@ class HashJoinOperatorState : public CachingOperatorState { if (spill_chunk.ColumnCount() != 0) { spill_chunk.Reset(); } - // discard cached build-side pointers; the HT may have been reset between iterations (e.g. recursive CTE) - if (probe_state.dict_state) { + probe_state.dict_state.reset(); + if (CanUseCompressedProbe(op.sink_state->Cast(), op.conditions)) { probe_state.dict_state = make_uniq(); } } @@ -2302,7 +1565,7 @@ unique_ptr PhysicalHashJoin::GetOperatorState(ExecutionContext &c TupleDataCollection::InitializeChunkState(state->join_key_state, condition_types); if (sink.external) { - state->spill_chunk.InitializeEmpty(sink.probe_types); + state->spill_chunk.Initialize(allocator, sink.probe_types, vector(sink.probe_types.size(), false)); sink.InitializeProbeSpill(); } @@ -2644,6 +1907,7 @@ void HashJoinGlobalSourceState::PrepareBuild(HashJoinGlobalSinkState &sink) { auto &data_collection = ht.GetDataCollection(); if (data_collection.Count() == 0 && op.EmptyResultIfRHSIsEmpty()) { + ht.Reset(); PrepareBuild(sink); return; } diff --git a/src/duckdb/src/execution/operator/join/physical_iejoin.cpp b/src/duckdb/src/execution/operator/join/physical_iejoin.cpp index 40b93de25..72861de62 100644 --- a/src/duckdb/src/execution/operator/join/physical_iejoin.cpp +++ b/src/duckdb/src/execution/operator/join/physical_iejoin.cpp @@ -21,9 +21,10 @@ namespace duckdb { -PhysicalIEJoin::PhysicalIEJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, PhysicalOperator &left, - PhysicalOperator &right, vector cond, JoinType join_type, - idx_t estimated_cardinality, unique_ptr pushdown_info) +PhysicalIEJoin::PhysicalIEJoin(PhysicalPlan &physical_plan, ClientContext &context, LogicalComparisonJoin &op, + PhysicalOperator &left, PhysicalOperator &right, vector cond, + JoinType join_type, idx_t estimated_cardinality, + unique_ptr pushdown_info) : PhysicalRangeJoin(physical_plan, op, PhysicalOperatorType::IE_JOIN, left, right, std::move(cond), join_type, estimated_cardinality, std::move(pushdown_info)) { // 1. let L1 (resp. L2) be the array of column X (resp. Y) @@ -63,12 +64,14 @@ PhysicalIEJoin::PhysicalIEJoin(PhysicalPlan &physical_plan, LogicalComparisonJoi D_ASSERT(cond.GetLHS().GetReturnType() == cond.GetRHS().GetReturnType()); join_key_types.push_back(cond.GetLHS().GetReturnType()); } + tail_predicate = CreateTailPredicate(context, conditions, 2); } -PhysicalIEJoin::PhysicalIEJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, PhysicalOperator &left, - PhysicalOperator &right, vector cond, JoinType join_type, - idx_t estimated_cardinality) - : PhysicalIEJoin(physical_plan, op, left, right, std::move(cond), join_type, estimated_cardinality, nullptr) { +PhysicalIEJoin::PhysicalIEJoin(PhysicalPlan &physical_plan, ClientContext &context, LogicalComparisonJoin &op, + PhysicalOperator &left, PhysicalOperator &right, vector cond, + JoinType join_type, idx_t estimated_cardinality) + : PhysicalIEJoin(physical_plan, context, op, left, right, std::move(cond), join_type, estimated_cardinality, + nullptr) { } //===--------------------------------------------------------------------===// @@ -418,7 +421,8 @@ class IEJoinLocalSourceState : public LocalSourceState { IEJoinLocalSourceState(ClientContext &client, IEJoinGlobalSourceState &gsource) : gsource(gsource), true_sel(STANDARD_VECTOR_SIZE), left_executor(client), right_executor(client), - simple_sel(STANDARD_VECTOR_SIZE), pred_executor(client), left_matches(nullptr), right_matches(nullptr) + tail_executor(client), simple_sel(STANDARD_VECTOR_SIZE), pred_executor(client), left_matches(nullptr), + right_matches(nullptr) { auto &op = gsource.op; @@ -463,6 +467,8 @@ class IEJoinLocalSourceState : public LocalSourceState { left_keys.Initialize(allocator, left_types); right_keys.Initialize(allocator, right_types); + tail_executor.AddExpression(*op.tail_predicate); + tail_keys.InitializeEmpty(PhysicalRangeJoin::GetTailTypes(op.conditions, 2)); } idx_t SelectOuterRows(bool *matches) { @@ -589,6 +595,9 @@ class IEJoinLocalSourceState : public LocalSourceState { ExpressionExecutor right_executor; DataChunk right_keys; + ExpressionExecutor tail_executor; + DataChunk tail_keys; + DataChunk unprojected; //! Simple join subselection @@ -842,9 +851,8 @@ void IEJoinLocalSourceState::ResolveInnerJoin(ExecutionContext &context, DataChu const SelectionVector *IEJoinLocalSourceState::ApplyTailConditions() { auto &op = gsource.op; const auto &conditions = op.conditions; - auto sel = FlatVector::IncrementalSelectionVector(); if (conditions.size() <= 2) { - return sel; + return FlatVector::IncrementalSelectionVector(); } // If there are more expressions to compute, @@ -856,32 +864,26 @@ const SelectionVector *IEJoinLocalSourceState::ApplyTailConditions() { right_executor.SetChunk(rpayload); auto result_count = lpayload.size(); - auto tail_count = result_count; - auto match_sel = &true_sel; left_keys.Reset(); right_keys.Reset(); - for (size_t cmp_idx = 0; cmp_idx < tail_cols; ++cmp_idx) { + for (idx_t cmp_idx = 0; cmp_idx < tail_cols; ++cmp_idx) { auto &left = left_keys.data[cmp_idx]; left_executor.ExecuteExpression(cmp_idx, left); + tail_keys.data[cmp_idx].Reference(left); auto &right = right_keys.data[cmp_idx]; right_executor.ExecuteExpression(cmp_idx, right); - - if (tail_count < result_count) { - left.Slice(*sel, tail_count); - right.Slice(*sel, tail_count); - } - tail_count = - op.SelectJoinTail(conditions[cmp_idx + 2].GetComparisonType(), left, right, sel, tail_count, match_sel); - sel = match_sel; + tail_keys.data[tail_cols + cmp_idx].Reference(right); } + tail_keys.CheckCardinality(result_count); + const auto tail_count = tail_executor.SelectExpression(tail_keys, true_sel); if (tail_count < result_count) { - lpayload.Slice(*sel, tail_count); - rpayload.Slice(*sel, tail_count); + lpayload.Slice(true_sel, tail_count); + rpayload.Slice(true_sel, tail_count); } - return sel; + return &true_sel; } void IEJoinLocalSourceState::MergePayloads(DataChunk &chunk) { diff --git a/src/duckdb/src/execution/operator/join/physical_nested_loop_join.cpp b/src/duckdb/src/execution/operator/join/physical_nested_loop_join.cpp index e86b3b516..c2ad983d7 100644 --- a/src/duckdb/src/execution/operator/join/physical_nested_loop_join.cpp +++ b/src/duckdb/src/execution/operator/join/physical_nested_loop_join.cpp @@ -2,18 +2,18 @@ #include "duckdb/parallel/thread_context.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/execution/nested_loop_join.hpp" -#include "duckdb/execution/mark_join_row_comparison.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/execution/operator/join/outer_join_marker.hpp" #include "duckdb/common/types/vector_cache.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/constant_vector.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" namespace duckdb { -PhysicalNestedLoopJoin::PhysicalNestedLoopJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, - PhysicalOperator &left, PhysicalOperator &right, - vector conds, JoinType join_type, +PhysicalNestedLoopJoin::PhysicalNestedLoopJoin(PhysicalPlan &physical_plan, ClientContext &context, + LogicalComparisonJoin &op, PhysicalOperator &left, + PhysicalOperator &right, vector conds, JoinType join_type, idx_t estimated_cardinality, unique_ptr pushdown_info_p) : PhysicalComparisonJoin(physical_plan, op, PhysicalOperatorType::NESTED_LOOP_JOIN, std::move(conds), join_type, @@ -28,13 +28,19 @@ PhysicalNestedLoopJoin::PhysicalNestedLoopJoin(PhysicalPlan &physical_plan, Logi if (join_type == JoinType::MARK) { mark_projection_map = FillProjectionMap(left, op.left_projection_map); } + if (predicate && conditions.size() == 1) { + auto &condition = conditions[0]; + condition_comparison = BoundComparisonExpression::CreateOnColumns(context, condition.GetComparisonType(), + condition.GetLHS().GetReturnType(), 0, + condition.GetRHS().GetReturnType(), 1); + } } -PhysicalNestedLoopJoin::PhysicalNestedLoopJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, - PhysicalOperator &left, PhysicalOperator &right, - vector cond, JoinType join_type, +PhysicalNestedLoopJoin::PhysicalNestedLoopJoin(PhysicalPlan &physical_plan, ClientContext &context, + LogicalComparisonJoin &op, PhysicalOperator &left, + PhysicalOperator &right, vector cond, JoinType join_type, idx_t estimated_cardinality) - : PhysicalNestedLoopJoin(physical_plan, op, left, right, std::move(cond), join_type, estimated_cardinality, + : PhysicalNestedLoopJoin(physical_plan, context, op, left, right, std::move(cond), join_type, estimated_cardinality, nullptr) { } @@ -135,6 +141,11 @@ bool PhysicalNestedLoopJoin::IsSupported(const vector &conditions if (join_type == JoinType::MARK) { return true; } + if (join_type == JoinType::RIGHT_SEMI) { + // one comparison that marks the build rows a probe chunk matches, no further predicate: the mark kernel + // compares nested keys as well + return conditions.size() == 1 && conditions[0].IsComparison(); + } idx_t comparison_count = 0; for (auto &cond : conditions) { if (!cond.IsComparison()) { @@ -337,7 +348,8 @@ class PhysicalNestedLoopJoinState : public CachingOperatorState { public: PhysicalNestedLoopJoinState(ClientContext &context, const PhysicalNestedLoopJoin &op, const vector &conditions) - : lhs_executor(context), left_outer(IsLeftOuterJoin(op.join_type)), pred_executor(context) { + : lhs_executor(context), left_outer(IsLeftOuterJoin(op.join_type)), pred_executor(context), + comparison_executor(context) { vector condition_types; for (auto &cond : conditions) { lhs_executor.AddExpression(cond.GetLHS()); @@ -363,6 +375,11 @@ class PhysicalNestedLoopJoinState : public CachingOperatorState { } pred_input.Initialize(allocator, predicate_types); } + if (op.condition_comparison) { + comparison_executor.AddExpression(*op.condition_comparison); + comparison_input.InitializeEmpty( + {conditions[0].GetLHS().GetReturnType(), conditions[0].GetRHS().GetReturnType()}); + } ResetState(); } @@ -387,6 +404,9 @@ class PhysicalNestedLoopJoinState : public CachingOperatorState { SelectionVector pred_matches; DataChunk pred_input; DataChunk mark_payload; + //! The condition of SEMI/ANTI joins with a predicate, over [left constant, right condition] + ExpressionExecutor comparison_executor; + DataChunk comparison_input; private: void ResetState() { @@ -450,6 +470,10 @@ OperatorResultType PhysicalNestedLoopJoin::ExecuteInternal(ExecutionContext &con // simple joins can have max STANDARD_VECTOR_SIZE matches per chunk ResolveSimpleJoin(context, input, chunk, state_p); return OperatorResultType::NEED_MORE_INPUT; + case JoinType::RIGHT_SEMI: + // the source phase emits the matching build rows + ResolveRightSemiJoin(context, input, state_p); + return OperatorResultType::NEED_MORE_INPUT; case JoinType::LEFT: case JoinType::INNER: case JoinType::OUTER: @@ -466,8 +490,7 @@ static void ResolveSimpleJoinPredicate(const vector &conditions, D_ASSERT(conditions.size() == 1); gstate.right_condition_data.InitializeScan(state.condition_scan_state); gstate.right_payload_data.InitializeScan(state.payload_scan_state); - Vector comparison(LogicalType::BOOLEAN); - Vector left_reference(state.left_condition.data[0].GetType()); + auto &comparison_input = state.comparison_input; VectorCache predicate_cache(state.pred_executor.GetAllocator(), LogicalType::BOOLEAN); Vector predicate_result(predicate_cache); while (gstate.right_condition_data.Scan(state.condition_scan_state, state.right_condition)) { @@ -479,18 +502,12 @@ static void ResolveSimpleJoinPredicate(const vector &conditions, if (found_match[left_row]) { continue; } - ConstantVector::Reference(left_reference, count_t(state.right_condition.size()), + ConstantVector::Reference(comparison_input.data[0], count_t(state.right_condition.size()), state.left_condition.data[0], left_row, state.left_condition.size()); - MarkJoinRowComparison::Compare(left_reference, state.right_condition.data[0], - conditions[0].GetComparisonType(), comparison); - auto comparisons = comparison.Values(); - idx_t candidate_count = 0; - for (idx_t right_row = 0; right_row < state.right_condition.size(); right_row++) { - auto entry = comparisons[right_row]; - if (entry.IsValid() && entry.GetValue()) { - state.pred_matches.set_index(candidate_count++, right_row); - } - } + comparison_input.data[1].Reference(state.right_condition.data[0]); + comparison_input.CheckCardinality(state.right_condition.size()); + const auto candidate_count = + state.comparison_executor.SelectExpression(comparison_input, state.pred_matches); if (candidate_count == 0) { continue; } @@ -554,6 +571,42 @@ void PhysicalNestedLoopJoin::ResolveSimpleJoin(ExecutionContext &context, DataCh } } +void PhysicalNestedLoopJoin::ResolveRightSemiJoin(ExecutionContext &context, DataChunk &input, + OperatorState &state_p) const { + auto &state = state_p.Cast(); + auto &gstate = sink_state->Cast(); + D_ASSERT(conditions.size() == 1 && !predicate); + + // resolve the left join condition for the current chunk + state.left_condition.Reset(); + state.lhs_executor.Execute(input, state.left_condition); + + // mark the build rows a probe row matches: each build chunk is the left side of the flipped comparison + const auto comparison = FlipComparisonExpression(conditions[0].GetComparisonType()); + bool found_match[STANDARD_VECTOR_SIZE]; + SelectionVector match_sel(STANDARD_VECTOR_SIZE); + gstate.right_condition_data.InitializeScan(state.condition_scan_state); + while (gstate.right_condition_data.Scan(state.condition_scan_state, state.right_condition)) { + const auto count = state.right_condition.size(); + const auto base = state.condition_scan_state.current_row_index; + memset(found_match, 0, sizeof(bool) * count); + NestedLoopJoinMark::Perform(state.right_condition.data[0], state.left_condition.data[0], count, input.size(), + found_match, comparison); + idx_t match_count = 0; + for (idx_t i = 0; i < count; i++) { + if (found_match[i]) { + match_sel.set_index(match_count++, i); + } + } + if (match_count == 0) { + continue; + } + // the marker is shared by all probe threads + lock_guard guard(gstate.nj_lock); + gstate.right_outer.SetMatches(match_sel, match_count, base); + } +} + OperatorResultType PhysicalNestedLoopJoin::ResolveComplexJoin(ExecutionContext &context, DataChunk &input, DataChunk &chunk, OperatorState &state_p) const { auto &state = state_p.Cast(); @@ -722,8 +775,8 @@ SourceResultType PhysicalNestedLoopJoin::GetDataInternal(ExecutionContext &conte auto &gstate = input.global_state.Cast(); auto &lstate = input.local_state.Cast(); - // if the LHS is exhausted in a FULL/RIGHT OUTER JOIN, we scan chunks we still need to output - sink.right_outer.Scan(gstate.scan_state, lstate.scan_state, chunk); + // the build rows without a match for a FULL/RIGHT OUTER JOIN, the ones with a match for a RIGHT SEMI join + sink.right_outer.Scan(gstate.scan_state, lstate.scan_state, chunk, join_type == JoinType::RIGHT_SEMI); return chunk.size() == 0 ? SourceResultType::FINISHED : SourceResultType::HAVE_MORE_OUTPUT; } diff --git a/src/duckdb/src/execution/operator/join/physical_piecewise_merge_join.cpp b/src/duckdb/src/execution/operator/join/physical_piecewise_merge_join.cpp index 334b2d9f4..020b04cf3 100644 --- a/src/duckdb/src/execution/operator/join/physical_piecewise_merge_join.cpp +++ b/src/duckdb/src/execution/operator/join/physical_piecewise_merge_join.cpp @@ -1,5 +1,6 @@ #include "duckdb/execution/operator/join/physical_piecewise_merge_join.hpp" +#include #include #include "duckdb/common/atomic.hpp" @@ -14,10 +15,10 @@ namespace duckdb { -PhysicalPiecewiseMergeJoin::PhysicalPiecewiseMergeJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, - PhysicalOperator &left, PhysicalOperator &right, - vector cond, JoinType join_type, - idx_t estimated_cardinality, +PhysicalPiecewiseMergeJoin::PhysicalPiecewiseMergeJoin(PhysicalPlan &physical_plan, ClientContext &context, + LogicalComparisonJoin &op, PhysicalOperator &left, + PhysicalOperator &right, vector cond, + JoinType join_type, idx_t estimated_cardinality, unique_ptr pushdown_info_p) : PhysicalRangeJoin(physical_plan, op, PhysicalOperatorType::PIECEWISE_MERGE_JOIN, left, right, std::move(cond), join_type, estimated_cardinality, std::move(pushdown_info_p)) { @@ -52,6 +53,7 @@ PhysicalPiecewiseMergeJoin::PhysicalPiecewiseMergeJoin(PhysicalPlan &physical_pl throw NotImplementedException("Unimplemented join type for merge join"); } } + tail_predicate = CreateTailPredicate(context, conditions, 1); } //===--------------------------------------------------------------------===// @@ -85,10 +87,13 @@ class MergeJoinGlobalState : public GlobalSinkState { bool skip_filter_pushdown = false; //! The global filter states to push down (if any) unique_ptr global_filter_state; + //! The first build row in sort order that a probe row matches (RIGHT SEMI) + atomic right_semi_boundary {0}; private: void ResetState(ClientContext &client) { table->ResetForReuse(client); + right_semi_boundary = 0; if (op.filter_pushdown) { skip_filter_pushdown = op.filter_pushdown->probe_info.empty(); global_filter_state = op.filter_pushdown->GetGlobalState(client, op); @@ -203,7 +208,10 @@ SinkFinalizeType PhysicalPiecewiseMergeJoin::Finalize(Pipeline &pipeline, Event gstate.table->Finalize(client, input.interrupt_state); - if (PropagatesBuildSide(join_type)) { + if (join_type == JoinType::RIGHT_SEMI) { + // the matching build rows are a suffix of the non-NULL keys: probing moves its start down + gstate.right_semi_boundary = gstate.table->Count() - gstate.table->has_null; + } else if (PropagatesBuildSide(join_type)) { // for FULL/RIGHT OUTER JOIN, initialize found_match to false for every tuple gstate.table->InitializeMatches(); } @@ -231,7 +239,7 @@ class PiecewiseMergeJoinState : public CachingOperatorState { PiecewiseMergeJoinState(ClientContext &client, const PhysicalPiecewiseMergeJoin &op) : client(client), allocator(Allocator::Get(client)), op(op), left_outer(IsLeftOuterJoin(op.join_type)), left_position(0), first_fetch(true), finished(true), right_position(0), right_chunk_index(0), - rhs_executor(client), pred_executor(client) { + rhs_executor(client), tail_executor(client), pred_executor(client) { left_outer.Initialize(STANDARD_VECTOR_SIZE); lhs_payload.Initialize(client, op.children[0].get().GetTypes()); @@ -247,6 +255,10 @@ class PiecewiseMergeJoinState : public CachingOperatorState { condition_types.push_back(order.expression->GetReturnType()); } rhs_keys.Initialize(client, condition_types); + if (op.tail_predicate) { + tail_executor.AddExpression(*op.tail_predicate); + tail_keys.InitializeEmpty(PhysicalRangeJoin::GetTailTypes(op.conditions, 1)); + } rhs_input.Initialize(client, op.children[1].get().GetTypes()); auto &gsink = op.sink_state->Cast(); @@ -291,6 +303,8 @@ class PiecewiseMergeJoinState : public CachingOperatorState { DataChunk rhs_keys; DataChunk rhs_input; ExpressionExecutor rhs_executor; + ExpressionExecutor tail_executor; + DataChunk tail_keys; //! Arbitrary expressions ExpressionExecutor pred_executor; @@ -468,6 +482,10 @@ void PhysicalPiecewiseMergeJoin::ResolveSimpleJoin(ExecutionContext &context, Da auto &state = state_p.Cast(); auto &gstate = sink_state->Cast(); + if (!state.rhs_iterator) { + // the state was reset for reuse (a recursive CTE runs its pipelines once per iteration) + state.InitializeRightScanState(gstate); + } state.ResolveJoinKeys(context, input); auto &lhs_table = *state.lhs_global_table; auto &lhs_keys = state.lhs_local_table->keys; @@ -512,6 +530,66 @@ void PhysicalPiecewiseMergeJoin::ResolveSimpleJoin(ExecutionContext &context, Da } } +template +static idx_t TemplatedMergeJoinRightSemiBoundary(PiecewiseMergeJoinState &lstate, const idx_t rhs_end, + const bool strict) { + using SORT_KEY = SortKey; + using BLOCK_ITERATOR = block_iterator_t; + + // the first sorted probe key matches every build row that a later one matches + const auto &lhs_val = lstate.lhs_iterator->template GetValueAtIndex(idx_t(0), idx_t(0)); + + // only the keys are searched: keep them pinned for the search, but not the payload + auto &rhs_iterator = *lstate.rhs_iterator; + rhs_iterator.SetKeepPinned(true); + rhs_iterator.SetPinPayload(false); + const BLOCK_ITERATOR rhs_begin(rhs_iterator, idx_t(0)); + const BLOCK_ITERATOR rhs_end_itr(rhs_iterator, rhs_end); + const auto boundary = std::partition_point( + rhs_begin, rhs_end_itr, [&](const SORT_KEY &rhs_val) { return !MergeJoinBefore(lhs_val, rhs_val, strict); }); + return NumericCast(boundary - rhs_begin); +} + +static idx_t MergeJoinRightSemiBoundary(PiecewiseMergeJoinState &lstate, const idx_t rhs_end, + const ExpressionType comparison) { + const auto strict = MergeJoinStrictComparison(comparison); + + switch (lstate.sort_key_type) { +#define DUCKDB_SORT_KEY_CASE(SORT_KEY_TYPE) \ + case SortKeyType::SORT_KEY_TYPE: \ + return TemplatedMergeJoinRightSemiBoundary(lstate, rhs_end, strict); + DUCKDB_FOR_EACH_SORT_KEY_TYPE(DUCKDB_SORT_KEY_CASE) +#undef DUCKDB_SORT_KEY_CASE + default: + throw NotImplementedException("MergeJoinRightSemiBoundary for %s", EnumUtil::ToString(lstate.sort_key_type)); + } +} + +void PhysicalPiecewiseMergeJoin::ResolveRightSemiJoin(ExecutionContext &context, DataChunk &input, + OperatorState &state_p) const { + auto &state = state_p.Cast(); + auto &gstate = sink_state->Cast(); + + // the build rows from the boundary on match already; the ones before it are searched + auto boundary = gstate.right_semi_boundary.load(); + if (boundary == 0) { + return; + } + if (!state.rhs_iterator) { + // the state was reset for reuse (a recursive CTE runs its pipelines once per iteration) + state.InitializeRightScanState(gstate); + } + state.ResolveJoinKeys(context, input); + auto &lhs_table = *state.lhs_global_table; + if (lhs_table.count == lhs_table.has_null) { + return; + } + + const auto new_boundary = MergeJoinRightSemiBoundary(state, boundary, conditions[0].GetComparisonType()); + while (new_boundary < boundary && !gstate.right_semi_boundary.compare_exchange_weak(boundary, new_boundary)) { + } +} + struct ChunkMergeInfo { //! The iteration state ExternalBlockIteratorState &state; @@ -692,22 +770,18 @@ OperatorResultType PhysicalPiecewiseMergeJoin::ResolveComplexJoin(ExecutionConte state.rhs_executor.SetChunk(state.rhs_input); state.rhs_keys.Reset(); - auto tail_count = result_count; - for (size_t cmp_idx = 1; cmp_idx < conditions.size(); ++cmp_idx) { - Vector left(Vector::Ref(state.lhs_local_table->keys.data[cmp_idx])); - left.Slice(left_info.lhs, result_count); + auto &tail_keys = state.tail_keys; + for (idx_t cmp_idx = 1; cmp_idx < conditions.size(); ++cmp_idx) { + tail_keys.data[cmp_idx - 1].Slice(state.lhs_local_table->keys.data[cmp_idx], left_info.lhs, + result_count); auto &right = state.rhs_keys.data[cmp_idx]; state.rhs_executor.ExecuteExpression(cmp_idx, right); - - if (tail_count < result_count) { - left.Slice(*sel, tail_count); - right.Slice(*sel, tail_count); - } - tail_count = SelectJoinTail(conditions[cmp_idx].GetComparisonType(), left, right, sel, tail_count, - &state.sel); - sel = &state.sel; + tail_keys.data[tail_cols + cmp_idx - 1].Reference(right); } + tail_keys.CheckCardinality(result_count); + const auto tail_count = state.tail_executor.SelectExpression(tail_keys, state.sel); + sel = &state.sel; if (tail_count < result_count) { result_count = tail_count; @@ -771,6 +845,10 @@ OperatorResultType PhysicalPiecewiseMergeJoin::ExecuteInternal(ExecutionContext // simple joins can have max STANDARD_VECTOR_SIZE matches per chunk ResolveSimpleJoin(context, input, chunk, state); return OperatorResultType::NEED_MORE_INPUT; + case JoinType::RIGHT_SEMI: + // the source phase emits the matching build rows + ResolveRightSemiJoin(context, input, state); + return OperatorResultType::NEED_MORE_INPUT; case JoinType::LEFT: case JoinType::INNER: case JoinType::RIGHT: @@ -855,13 +933,41 @@ SourceResultType PhysicalPiecewiseMergeJoin::GetDataInternal(ExecutionContext &c return SourceResultType::FINISHED; } - // if the LHS is exhausted in a FULL/RIGHT OUTER JOIN, we scan the found_match for any chunks we - // still need to output - const auto found_match = gsink.table->found_match.get(); - auto &lsource = source.local_state.Cast(); auto &rhs_chunk = lsource.rhs_chunk; auto &rsel = lsource.rsel; + if (join_type == JoinType::RIGHT_SEMI) { + // the payload is in sort order: the matching rows run from the boundary up to the NULL tail + const auto boundary = gsink.right_semi_boundary.load(); + const auto not_null = gsink.table->count - gsink.table->has_null; + for (;;) { + rhs_chunk.Reset(); + const auto rhs_pos = gsource.Scan(lsource.scanner, rhs_chunk); + const auto count = rhs_chunk.size(); + if (count == 0) { + return SourceResultType::FINISHED; + } + gsource.rows_scanned.fetch_add(count, std::memory_order_relaxed); + const auto begin = MaxValue(boundary, rhs_pos); + const auto end = MinValue(not_null, rhs_pos + count); + if (begin >= end) { + continue; + } + if (end - begin == count) { + result.Reference(rhs_chunk); + } else { + for (idx_t i = begin; i < end; i++) { + rsel.set_index(i - begin, i - rhs_pos); + } + result.Slice(rhs_chunk, rsel, end - begin); + } + return SourceResultType::HAVE_MORE_OUTPUT; + } + } + + // if the LHS is exhausted in a FULL/RIGHT OUTER JOIN, we scan the found_match for any chunks we + // still need to output + const auto found_match = gsink.table->found_match.get(); for (;;) { // Read the next sorted chunk rhs_chunk.Reset(); diff --git a/src/duckdb/src/execution/operator/join/physical_range_join.cpp b/src/duckdb/src/execution/operator/join/physical_range_join.cpp index 26426f4ed..d0315fd4b 100644 --- a/src/duckdb/src/execution/operator/join/physical_range_join.cpp +++ b/src/duckdb/src/execution/operator/join/physical_range_join.cpp @@ -11,6 +11,8 @@ #include "duckdb/parallel/base_pipeline_event.hpp" #include "duckdb/parallel/thread_context.hpp" #include "duckdb/parallel/executor_task.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" namespace duckdb { @@ -518,30 +520,32 @@ void PhysicalRangeJoin::SliceSortedPayload(DataChunk &chunk, GlobalSortedTable & } } -idx_t PhysicalRangeJoin::SelectJoinTail(const ExpressionType &condition, const Vector &left, const Vector &right, - const SelectionVector *sel, idx_t count, SelectionVector *true_sel) { - switch (condition) { - case ExpressionType::COMPARE_NOTEQUAL: - return VectorOperations::NotEquals(left, right, sel, count, true_sel, nullptr); - case ExpressionType::COMPARE_LESSTHAN: - return VectorOperations::LessThan(left, right, sel, count, true_sel, nullptr); - case ExpressionType::COMPARE_GREATERTHAN: - return VectorOperations::GreaterThan(left, right, sel, count, true_sel, nullptr); - case ExpressionType::COMPARE_LESSTHANOREQUALTO: - return VectorOperations::LessThanEquals(left, right, sel, count, true_sel, nullptr); - case ExpressionType::COMPARE_GREATERTHANOREQUALTO: - return VectorOperations::GreaterThanEquals(left, right, sel, count, true_sel, nullptr); - case ExpressionType::COMPARE_DISTINCT_FROM: - return VectorOperations::DistinctFrom(left, right, sel, count, true_sel, nullptr); - case ExpressionType::COMPARE_NOT_DISTINCT_FROM: - return VectorOperations::NotDistinctFrom(left, right, sel, count, true_sel, nullptr); - case ExpressionType::COMPARE_EQUAL: - return VectorOperations::Equals(left, right, sel, count, true_sel, nullptr); - default: - throw InternalException("Unsupported comparison type for PhysicalRangeJoin"); +unique_ptr PhysicalRangeJoin::CreateTailPredicate(ClientContext &context, + const vector &conditions, + idx_t tail_begin) { + if (tail_begin >= conditions.size()) { + return nullptr; + } + const auto tail_count = conditions.size() - tail_begin; + vector> comparisons; + for (idx_t tail_idx = 0; tail_idx < tail_count; tail_idx++) { + auto &condition = conditions[tail_begin + tail_idx]; + comparisons.push_back(BoundComparisonExpression::CreateOnColumns( + context, condition.GetComparisonType(), condition.GetLHS().GetReturnType(), tail_idx, + condition.GetRHS().GetReturnType(), tail_count + tail_idx)); } + return BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_AND, std::move(comparisons)); +} - return count; +vector PhysicalRangeJoin::GetTailTypes(const vector &conditions, idx_t tail_begin) { + vector result; + for (idx_t cond_idx = tail_begin; cond_idx < conditions.size(); cond_idx++) { + result.push_back(conditions[cond_idx].GetLHS().GetReturnType()); + } + for (idx_t cond_idx = tail_begin; cond_idx < conditions.size(); cond_idx++) { + result.push_back(conditions[cond_idx].GetRHS().GetReturnType()); + } + return result; } } // namespace duckdb diff --git a/src/duckdb/src/execution/operator/order/physical_top_n.cpp b/src/duckdb/src/execution/operator/order/physical_top_n.cpp index f44778518..b96808dc2 100644 --- a/src/duckdb/src/execution/operator/order/physical_top_n.cpp +++ b/src/duckdb/src/execution/operator/order/physical_top_n.cpp @@ -1,4 +1,5 @@ #include "duckdb/execution/operator/order/physical_top_n.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/common/atomic.hpp" #include "duckdb/common/assert.hpp" @@ -12,11 +13,17 @@ namespace duckdb { -PhysicalTopN::PhysicalTopN(PhysicalPlan &physical_plan, vector types, vector orders, - idx_t limit, idx_t offset, shared_ptr dynamic_filter_p, - idx_t estimated_cardinality) +PhysicalTopN::PhysicalTopN(PhysicalPlan &physical_plan, ClientContext &context, vector types, + vector orders, idx_t limit, idx_t offset, + shared_ptr dynamic_filter_p, idx_t estimated_cardinality) : PhysicalOperator(physical_plan, PhysicalOperatorType::TOP_N, std::move(types), estimated_cardinality), orders(std::move(orders)), limit(limit), offset(offset), dynamic_filter(std::move(dynamic_filter_p)) { + const auto order_count = this->orders.size(); + for (idx_t order_idx = 0; order_idx < order_count; order_idx++) { + auto &type = this->orders[order_idx].expression->GetReturnType(); + not_distinct_from.push_back(BoundComparisonExpression::CreateOnColumns( + context, ExpressionType::COMPARE_NOT_DISTINCT_FROM, type, order_idx, type, order_count + order_idx)); + } } PhysicalTopN::~PhysicalTopN() { @@ -85,11 +92,13 @@ struct TopNBoundaryValue { class TopNHeap { public: TopNHeap(ClientContext &context, const vector &payload_types, const vector &orders, - idx_t limit, idx_t offset); + const vector> ¬_distinct_from, idx_t limit, idx_t offset); TopNHeap(ExecutionContext &context, const vector &payload_types, - const vector &orders, idx_t limit, idx_t offset); + const vector &orders, const vector> ¬_distinct_from, + idx_t limit, idx_t offset); TopNHeap(ClientContext &context, Allocator &allocator, const vector &payload_types, - const vector &orders, idx_t limit, idx_t offset); + const vector &orders, const vector> ¬_distinct_from, + idx_t limit, idx_t offset); Allocator &allocator; BufferManager &buffer_manager; @@ -102,10 +111,13 @@ class TopNHeap { idx_t offset; idx_t heap_size; ExpressionExecutor executor; + //! NOT DISTINCT FROM comparison of every sort column + vector> not_distinct_from; DataChunk sort_chunk; DataChunk heap_data; DataChunk payload_chunk; DataChunk sort_keys; + CreateSortKeyState sort_key_state; StringHeap sort_key_heap; SelectionVector matching_sel; @@ -113,6 +125,8 @@ class TopNHeap { DataChunk compare_chunk; //! Cached global boundary value as a set of constant vectors DataChunk boundary_values; + //! The input of not_distinct_from: [sort columns..., boundary values...] + DataChunk boundary_compare_chunk; //! Cached global boundary value in sort-key format string boundary_val; SelectionVector final_sel; @@ -176,7 +190,8 @@ class TopNHeap { // TopNHeap //===--------------------------------------------------------------------===// TopNHeap::TopNHeap(ClientContext &context, Allocator &allocator, const vector &payload_types_p, - const vector &orders_p, idx_t limit, idx_t offset) + const vector &orders_p, const vector> ¬_distinct_from_p, + idx_t limit, idx_t offset) : allocator(allocator), buffer_manager(BufferManager::GetBufferManager(context)), arena_allocator(allocator), heap(arena_allocator), payload_types(payload_types_p), orders(orders_p), limit(limit), offset(offset), heap_size(limit + offset), executor(context), sort_key_heap(allocator), matching_sel(STANDARD_VECTOR_SIZE), @@ -188,6 +203,8 @@ TopNHeap::TopNHeap(ClientContext &context, Allocator &allocator, const vectorGetReturnType()); executor.AddExpression(*expr); + not_distinct_from.push_back( + make_uniq(executor.GetContext(), *not_distinct_from_p[not_distinct_from.size()])); modifiers.emplace_back(order.type, order.null_order); } heap.reserve(InitialHeapAllocSize()); @@ -198,16 +215,22 @@ TopNHeap::TopNHeap(ClientContext &context, Allocator &allocator, const vector &payload_types, - const vector &orders, idx_t limit, idx_t offset) - : TopNHeap(context, BufferAllocator::Get(context), payload_types, orders, limit, offset) { + const vector &orders, const vector> ¬_distinct_from, + idx_t limit, idx_t offset) + : TopNHeap(context, BufferAllocator::Get(context), payload_types, orders, not_distinct_from, limit, offset) { } TopNHeap::TopNHeap(ExecutionContext &context, const vector &payload_types, - const vector &orders, idx_t limit, idx_t offset) - : TopNHeap(context.client, BufferAllocator::Get(context.client), payload_types, orders, limit, offset) { + const vector &orders, const vector> ¬_distinct_from, + idx_t limit, idx_t offset) + : TopNHeap(context.client, BufferAllocator::Get(context.client), payload_types, orders, not_distinct_from, limit, + offset) { } void TopNHeap::AddSmallHeap(DataChunk &input, const Vector &sort_keys_vec) { @@ -293,6 +316,11 @@ bool TopNHeap::CheckBoundaryValues(DataChunk &sort_chunk, DataChunk &payload, To } } boundary_values.SetChildCardinality(sort_chunk.size()); + for (idx_t i = 0; i < orders.size(); i++) { + boundary_compare_chunk.data[i].Reference(sort_chunk.data[i]); + boundary_compare_chunk.data[orders.size() + i].Reference(boundary_values.data[i]); + } + boundary_compare_chunk.CheckCardinality(sort_chunk.size()); // we have boundary values // from these boundary values, determine which values we should insert (if any) @@ -337,9 +365,8 @@ bool TopNHeap::CheckBoundaryValues(DataChunk &sort_chunk, DataChunk &payload, To idx_t false_count = remaining_count - true_count; if (!is_last && false_count > 0) { // check what we should continue to check - compare_chunk.data[i].Slice(sort_chunk.data[i], false_sel, false_count); - remaining_count = VectorOperations::NotDistinctFrom(compare_chunk.data[i], boundary_values.data[i], - &false_sel, false_count, &new_remaining_sel, nullptr); + remaining_count = not_distinct_from[i]->SelectExpression(boundary_compare_chunk, &new_remaining_sel, + nullptr, &false_sel, false_count); remaining_sel.Initialize(new_remaining_sel); } else { break; @@ -378,7 +405,7 @@ void TopNHeap::Sink(DataChunk &input, optional_ptr global_bou // construct the sort key from the sort chunk sort_keys.Reset(); auto &sort_keys_vec = sort_keys.data[0]; - CreateSortKeyHelpers::CreateSortKey(sort_chunk, modifiers, sort_keys_vec); + CreateSortKeyHelpers::CreateSortKey(sort_chunk, modifiers, sort_keys_vec, sort_key_state); if (heap_size <= SMALL_HEAP_THRESHOLD) { AddSmallHeap(input, sort_keys_vec); @@ -486,7 +513,7 @@ void TopNHeap::Scan(TopNScanState &state, DataChunk &chunk, idx_t &pos) { class TopNGlobalSinkState : public GlobalSinkState { public: TopNGlobalSinkState(ClientContext &context, const PhysicalTopN &op) - : heap(context, op.types, op.orders, op.limit, op.offset), boundary_value(op) { + : heap(context, op.types, op.orders, op.not_distinct_from, op.limit, op.offset), boundary_value(op) { } mutex lock; @@ -497,15 +524,16 @@ class TopNGlobalSinkState : public GlobalSinkState { class TopNLocalSinkState : public LocalSinkState { public: TopNLocalSinkState(ExecutionContext &context, const vector &payload_types, - const vector &orders, idx_t limit, idx_t offset) - : heap(context, payload_types, orders, limit, offset) { + const vector &orders, const vector> ¬_distinct_from, + idx_t limit, idx_t offset) + : heap(context, payload_types, orders, not_distinct_from, limit, offset) { } TopNHeap heap; }; unique_ptr PhysicalTopN::GetLocalSinkState(ExecutionContext &context) const { - return make_uniq(context, types, orders, limit, offset); + return make_uniq(context, types, orders, not_distinct_from, limit, offset); } unique_ptr PhysicalTopN::GetGlobalSinkState(ClientContext &context) const { diff --git a/src/duckdb/src/execution/operator/persistent/csv_rejects_table.cpp b/src/duckdb/src/execution/operator/persistent/csv_rejects_table.cpp index 5a89081f9..9a5d27375 100644 --- a/src/duckdb/src/execution/operator/persistent/csv_rejects_table.cpp +++ b/src/duckdb/src/execution/operator/persistent/csv_rejects_table.cpp @@ -59,26 +59,24 @@ shared_ptr CSVRejectsTable::GetOrCreate(ClientContext &context, return cache.GetOrCreate(key, rejects_scan, rejects_error); } -idx_t CSVRejectsTable::GetFileIndexBase(idx_t query_id, const void *scan_key, idx_t file_count) { +idx_t CSVRejectsTable::GetFileIndex(idx_t query_id, optional_ptr scan_op, idx_t file_index) { const lock_guard lock(file_index_lock); if (file_index_query_id != query_id) { // the file indexes are unique within a query file_index_query_id = query_id; next_file_index = 0; - scan_file_index_base.clear(); + scan_file_indexes.clear(); } - if (!scan_key) { + if (!scan_op) { // we cannot tell which scan this file belongs to - give it an index of its own return next_file_index++; } - auto entry = scan_file_index_base.find(scan_key); - if (entry != scan_file_index_base.end()) { - return entry->second; + auto &file_indexes = scan_file_indexes[*scan_op]; + // Earlier files may still be running, so reserve their indexes before assigning this one. + while (file_indexes.size() <= file_index) { + file_indexes.push_back(next_file_index++); } - const idx_t base = next_file_index; - next_file_index += MaxValue(file_count, 1); - scan_file_index_base.emplace(scan_key, base); - return base; + return file_indexes[file_index]; } void CSVRejectsTable::InitializeTable(ClientContext &context, const ReadCSVData &data) { diff --git a/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp b/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp index d8971bddf..1237645c2 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp @@ -33,7 +33,7 @@ struct ActiveFlushGuard { }; PhysicalBatchCopyToFile::PhysicalBatchCopyToFile(PhysicalPlan &physical_plan, vector types, - CopyFunction function_p, unique_ptr bind_data_p, + CopyFunction function_p, cow_ptr bind_data_p, idx_t estimated_cardinality) : PhysicalOperator(physical_plan, PhysicalOperatorType::BATCH_COPY_TO_FILE, std::move(types), estimated_cardinality), @@ -101,8 +101,20 @@ class FixedBatchCopyGlobalState : public GlobalSinkState { atomic initialized {false}; //! The total number of rows copied to the file atomic rows_copied; - //! Global copy state + //! Global copy state of the file being written unique_ptr global_state; + //! The state every batch is prepared against: the first file's, which rotation keeps open until the end + atomic> prepare_state {nullptr}; + //! The first file's state once rotation has moved past it + unique_ptr first_file_state; + //! Path of the file being written + string current_file_path; + //! Batches flushed to the file being written + idx_t current_file_batches = 0; + //! Files opened so far + idx_t file_count = 0; + //! Files a rotating copy has written, in order (for RETURN_FILES and RETURN_STATS) + vector> rotated_files; //! Unpartitioned batches map> raw_batches; //! The prepared batch data by batch index - ready to flush @@ -128,21 +140,42 @@ class FixedBatchCopyGlobalState : public GlobalSinkState { if (initialized.load(std::memory_order_relaxed)) { return; } - output_lifecycle.RegisterFile(op.file_path); - auto new_global_state = op.function.copy_to_initialize_global(context, *op.bind_data, op.file_path); + OpenFile(context, op); + prepare_state.store(*global_state, std::memory_order_release); + initialized.store(true, std::memory_order_release); + } + + //! Opens the output file, or the next file of a rotating copy + void OpenFile(ClientContext &context, const PhysicalBatchCopyToFile &op) { + auto path = op.file_path; + if (op.Rotate()) { + auto &fs = FileSystem::GetFileSystem(context); + path = op.filename_pattern.CreateFilename(fs, op.file_path, op.file_extension, file_count); + } + output_lifecycle.RegisterFile(path); + auto new_global_state = op.function.copy_to_initialize_global(context, *op.bind_data, path); if (op.function.initialize_operator) { op.function.initialize_operator(*new_global_state, op); } unique_ptr new_written_file_info; + if (op.Rotate() || + GetCopyFunctionBaseReturnType(op.return_type) == CopyFunctionReturnType::WRITTEN_FILE_STATISTICS) { + new_written_file_info = make_uniq(path); + } if (GetCopyFunctionBaseReturnType(op.return_type) == CopyFunctionReturnType::WRITTEN_FILE_STATISTICS) { - new_written_file_info = make_uniq(op.file_path); new_written_file_info->file_stats = make_uniq(); op.function.copy_to_get_written_statistics(context, *op.bind_data, *new_global_state, *new_written_file_info->file_stats); } global_state = std::move(new_global_state); - written_file_info = std::move(new_written_file_info); - initialized.store(true, std::memory_order_release); + if (op.Rotate()) { + rotated_files.push_back(std::move(new_written_file_info)); + } else { + written_file_info = std::move(new_written_file_info); + } + current_file_path = std::move(path); + current_file_batches = 0; + file_count++; } void AddBatchData(idx_t batch_index, unique_ptr new_batch, idx_t memory_usage, @@ -347,6 +380,14 @@ SinkFinalizeType PhysicalBatchCopyToFile::FinalFlush(ClientContext &context, Glo PhysicalCopyToFile::MoveTmpFile(context, file_path); } } + if (gstate.first_file_state) { + // nothing is prepared anymore + gstate.prepare_state.store(nullptr, std::memory_order_release); + if (function.copy_to_finalize) { + function.copy_to_finalize(context, *bind_data, *gstate.first_file_state); + } + gstate.first_file_state.reset(); + } gstate.output_lifecycle.MarkSuccessful(); return SinkFinalizeType::READY; } @@ -397,7 +438,8 @@ class PrepareBatchTask : public BatchCopyTask { auto memory_usage = batch_data->memory_usage; const CopyFunctionBatchAnalyzer batch_analyzer(*batch_data->collection, op.batch_size, op.batch_size_bytes); auto prepared_batch = - op.function.prepare_batch(context, *op.bind_data, *gstate.global_state, std::move(batch_data->collection)); + op.function.prepare_batch(context, *op.bind_data, *gstate.prepare_state.load(std::memory_order_acquire), + std::move(batch_data->collection)); gstate.AddBatchData(batch_index, std::move(prepared_batch), memory_usage, batch_analyzer); if (batch_index == gstate.flushed_batch_index) { gstate.task_manager.AddTask(make_uniq()); @@ -422,6 +464,10 @@ void PhysicalBatchCopyToFile::AddRawBatchData(ClientContext &context, GlobalSink static bool CorrectSizeForBatch(const ColumnDataCollection &batch, const optional_idx &batch_size, const optional_idx &batch_size_bytes) { + if (!batch_size.IsValid()) { + // no row target (only ROW_GROUP_SIZE_BYTES): the byte target alone decides + return CopyFunctionBatchAnalyzer(batch, batch_size, batch_size_bytes).IsAcceptable(); + } if (batch_size.GetIndex() == 0) { // a batch size of 0 indicates we are happy with any batch size return true; @@ -598,18 +644,46 @@ void PhysicalBatchCopyToFile::FlushBatchData(ClientContext &context, GlobalSinkS batch_data = std::move(entry->second); gstate.batch_data.erase(entry); } + RotateFile(context, gstate_p); DUCKDB_LOG(context, PhysicalOperatorLogType, *this, "PhysicalBatchCopyToFile", "FlushBatch", - {{"file", file_path}, + {{"file", gstate.current_file_path}, {"rows", to_string(batch_data->batch_analyzer.current_batch_size)}, {"size", to_string(batch_data->batch_analyzer.current_batch_size_bytes)}, {"reason", EnumUtil::ToString(batch_data->batch_analyzer.ToReason())}}); function.flush_batch(context, *bind_data, *gstate.global_state, *batch_data->prepared_data); + gstate.current_file_batches++; batch_data->prepared_data.reset(); memory_manager.ReduceUnflushedMemory(batch_data->memory_usage); gstate.flushed_batch_index++; } } +void PhysicalBatchCopyToFile::RotateFile(ClientContext &context, GlobalSinkState &gstate_p) const { + auto &gstate = gstate_p.Cast(); + if (!Rotate() || gstate.current_file_batches == 0) { + // never rotate a file that holds no data yet + return; + } + const bool size_reached = file_size_bytes.IsValid() && function.file_size_bytes && + function.file_size_bytes(*gstate.global_state) >= file_size_bytes.GetIndex(); + const bool batches_reached = + batches_per_file.IsValid() && gstate.current_file_batches >= batches_per_file.GetIndex(); + if (!size_reached && !batches_reached) { + return; + } + // only the flushing thread gets here, and prepares do not use global_state + if (gstate.file_count == 1) { + // batches are still prepared against the first file's state: finalize it last + gstate.first_file_state = std::move(gstate.global_state); + } else { + if (function.copy_to_finalize) { + function.copy_to_finalize(context, *bind_data, *gstate.global_state); + } + gstate.global_state.reset(); + } + gstate.OpenFile(context, *this); +} + //===--------------------------------------------------------------------===// // Tasks //===--------------------------------------------------------------------===// @@ -697,6 +771,10 @@ unique_ptr PhysicalBatchCopyToFile::GetGlobalSinkState(ClientCo auto minimum_memory_per_thread = FixedBatchCopyGlobalState::MINIMUM_MEMORY_PER_COLUMN_PER_THREAD * children[0].get().GetTypes().size(); auto result = make_uniq(context, minimum_memory_per_thread); + if (Rotate()) { + D_ASSERT(!use_tmp_file); + PhysicalCopyToFile::PrepareOutputDirectory(context, file_path, overwrite_mode, result->output_lifecycle); + } if (write_empty_file) { // if we are writing the file also if it is empty - initialize now result->Initialize(context, *this); @@ -707,11 +785,70 @@ unique_ptr PhysicalBatchCopyToFile::GetGlobalSinkState(ClientCo //===--------------------------------------------------------------------===// // Source //===--------------------------------------------------------------------===// +class BatchCopyGlobalSourceState : public GlobalSourceState { +public: + idx_t offset = 0; + + idx_t MaxThreads() override { + return 1; + } +}; + +unique_ptr PhysicalBatchCopyToFile::GetGlobalSourceState(ClientContext &context) const { + return make_uniq(); +} + +SourceResultType PhysicalBatchCopyToFile::GetRotatedFiles(ExecutionContext &context, DataChunk &chunk, + OperatorSourceInput &input) const { + auto &g = sink_state->Cast(); + auto &files = g.rotated_files; + auto return_column_types = CopyFunctionReturnsColumnTypes(return_type); + switch (GetCopyFunctionBaseReturnType(return_type)) { + case CopyFunctionReturnType::CHANGED_ROWS: + chunk.data[0].Append(Value::BIGINT(NumericCast(g.rows_copied.load()))); + break; + case CopyFunctionReturnType::CHANGED_ROWS_AND_FILE_LIST: { + vector file_list; + for (auto &file : files) { + file_list.emplace_back(file->file_path); + } + chunk.data[0].Append(Value::BIGINT(NumericCast(g.rows_copied.load()))); + chunk.data[1].Append(Value::LIST(LogicalType::VARCHAR, std::move(file_list))); + break; + } + case CopyFunctionReturnType::WRITTEN_FILE_STATISTICS: { + auto &source_state = input.global_state.Cast(); + const auto next_end = MinValue(source_state.offset + STANDARD_VECTOR_SIZE, files.size()); + for (idx_t file_idx = source_state.offset; file_idx < next_end; file_idx++) { + PhysicalCopyToFile::ReturnStatistics(context.client.GetContext(), chunk, *files[file_idx]); + } + if (return_column_types) { + if (files.empty()) { + // WRITE_EMPTY_FILE false writes no file without rows + PhysicalCopyToFile::ReturnNoFileStatistics(chunk); + } + PhysicalCopyToFile::ReturnColumnTypes(chunk, query_names, query_types); + } + source_state.offset = next_end; + return next_end < files.size() ? SourceResultType::HAVE_MORE_OUTPUT : SourceResultType::FINISHED; + } + default: + throw NotImplementedException("Unknown CopyFunctionReturnType"); + } + if (return_column_types) { + PhysicalCopyToFile::ReturnColumnTypes(chunk, query_names, query_types); + } + return SourceResultType::FINISHED; +} + SourceResultType PhysicalBatchCopyToFile::GetDataInternal(ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input) const { auto &g = sink_state->Cast(); auto fp = use_tmp_file ? PhysicalCopyToFile::GetNonTmpFile(context.client, file_path) : file_path; auto return_column_types = CopyFunctionReturnsColumnTypes(return_type); + if (Rotate()) { + return GetRotatedFiles(context, chunk, input); + } switch (GetCopyFunctionBaseReturnType(return_type)) { case CopyFunctionReturnType::CHANGED_ROWS: chunk.data[0].Append(Value::BIGINT(NumericCast(g.rows_copied.load()))); diff --git a/src/duckdb/src/execution/operator/persistent/physical_batch_insert.cpp b/src/duckdb/src/execution/operator/persistent/physical_batch_insert.cpp index 19057fd8f..bbb4ac1e5 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_batch_insert.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_batch_insert.cpp @@ -116,9 +116,10 @@ class BatchInsertLocalState : public LocalSinkState { void CreateNewCollection(ClientContext &context, DuckTableEntry &table_entry, const vector &insert_types) { if (!optimistic_writer) { - optimistic_writer = make_uniq(context, table_entry.GetStorage()); + optimistic_writer = make_uniq(table_entry.GetStorage()); } - auto collection = optimistic_writer->CreateCollection(table_entry.GetStorage(), insert_types); + auto collection = + optimistic_writer->CreateCollection(context.GetContext(), table_entry.GetStorage(), insert_types); auto &row_collection = *collection->collection; row_collection.InitializeEmpty(); row_collection.InitializeAppend(current_append_state); @@ -147,7 +148,7 @@ class MergeCollectionTask : public BatchInsertTask { // Merge the collections. if (!l_state.optimistic_writer) { - l_state.optimistic_writer = make_uniq(context, g_state.table.GetStorage()); + l_state.optimistic_writer = make_uniq(g_state.table.GetStorage()); } auto result_collection_index = g_state.MergeCollections(context, merge_collections, *l_state.optimistic_writer); merge_collections.clear(); @@ -301,7 +302,7 @@ void BatchInsertGlobalState::AddCollection(ClientContext &context, const idx_t b auto new_count = collection.GetTotalRows(); auto batch_type = new_count < row_group_size ? RowGroupBatchType::NOT_FLUSHED : RowGroupBatchType::FLUSHED; if (batch_type == RowGroupBatchType::FLUSHED && writer) { - writer->WriteUnflushedRowGroups(optimistic_collection); + writer->WriteUnflushedRowGroups(context.GetContext(), optimistic_collection); } annotated_lock_guard l(lock); insert_count += new_count; @@ -482,7 +483,8 @@ SinkResultType PhysicalBatchInsert::Sink(ExecutionContext &context, DataChunk &i auto flushed_row_group_idx = collection.Append(insert_chunk, lstate.current_append_state); if (flushed_row_group_idx.IsValid()) { // we have already written to disk - flush the next row group as well - lstate.optimistic_writer->WriteNewRowGroup(optimistic_collection, flushed_row_group_idx.GetIndex()); + lstate.optimistic_writer->WriteNewRowGroup(context.client.GetContext(), optimistic_collection, + flushed_row_group_idx.GetIndex()); } return SinkResultType::NEED_MORE_INPUT; } @@ -515,7 +517,7 @@ SinkCombineResultType PhysicalBatchInsert::Combine(ExecutionContext &context, Op if (lstate.optimistic_writer) { annotated_lock_guard l(gstate.lock); auto &optimistic_writer = gstate.table.GetStorage().GetOptimisticWriter(context.client); - optimistic_writer.Merge(*lstate.optimistic_writer); + optimistic_writer.Merge(context.client.GetContext(), *lstate.optimistic_writer); } // unblock any blocked tasks @@ -572,7 +574,7 @@ SinkFinalizeType PhysicalBatchInsert::Finalize(Pipeline &pipeline, Event &event, // now that we have created all of the mergers, perform the actual merging vector final_collections; final_collections.reserve(mergers.size()); - auto writer = make_uniq(context, data_table); + auto writer = make_uniq(data_table); for (auto &merger : mergers) { final_collections.push_back(merger->Flush(*writer)); } @@ -585,8 +587,8 @@ SinkFinalizeType PhysicalBatchInsert::Finalize(Pipeline &pipeline, Event &event, } auto &optimistic_writer = data_table.GetOptimisticWriter(context); - optimistic_writer.Merge(*writer); - optimistic_writer.FinalFlush(); + optimistic_writer.Merge(context.GetContext(), *writer); + optimistic_writer.FinalFlush(context.GetContext()); memory_manager.FinalCheck(); return SinkFinalizeType::READY; } diff --git a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp index 3cda66bdb..ec9b58c5b 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp @@ -1,3 +1,4 @@ +#include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/execution/operator/persistent/physical_copy_to_file.hpp" #include "duckdb/common/file_opener.hpp" @@ -1779,8 +1780,8 @@ CreateColumnStatistics(const case_insensitive_map_t state) { +static void FinalizeLifecycleFileState(ClientContext &context, copy_to_finalize_t finalize, + const FunctionData &bind_data, unique_ptr state) { if (!finalize) { throw InternalException("COPY file lifecycle finalize requires a finalize callback"); } @@ -1792,7 +1793,7 @@ static void FinalizeLifecycleFileState(ClientContext &context, copy_to_finalize_ void CopyFileLifecycleExecutor::WaitForJob(CopyFileLifecycleJob &job, CopyFileLifecycleWaitMode mode) { while (!job.IsFinished()) { if (mode == CopyFileLifecycleWaitMode::INTERRUPTIBLE) { - context.InterruptCheck(); + context.FastInterruptCheck(); } WorkOnTaskOrYield(); } @@ -1806,7 +1807,7 @@ void CopyFileLifecycleExecutor::WaitAll(CopyFileLifecycleWaitMode mode) { return; } while (pending_tasks.load(std::memory_order_acquire) > 0) { - context.InterruptCheck(); + context.FastInterruptCheck(); WorkOnTaskOrYield(); } ThrowError(); @@ -1855,7 +1856,7 @@ void CopyFileLifecycleExecutor::WorkOnTaskOrYield() { void CopyFileLifecycleExecutor::WaitForTaskSlot(CopyFileLifecycleWaitMode mode) { while (pending_tasks >= max_pending_tasks) { if (mode == CopyFileLifecycleWaitMode::INTERRUPTIBLE) { - context.InterruptCheck(); + context.FastInterruptCheck(); } if (async_threads == 0 || mode == CopyFileLifecycleWaitMode::DRAIN) { WorkOnTaskOrYield(); @@ -2159,7 +2160,8 @@ class SortStrategyInputLocalState : public PartitionedCopyInputLocalState { class SortStrategyInput : public PartitionedCopyInput { public: - SortStrategyInput(const PartitionedCopy &partitioned_copy, unique_ptr strategy); + SortStrategyInput(ClientContext &context, const PartitionedCopy &partitioned_copy, + unique_ptr strategy); public: unique_ptr GetGlobalState(ClientContext &context) const override; @@ -2182,6 +2184,8 @@ class SortStrategyInput : public PartitionedCopyInput { public: const PartitionedCopy &partitioned_copy; const unique_ptr strategy; + //! DISTINCT FROM comparison of the partition columns + unique_ptr partition_distinct_from; }; //! A hash bin of a SortStrategyInput (or all bins of an overflow sort): sorted, materialized and masked for partition @@ -2259,7 +2263,7 @@ class SortedBinGroup : public PartitionedCopyGroup { private: void TakeMaterializedBins(ExecutionContext &context, OperatorSourceInput &source_input); - void Mask(idx_t begin_block, idx_t end_block); + void Mask(Context &context, idx_t begin_block, idx_t end_block); void PartitionBoundaries(idx_t row_begin, idx_t chunk_rows, vector &boundaries) const; //! The chunk holding a row idx_t ChunkOf(idx_t row) const; @@ -2281,9 +2285,17 @@ class SortedBinGroup : public PartitionedCopyGroup { ValidityMask partition_mask; }; -SortStrategyInput::SortStrategyInput(const PartitionedCopy &partitioned_copy_p, +SortStrategyInput::SortStrategyInput(ClientContext &context, const PartitionedCopy &partitioned_copy_p, unique_ptr strategy_p) : partitioned_copy(partitioned_copy_p), strategy(std::move(strategy_p)) { + auto &op = partitioned_copy.op; + vector key_types; + for (auto partition_column : op.partition_columns) { + key_types.push_back(op.expected_types[partition_column]); + } + auto key_type = WindowCollectionChunkScanner::PrefixStructType(key_types, key_types.size()); + partition_distinct_from = BoundComparisonExpression::CreateOnColumns(context, ExpressionType::COMPARE_DISTINCT_FROM, + key_type, 0, key_type, 1); } unique_ptr SortStrategyInput::GetGlobalState(ClientContext &context) const { @@ -2412,7 +2424,7 @@ void SortedBinGroup::ExecutePreparation(ExecutionContext &context, InterruptStat break; } case MASK: - Mask(begin_block, end_block); + Mask(context.client.GetContext(), begin_block, end_block); break; default: throw InternalException("Invalid SortedBinGroup preparation step"); @@ -2464,7 +2476,7 @@ idx_t SortedBinGroup::ChunkOf(idx_t row) const { return NumericCast(entry - chunk_row_offsets.begin()) - 1; } -void SortedBinGroup::Mask(idx_t begin_block, idx_t end_block) { +void SortedBinGroup::Mask(Context &context, idx_t begin_block, idx_t end_block) { D_ASSERT(collection); D_ASSERT(partition_mask.IsMaskSet()); @@ -2493,7 +2505,8 @@ void SortedBinGroup::Mask(idx_t begin_block, idx_t end_block) { auto &scan_cols = input.strategy->sort_ids; const auto chunk_begin = ChunkOf(owned_begin); const auto chunk_end = ChunkOf(owned_end - 1) + 1; - WindowDeltaScanner(*collection, chunk_begin, chunk_end, scan_cols, key_count, + WindowDeltaScanner(context, *input.partition_distinct_from, *collection, chunk_begin, chunk_end, scan_cols, + key_count, [&](const idx_t row_idx, DataChunk &, DataChunk &, const idx_t ndistinct, const SelectionVector &distinct, const SelectionVector &) { for (idx_t i = 0; i < ndistinct; i++) { @@ -2799,7 +2812,7 @@ unique_ptr IntegerPartitionInput::CreateOverflowInput(ClientC OperatorPartitionInfo unpartitioned_info; auto strategy = SortStrategy::Factory(context, partition_bys, op.order_columns, op.expected_types, no_stats, unpartitioned_info, count); - return make_uniq(partitioned_copy, std::move(strategy)); + return make_uniq(context, partitioned_copy, std::move(strategy)); } unique_ptr IntegerPartitionInput::GetGlobalState(ClientContext &context) const { @@ -3737,7 +3750,7 @@ unique_ptr PartitionedCopy::ConstructInput() const { auto strategy = SortStrategy::Factory(context, partition_bys, op.order_columns, op.expected_types, op.partition_stats, unpartitioned_info, op.children.empty() ? 0 : op.children[0].get().estimated_cardinality); - return make_uniq(*this, std::move(strategy)); + return make_uniq(context, *this, std::move(strategy)); } bool PartitionedCopy::RequiresSerializedPartitionWrites() const { @@ -3794,7 +3807,7 @@ void PartitionedCopy::NotifyFlushProgress() { template bool PartitionedCopy::TryBlockOnFlush(ExecutionContext &execution_context, InterruptState &interrupt_state, idx_t observed_progress, FUNC &&can_continue) { - context.InterruptCheck(); + context.FastInterruptCheck(); Flush(execution_context, interrupt_state); if (!interrupt_state.CanCallback()) { copy_gstate.lifecycle_executor.WorkOnTaskOrYield(); @@ -3934,7 +3947,7 @@ class PartitionedCopyFinalizeTask : public ExecutorTask { event->Cast().pipeline); InterruptState interrupt_state(shared_from_this()); while (partitioned_copy.flushing.load(std::memory_order_relaxed) || partitioned_copy.HasDelayedPartitions()) { - event->GetClientContext().InterruptCheck(); + event->GetClientContext().FastInterruptCheck(); if (partitioned_copy.flushing.load(std::memory_order_relaxed)) { partitioned_copy.Flush(execution_context, interrupt_state); } else { @@ -4511,31 +4524,37 @@ void CopyToFileGlobalState::Initialize() { initialized = true; } -void CopyToFileGlobalState::PrepareOutputDirectory() { +void PhysicalCopyToFile::PrepareOutputDirectory(ClientContext &context, const string &directory, + CopyOverwriteMode overwrite_mode, + CopyOutputLifecycle &output_lifecycle) { auto &fs = FileSystem::GetFileSystem(context); - if (!fs.IsRemoteFile(op.file_path)) { - if (fs.FileExists(op.file_path)) { - if (op.overwrite_mode == CopyOverwriteMode::COPY_OVERWRITE) { - fs.RemoveFile(op.file_path); + if (!fs.IsRemoteFile(directory)) { + if (fs.FileExists(directory)) { + if (overwrite_mode == CopyOverwriteMode::COPY_OVERWRITE) { + fs.RemoveFile(directory); } else { throw IOException("Cannot write to \"%s\" - it exists and is a file, not a directory! Enable " "OVERWRITE option to overwrite the file", - op.file_path); + directory); } } } - if (!fs.DirectoryExists(op.file_path)) { - if (fs.CreateDirectoryExtended(op.file_path, {CreateDirectoryMode::SINGLE})) { - output_lifecycle.RegisterCreatedDirectory(op.file_path); + if (!fs.DirectoryExists(directory)) { + if (fs.CreateDirectoryExtended(directory, {CreateDirectoryMode::SINGLE})) { + output_lifecycle.RegisterCreatedDirectory(directory); } else { - CheckDirectory(fs, op.file_path, op.overwrite_mode); + CheckDirectory(fs, directory, overwrite_mode); } } else { - CheckDirectory(fs, op.file_path, op.overwrite_mode); + CheckDirectory(fs, directory, overwrite_mode); } } +void CopyToFileGlobalState::PrepareOutputDirectory() { + PhysicalCopyToFile::PrepareOutputDirectory(context, op.file_path, op.overwrite_mode, output_lifecycle); +} + void CopyToFileGlobalState::ScheduleOutputDirectorySetup() { D_ASSERT(!output_directory_job); output_directory_job = make_shared_ptr(); @@ -4829,7 +4848,7 @@ CopyToFileLocalState::CopyToFileLocalState(const PhysicalCopyToFile &op_p, Execu // PhysicalCopyToFile //===--------------------------------------------------------------------===// PhysicalCopyToFile::PhysicalCopyToFile(PhysicalPlan &physical_plan, vector types, CopyFunction function_p, - unique_ptr bind_data, idx_t estimated_cardinality) + cow_ptr bind_data, idx_t estimated_cardinality) : PhysicalOperator(physical_plan, PhysicalOperatorType::COPY_TO_FILE, std::move(types), estimated_cardinality), function(std::move(function_p)), bind_data(std::move(bind_data)), parallel(false) { } @@ -5171,7 +5190,7 @@ static unique_ptr PrepareLegacyCopyBatch(unique_ptr(std::move(batch)); } -static void FlushLegacyCopyBatch(ClientContext &context, const CopyFunction &function, FunctionData &bind_data, +static void FlushLegacyCopyBatch(ClientContext &context, const CopyFunction &function, const FunctionData &bind_data, GlobalFunctionData &gstate, PreparedBatchData &prepared_batch) { if (!function.copy_to_initialize_local || !function.copy_to_sink || !function.copy_to_combine) { throw InternalException("Legacy copy function is missing required sink/combine callbacks"); diff --git a/src/duckdb/src/execution/operator/persistent/physical_insert.cpp b/src/duckdb/src/execution/operator/persistent/physical_insert.cpp index d26102722..7fc9c09c7 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_insert.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_insert.cpp @@ -286,7 +286,7 @@ static idx_t PerformOnConflictAction(InsertLocalState &lstate, InsertGlobalState data_table.Delete(delete_state, context.client, table, row_ids, update_chunk.size()); } else { auto &local_storage = LocalStorage::Get(context.client, data_table.db); - local_storage.Delete(data_table, table, row_ids, update_chunk.size()); + local_storage.Delete(context.client.GetContext(), data_table, table, row_ids, update_chunk.size()); } if (!op.parallel && op.return_chunk) { @@ -416,7 +416,7 @@ static void VerifyOnConflictCondition(ExecutionContext &context, DataChunk &comb throw InternalException("VerifyAppendConstraints was expected to throw but didn't"); } - auto &indexes = local_storage.GetIndexes(data_table); + auto &indexes = local_storage.GetIndexes(context.client.GetContext(), data_table); auto storage = local_storage.GetStorage(data_table); indexes.VerifyUniqueIndexes(storage ? &storage->delete_indexes : nullptr, tuples, nullptr); throw InternalException("VerifyUniqueIndexes was expected to throw but didn't"); @@ -439,7 +439,7 @@ static idx_t HandleInsertConflicts(DuckTableEntry &table, ExecutionContext &cont auto &constraint_state = lstate.GetConstraintState(data_table, table); data_table.VerifyAppendConstraints(constraint_state, context.client, tuples, storage, &conflict_manager); } else { - auto &indexes = local_storage.GetIndexes(data_table); + auto &indexes = local_storage.GetIndexes(context.client.GetContext(), data_table); indexes.VerifyUniqueIndexes(storage ? &storage->delete_indexes : nullptr, tuples, &conflict_manager); } @@ -530,7 +530,7 @@ idx_t PhysicalInsert::OnConflictHandling(DuckTableEntry &table, ExecutionContext // We care about every index that applies to the table if no ON CONFLICT (...) target is given matching_index_columns = global_indexes.GetConflictTargetColumns(conflict_info); - const auto &local_indexes = local_storage.GetIndexes(data_table); + const auto &local_indexes = local_storage.GetIndexes(context.client.GetContext(), data_table); auto local_index_columns = local_indexes.GetConflictTargetColumns(conflict_info); for (auto &column_set : local_index_columns) { matching_index_columns.push_back(std::move(column_set)); @@ -630,9 +630,10 @@ SinkResultType PhysicalInsert::Sink(ExecutionContext &context, DataChunk &insert auto &data_table = gstate.table.GetStorage(); if (!lstate.collection_index.IsValid()) { lock_guard l(gstate.lock); - lstate.optimistic_writer = make_uniq(context.client, data_table); + lstate.optimistic_writer = make_uniq(data_table); // Create the local row group collection. - auto optimistic_collection = lstate.optimistic_writer->CreateCollection(storage, insert_types); + auto optimistic_collection = + lstate.optimistic_writer->CreateCollection(context.client.GetContext(), storage, insert_types); auto &collection = *optimistic_collection->collection; collection.InitializeEmpty(); collection.InitializeAppend(lstate.local_append_state); @@ -648,7 +649,8 @@ SinkResultType PhysicalInsert::Sink(ExecutionContext &context, DataChunk &insert auto &collection = *optimistic_collection.collection; auto flushed_row_group_idx = collection.Append(insert_chunk, lstate.local_append_state); if (flushed_row_group_idx.IsValid()) { - lstate.optimistic_writer->WriteNewRowGroup(optimistic_collection, flushed_row_group_idx.GetIndex()); + lstate.optimistic_writer->WriteNewRowGroup(context.client.GetContext(), optimistic_collection, + flushed_row_group_idx.GetIndex()); } return SinkResultType::NEED_MORE_INPUT; } @@ -680,8 +682,8 @@ SinkCombineResultType PhysicalInsert::Combine(ExecutionContext &context, Operato if (append_count >= row_group_size) { // flush thread-local optimistic data - lstate.optimistic_writer->WriteUnflushedRowGroups(optimistic_collection); - lstate.optimistic_writer->FinalFlush(); + lstate.optimistic_writer->WriteUnflushedRowGroups(context.client.GetContext(), optimistic_collection); + lstate.optimistic_writer->FinalFlush(context.client.GetContext()); } lock_guard lock(gstate.lock); @@ -693,7 +695,7 @@ SinkCombineResultType PhysicalInsert::Combine(ExecutionContext &context, Operato // we have written rows to disk optimistically - merge directly into the transaction-local storage gstate.table.GetStorage().LocalMerge(context.client, gstate.table, optimistic_collection); auto &optimistic_writer = gstate.table.GetStorage().GetOptimisticWriter(context.client); - optimistic_writer.Merge(*lstate.optimistic_writer); + optimistic_writer.Merge(context.client.GetContext(), *lstate.optimistic_writer); } return SinkCombineResultType::FINISHED; @@ -735,7 +737,7 @@ class MergeCollectionsEvent : public BasePipelineEvent { auto &data_table = table.GetStorage(); vector> tasks; for (idx_t i = 0; i < mergers.size(); i++) { - writers.push_back(make_uniq(context, data_table)); + writers.push_back(make_uniq(data_table)); tasks.push_back(make_uniq(context, shared_from_this(), *mergers[i], *writers[i], merged_collections[i], op)); } @@ -750,9 +752,9 @@ class MergeCollectionsEvent : public BasePipelineEvent { auto &collection = data_table.GetOptimisticCollection(context, merged_collections[i]); data_table.LocalMerge(context, table, collection); data_table.ResetOptimisticCollection(context, merged_collections[i]); - optimistic_writer.Merge(*writers[i]); + optimistic_writer.Merge(context.GetContext(), *writers[i]); } - optimistic_writer.FinalFlush(); + optimistic_writer.FinalFlush(context.GetContext()); } private: diff --git a/src/duckdb/src/execution/operator/persistent/physical_update.cpp b/src/duckdb/src/execution/operator/persistent/physical_update.cpp index 165d985a5..67ee1afb8 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_update.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_update.cpp @@ -3,6 +3,9 @@ #include "duckdb/catalog/catalog_entry/duck_table_entry.hpp" #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/common/algorithm.hpp" +#include "duckdb/common/sorting/sort.hpp" +#include "duckdb/parallel/task_scheduler.hpp" +#include "duckdb/storage/buffer_manager.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/execution/expression_executor.hpp" @@ -57,17 +60,43 @@ PhysicalUpdate::PhysicalUpdate(PhysicalPlan &physical_plan, vector class UpdateGlobalState : public GlobalSinkState { public: explicit UpdateGlobalState(ClientContext &context, const vector &return_types, - bool update_is_del_and_insert) + bool update_is_del_and_insert, const vector> &expressions) : updated_count(0), return_collection(context, return_types) { if (update_is_del_and_insert) { updated_rows = make_uniq(context, vector {LogicalType::ROW_TYPE}); + return; } + // in-place updates are staged (followed by their row ids) and applied sorted by row id + for (auto &expr : expressions) { + staged_types.push_back(expr->GetReturnType()); + } + staged_types.push_back(LogicalType::ROW_TYPE); + vector orders; + orders.emplace_back(OrderType::ASCENDING, OrderByNullType::NULLS_LAST, + make_uniq(LogicalType::ROW_TYPE, staged_types.size() - 1)); + vector projection_map; + for (idx_t i = 0; i < staged_types.size(); i++) { + projection_map.push_back(i); + } + staged_sort = make_uniq(context, orders, staged_types, std::move(projection_map)); + // every thread stages at most an equal share of a fraction of the memory limit + auto max_memory = BufferManager::GetBufferManager(context).GetMaxMemory(); + auto threads = MaxValue(TaskScheduler::GetScheduler(context).NumberOfThreads(), 1); + staged_memory_budget = MinValue(max_memory / PhysicalUpdate::STAGED_UPDATE_MEMORY_FRACTION / threads, + PhysicalUpdate::STAGED_UPDATE_MAX_MEMORY); + staged_memory_budget = MaxValue(staged_memory_budget, PhysicalUpdate::STAGED_UPDATE_MIN_MEMORY); } mutex lock; atomic updated_count; unique_ptr updated_rows; ColumnDataCollection return_collection; + //! The types of the staged in-place updates: the updated columns followed by the row ids + vector staged_types; + //! Sorts the staged in-place updates of each thread by row id + unique_ptr staged_sort; + //! The memory a thread stages before it applies its staged updates + idx_t staged_memory_budget = 0; }; class UpdateLocalState : public LocalSinkState { @@ -136,6 +165,15 @@ class UpdateLocalState : public LocalSinkState { unique_ptr delete_state; unique_ptr update_state; const vector> &bound_constraints; + //! The sort of the in-place updates this thread staged since its last flush + unique_ptr staged_sort_gstate; + unique_ptr staged_sort_lstate; + idx_t staged_count = 0; + //! References the update chunk and its row ids, to sink them into the staged sort + DataChunk staging_input; + //! A chunk of the sorted staged updates and the references to its update columns + DataChunk sorted_chunk; + DataChunk sorted_updates; TableDeleteState &GetDeleteState(DataTable &table, TableCatalogEntry &tableref, ClientContext &context) { if (!delete_state) { @@ -210,8 +248,7 @@ SinkResultType PhysicalUpdate::Sink(ExecutionContext &context, DataChunk &chunk, } mock_chunk.CheckCardinality(update_chunk.size()); } - auto &update_state = l_state.GetUpdateState(table, tableref, context.client); - table.Update(update_state, context.client, tableref, row_ids, columns, update_chunk); + StageUpdates(context, g_state, l_state, update_chunk, row_ids, input.interrupt_state); if (return_chunk) { lock_guard glock(g_state.lock); @@ -295,7 +332,7 @@ SinkResultType PhysicalUpdate::Sink(ExecutionContext &context, DataChunk &chunk, } unique_ptr PhysicalUpdate::GetGlobalSinkState(ClientContext &context) const { - return make_uniq(context, GetTypes(), update_is_del_and_insert); + return make_uniq(context, GetTypes(), update_is_del_and_insert, expressions); } unique_ptr PhysicalUpdate::GetLocalSinkState(ExecutionContext &context) const { @@ -303,7 +340,119 @@ unique_ptr PhysicalUpdate::GetLocalSinkState(ExecutionContext &c bound_constraints, capture_old_rows, index_update); } +static bool RowIdsAreSorted(Vector &row_ids, idx_t count) { + auto ids = row_ids.Values(); + for (idx_t i = 1; i < count; i++) { + if (ids[i].GetValueUnsafe() < ids[i - 1].GetValueUnsafe()) { + return false; + } + } + return true; +} + +//! Keeps one entry per row id of a chunk sorted by row id. Updating a row id more than once in a single chunk would +//! let every column pick its value from a different entry; across chunks, every entry still overwrites the whole row. +static idx_t SelectLastPerRowId(Vector &row_ids, idx_t count, SelectionVector &sel) { + auto ids = row_ids.Values(); + idx_t kept = 0; + for (idx_t i = 0; i < count; i++) { + if (i + 1 == count || ids[i + 1].GetValueUnsafe() != ids[i].GetValueUnsafe()) { + sel.set_index(kept++, i); + } + } + return kept; +} + +void PhysicalUpdate::StageUpdates(ExecutionContext &context, GlobalSinkState &gstate, LocalSinkState &lstate, + DataChunk &updates, Vector &row_ids, InterruptState &interrupt_state) const { + auto &g_state = gstate.Cast(); + auto &l_state = lstate.Cast(); + if (l_state.staged_count == 0 && RowIdsAreSorted(row_ids, updates.size())) { + // already clustered (e.g. updates driven by a scan of the table) - staging would not help + auto &update_state = l_state.GetUpdateState(table, tableref, context.client); + table.Update(update_state, context.client, tableref, row_ids, columns, updates); + return; + } + auto &sort = *g_state.staged_sort; + if (!l_state.staged_sort_gstate) { + l_state.staged_sort_gstate = sort.GetGlobalSinkState(context.client); + l_state.staged_sort_lstate = sort.GetLocalSinkState(context); + } + auto &input = l_state.staging_input; + if (input.ColumnCount() == 0) { + input.InitializeEmpty(g_state.staged_types); + } + for (idx_t c = 0; c < updates.ColumnCount(); c++) { + input.data[c].Reference(updates.data[c]); + } + input.data.back().Reference(row_ids); + input.CheckCardinality(updates.size()); + OperatorSinkInput sink_input {*l_state.staged_sort_gstate, *l_state.staged_sort_lstate, interrupt_state}; + sort.Sink(context, input, sink_input); + l_state.staged_count += updates.size(); + // a completed run leaves the local state, so flush then too: staged runs would otherwise pile up until Combine + if (sort.GetSortedCount(*l_state.staged_sort_gstate) > 0 || + sort.GetLocalSizeInBytes(*l_state.staged_sort_lstate) >= g_state.staged_memory_budget) { + FlushStagedUpdates(context, gstate, lstate, interrupt_state); + } +} + +void PhysicalUpdate::FlushStagedUpdates(ExecutionContext &context, GlobalSinkState &gstate, LocalSinkState &lstate, + InterruptState &interrupt_state) const { + auto &g_state = gstate.Cast(); + auto &l_state = lstate.Cast(); + if (l_state.staged_count == 0) { + return; + } + // sort by row id, so that every update chunk touches as few vectors of the table as possible + auto &sort = *g_state.staged_sort; + auto &sort_gstate = *l_state.staged_sort_gstate; + OperatorSinkCombineInput combine_input {sort_gstate, *l_state.staged_sort_lstate, interrupt_state}; + sort.Combine(context, combine_input); + OperatorSinkFinalizeInput finalize_input {sort_gstate, interrupt_state}; + sort.Finalize(context.client, finalize_input); + auto source_gstate = sort.GetGlobalSourceState(context.client, sort_gstate); + auto source_lstate = sort.GetLocalSourceState(context, *source_gstate); + OperatorSourceInput source_input {*source_gstate, *source_lstate, interrupt_state}; + + auto &sorted_chunk = l_state.sorted_chunk; + auto &sorted_updates = l_state.sorted_updates; + if (sorted_chunk.ColumnCount() == 0) { + sorted_chunk.Initialize(context.client, g_state.staged_types); + vector update_types(g_state.staged_types.begin(), g_state.staged_types.end() - 1); + sorted_updates.InitializeEmpty(update_types); + } + auto &update_state = l_state.GetUpdateState(table, tableref, context.client); + SelectionVector unique_sel(STANDARD_VECTOR_SIZE); + while (true) { + context.client.InterruptCheck(); + sorted_chunk.Reset(); + auto result = sort.GetData(context, sorted_chunk, source_input); + if (result == SourceResultType::BLOCKED) { + throw InternalException("Sorting the staged updates of an UPDATE unexpectedly blocked"); + } + if (sorted_chunk.size() > 0) { + auto unique_count = SelectLastPerRowId(sorted_chunk.data.back(), sorted_chunk.size(), unique_sel); + if (unique_count < sorted_chunk.size()) { + sorted_chunk.Slice(unique_sel, unique_count); + } + for (idx_t c = 0; c < sorted_updates.ColumnCount(); c++) { + sorted_updates.data[c].Reference(sorted_chunk.data[c]); + } + sorted_updates.CheckCardinality(sorted_chunk.size()); + table.Update(update_state, context.client, tableref, sorted_chunk.data.back(), columns, sorted_updates); + } + if (result == SourceResultType::FINISHED) { + break; + } + } + l_state.staged_sort_lstate.reset(); + l_state.staged_sort_gstate.reset(); + l_state.staged_count = 0; +} + SinkCombineResultType PhysicalUpdate::Combine(ExecutionContext &context, OperatorSinkCombineInput &input) const { + FlushStagedUpdates(context, input.global_state, input.local_state, input.interrupt_state); auto &client_profiler = QueryProfiler::Get(context.client); context.thread.profiler.Flush(*this); client_profiler.Flush(context.thread.profiler); diff --git a/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp b/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp index 6d096a0b8..bd24bb842 100644 --- a/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp +++ b/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp @@ -33,8 +33,7 @@ class TableInOutGlobalState : public GlobalOperatorState { }; PhysicalTableInOutFunction::PhysicalTableInOutFunction(PhysicalPlan &physical_plan, vector types, - BoundTableFunction function_p, - unique_ptr bind_data_p, + BoundTableFunction function_p, cow_ptr bind_data_p, vector column_ids_p, vector projection_ids_p, unique_ptr table_filters_p, idx_t estimated_cardinality, vector project_input_p) diff --git a/src/duckdb/src/execution/operator/scan/physical_table_scan.cpp b/src/duckdb/src/execution/operator/scan/physical_table_scan.cpp index bd11adf13..2ae0bfd0d 100644 --- a/src/duckdb/src/execution/operator/scan/physical_table_scan.cpp +++ b/src/duckdb/src/execution/operator/scan/physical_table_scan.cpp @@ -17,7 +17,7 @@ namespace duckdb { PhysicalTableScan::PhysicalTableScan(PhysicalPlan &physical_plan, vector types, - BoundTableFunction function_p, unique_ptr bind_data_p, + BoundTableFunction function_p, cow_ptr bind_data_p, vector returned_types_p, vector column_ids_p, vector projection_ids_p, vector names_p, unique_ptr table_filters_p, idx_t estimated_cardinality, @@ -88,6 +88,10 @@ class TableScanLocalSourceState : public LocalSourceState { if (op.function.init_local) { TableFunctionInitInput input(op.bind_data.get(), op.column_ids, op.projection_ids, gstate.GetTableFilters(op), op.extra_info.sample_options, &op); + if (context.pipeline && context.pipeline->GetSource().get() == &op && context.pipeline->GetSink()) { + input.execution_order = context.pipeline->GetExecutionOrder(); + input.max_threads = context.pipeline->GetMaxThreads(); + } local_state = op.function.init_local(context, input, gstate.global_state.get()); } } diff --git a/src/duckdb/src/execution/operator/schema/physical_attach.cpp b/src/duckdb/src/execution/operator/schema/physical_attach.cpp index 7ddc9ed93..bd1242e11 100644 --- a/src/duckdb/src/execution/operator/schema/physical_attach.cpp +++ b/src/duckdb/src/execution/operator/schema/physical_attach.cpp @@ -131,10 +131,14 @@ SourceResultType PhysicalAttach::GetDataInternal(ExecutionContext &context, Data // check ATTACH IF NOT EXISTS auto &db_manager = DatabaseManager::Get(context.client); - auto existing_db = db_manager.GetDatabase(name); + // compare by oid: a held reference would keep a database replaced by OR REPLACE from being closed + idx_t existing_oid = DConstants::INVALID_INDEX; + if (auto existing_db = db_manager.GetDatabase(name)) { + existing_oid = existing_db->oid; + } attached_db = db_manager.AttachDatabase(context.client, *attach_info, options); // IF NOT EXISTS / OR REPLACE can return the existing attachment without opening the path - if (attached_db == existing_db) { + if (attached_db->oid == existing_oid) { warn_ducklake_metadata = false; } } catch (...) { diff --git a/src/duckdb/src/execution/operator/schema/physical_create_index.cpp b/src/duckdb/src/execution/operator/schema/physical_create_index.cpp index ba00a76ae..2cf929850 100644 --- a/src/duckdb/src/execution/operator/schema/physical_create_index.cpp +++ b/src/duckdb/src/execution/operator/schema/physical_create_index.cpp @@ -175,7 +175,7 @@ SinkFinalizeType PhysicalCreateIndex::Finalize(Pipeline &pipeline, Event &event, if (info->constraint_type == IndexConstraintType::PRIMARY) { for (const auto &column_id : storage_ids) { BoundNotNullConstraint not_null {PhysicalIndex(column_id)}; - local_storage.VerifyNewConstraint(storage, not_null); + local_storage.VerifyNewConstraint(context.GetContext(), storage, not_null); } } auto &constraint_info = alter_table_info->Cast(); diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_delta.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_delta.cpp index 6939f4309..5955a9360 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_delta.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_delta.cpp @@ -96,16 +96,14 @@ RecursiveCTEKeyDeltaState::RecursiveCTEKeyDeltaState(ClientContext &context, con changed_rows.Initialize(Allocator::Get(context), op.GetTypes()); previous_scan_rows.Initialize(Allocator::Get(context), GetPreviousStateTypes(op, address_only_previous)); key_scan_rows.Initialize(Allocator::Get(context), op.hash_key_types); + for (auto &comparison : op.payload_distinct_from) { + payload_distinct_from.push_back(make_uniq(context, *comparison)); + } vector comparison_types; comparison_types.reserve(op.payload_types.size() * 2); comparison_types.insert(comparison_types.end(), op.payload_types.begin(), op.payload_types.end()); comparison_types.insert(comparison_types.end(), op.payload_types.begin(), op.payload_types.end()); - for (auto &comparison : op.payload_comparisons) { - if (comparison) { - comparison_rows.InitializeEmpty(comparison_types); - break; - } - } + comparison_rows.InitializeEmpty(comparison_types); } void RecursiveCTEKeyDeltaState::Reset() { @@ -133,25 +131,29 @@ void RecursiveCTEKeyDeltaState::PrepareCollections() { collections_initialized = true; } -static idx_t SelectDistinctPayloadRows(const Vector &previous, const Vector ¤t, - optional_ptr candidates, idx_t candidate_count, - SelectionVector &changed, SelectionVector &unchanged) { - if (!candidates) { - return VectorOperations::DistinctFrom(previous, current, nullptr, candidate_count, &changed, &unchanged); - } - Vector previous_candidates(previous, *candidates, candidate_count); - Vector current_candidates(current, *candidates, candidate_count); - return VectorOperations::DistinctFrom(previous_candidates, current_candidates, candidates.get(), candidate_count, - &changed, &unchanged); +//! References [previous payloads..., current payloads...] in the comparison rows; the current payloads are either +//! all result columns (at op.payload_idx) or only the payload columns +static DataChunk &ReferenceComparisonRows(RecursiveCTEKeyDeltaState &delta, const PhysicalRecursiveCTE &op, + DataChunk &previous, idx_t previous_payload_offset, DataChunk ¤t, + bool current_is_result, idx_t count) { + auto &comparison_rows = delta.comparison_rows; + const auto payload_count = op.payload_idx.size(); + for (idx_t payload_idx = 0; payload_idx < payload_count; payload_idx++) { + comparison_rows.data[payload_idx].Reference(previous.data[previous_payload_offset + payload_idx]); + const auto current_idx = current_is_result ? op.payload_idx[payload_idx] : payload_idx; + comparison_rows.data[payload_count + payload_idx].Reference(current.data[current_idx]); + } + comparison_rows.CheckCardinality(count); + return comparison_rows; } //! Whether the finalized payload of every row equals the candidate payload that produced it static bool FinalizedPayloadsEqualCandidates(RecursiveCTEKeyDeltaState &delta, const PhysicalRecursiveCTE &op, DataChunk &finalized, DataChunk &candidates, idx_t count) { + auto &comparison_rows = ReferenceComparisonRows(delta, op, finalized, 0, candidates, true, count); for (idx_t payload_idx = 0; payload_idx < op.payload_idx.size(); payload_idx++) { - const auto mismatch_count = - VectorOperations::DistinctFrom(finalized.data[payload_idx], candidates.data[op.payload_idx[payload_idx]], - nullptr, count, &delta.changed_column_groups, &delta.equal_groups_a); + const auto mismatch_count = delta.payload_distinct_from[payload_idx]->SelectExpression( + comparison_rows, &delta.changed_column_groups, &delta.equal_groups_a, nullptr, count); if (mismatch_count != 0) { return false; } @@ -164,14 +166,15 @@ static bool FinalizedPayloadsEqualCandidates(RecursiveCTEKeyDeltaState &delta, c static idx_t CountChangedPayloadRows(RecursiveCTEKeyDeltaState &delta, const PhysicalRecursiveCTE &op, DataChunk &previous, idx_t previous_payload_offset, DataChunk ¤t, idx_t count) { + auto &comparison_rows = + ReferenceComparisonRows(delta, op, previous, previous_payload_offset, current, false, count); idx_t changed_count = 0; idx_t equal_count = count; optional_ptr equal_groups; for (idx_t payload_idx = 0; payload_idx < op.payload_idx.size() && equal_count > 0; payload_idx++) { auto &next_equal_groups = payload_idx % 2 == 0 ? delta.equal_groups_a : delta.equal_groups_b; - const auto changed_column_count = - SelectDistinctPayloadRows(previous.data[previous_payload_offset + payload_idx], current.data[payload_idx], - equal_groups, equal_count, delta.changed_column_groups, next_equal_groups); + const auto changed_column_count = delta.payload_distinct_from[payload_idx]->SelectExpression( + comparison_rows, delta.changed_column_groups, next_equal_groups, equal_groups.get(), equal_count); changed_count += changed_column_count; equal_count -= changed_column_count; equal_groups = &next_equal_groups; @@ -508,32 +511,18 @@ idx_t RecursiveCTEKeyedState::FinalizeUsingKeyDelta(bool update_partial_indexes, delta.aggregate_rows, delta.result_rows); auto &previous_payloads = read_old_from_rows ? delta.updated_aggregate_rows : delta.previous_scan_rows; const idx_t previous_payload_offset = read_old_from_rows ? 0 : 1; - if (op.keyed.has_payload_comparisons) { - delta.comparison_rows.Reset(); - for (idx_t payload_idx = 0; payload_idx < op.payload_idx.size(); payload_idx++) { - delta.comparison_rows.data[payload_idx].Reference( - previous_payloads.data[previous_payload_offset + payload_idx]); - delta.comparison_rows.data[op.payload_idx.size() + payload_idx].Reference( - delta.result_rows.data[op.payload_idx[payload_idx]]); - } - delta.comparison_rows.CheckCardinality(row_count); - } + auto &comparison_rows = ReferenceComparisonRows(delta, op, previous_payloads, previous_payload_offset, + delta.result_rows, true, row_count); idx_t changed_count = 0; idx_t equal_count = row_count; optional_ptr equal_groups; for (idx_t payload_idx = 0; payload_idx < op.payload_idx.size() && equal_count > 0; payload_idx++) { auto &next_equal_groups = payload_idx % 2 == 0 ? delta.equal_groups_a : delta.equal_groups_b; - idx_t changed_column_count; - if (payload_comparison_executors[payload_idx]) { - changed_column_count = payload_comparison_executors[payload_idx]->SelectExpression( - delta.comparison_rows, delta.changed_column_groups, next_equal_groups, equal_groups, equal_count); - } else { - changed_column_count = - SelectDistinctPayloadRows(previous_payloads.data[previous_payload_offset + payload_idx], - delta.result_rows.data[op.payload_idx[payload_idx]], equal_groups, - equal_count, delta.changed_column_groups, next_equal_groups); - } + auto &comparison = payload_comparison_executors[payload_idx] ? *payload_comparison_executors[payload_idx] + : *delta.payload_distinct_from[payload_idx]; + const auto changed_column_count = comparison.SelectExpression( + comparison_rows, delta.changed_column_groups, next_equal_groups, equal_groups.get(), equal_count); for (idx_t changed_idx = 0; changed_idx < changed_column_count; changed_idx++) { delta.changed_groups.set_index(changed_count++, delta.changed_column_groups.get_index_unsafe(changed_idx)); diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp index 676506c81..6d1a60964 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp @@ -244,7 +244,7 @@ void RecursiveCTEUnionState::PromoteDistinctState(ClientContext &context, idx_t AggregateHTScanState scan_state; ht->InitializeScan(scan_state); while (ht->Scan(scan_state, groups, payload)) { - context.InterruptCheck(); + context.FastInterruptCheck(); if (groups.size() > 0) { SinkDistinct(groups, migration_state, false, false); } diff --git a/src/duckdb/src/execution/perfect_aggregate_hashtable.cpp b/src/duckdb/src/execution/perfect_aggregate_hashtable.cpp index e309220c5..68fbc55f5 100644 --- a/src/duckdb/src/execution/perfect_aggregate_hashtable.cpp +++ b/src/duckdb/src/execution/perfect_aggregate_hashtable.cpp @@ -353,8 +353,10 @@ void PerfectAggregateHashTable::Scan(idx_t &scan_position, DataChunk &result) { ReconstructGroupVector(group_values, group_minima[i], required_bits[i], shift, entry_count, result.data[i]); } // then construct the payloads - RowOperationsState row_state(*aggregate_allocator); - RowOperations::FinalizeStates(row_state, *layout_ptr, addresses, result, grouping_columns); + if (!scan_row_state) { + scan_row_state = make_uniq(*aggregate_allocator); + } + RowOperations::FinalizeStates(*scan_row_state, *layout_ptr, addresses, result, grouping_columns); } void PerfectAggregateHashTable::Destroy() { diff --git a/src/duckdb/src/execution/perfect_hash_join_table.cpp b/src/duckdb/src/execution/perfect_hash_join_table.cpp index 80bb00886..f8d387741 100644 --- a/src/duckdb/src/execution/perfect_hash_join_table.cpp +++ b/src/duckdb/src/execution/perfect_hash_join_table.cpp @@ -1,3 +1,5 @@ +#include + #include "duckdb/execution/perfect_hash_join_table.hpp" #include "duckdb/common/array.hpp" @@ -11,6 +13,13 @@ PerfectHashJoinTable::~PerfectHashJoinTable() { void PerfectHashJoinTable::InitializeEntries(idx_t from, idx_t to) { memset(entries.get() + from * sizeof(uint64_t), 0, (to - from) * sizeof(uint64_t)); + if (track_matches) { + static_assert(sizeof(atomic) == sizeof(uint64_t), "Bitmap words must hold atomic flags"); + auto matches = GetMatchEntries(); + for (idx_t i = from; i < to; i++) { + new (&matches[i]) atomic(0); + } + } } void PerfectHashJoinTable::ConvertToDictionary(idx_t pointer_offset) { @@ -44,7 +53,8 @@ uhugeint_t KeyDistance(uhugeint_t max, uhugeint_t min) { template class TypedPerfectHashJoinTable : public PerfectHashJoinTable { public: - TypedPerfectHashJoinTable(Type type, bool nulls_equal) : PerfectHashJoinTable(type, nulls_equal) { + TypedPerfectHashJoinTable(Type type, bool nulls_equal, bool track_matches) + : PerfectHashJoinTable(type, nulls_equal, track_matches) { } void UpdateBounds(const Vector &keys) override { @@ -81,20 +91,33 @@ class TypedPerfectHashJoinTable : public PerfectHashJoinTable { } } - bool Initialize(Allocator &allocator, idx_t build_count, idx_t pointer_table_size) override { + idx_t EstimateSize(idx_t build_count, idx_t pointer_table_size) const override { if (range_too_large || build_count == 0) { - return false; + return 0; } // Reserve one additional slot for NULL, including an all-NULL build. - domain_size = has_bounds ? KeyDistance(max, min).lower + 1 : 0; - const auto slots = domain_size + 1; + const auto slots = has_bounds ? KeyDistance(max, min).lower + 2 : 1; const auto bytes = IsBitmap() ? ((slots + 63) / 64) * sizeof(uint64_t) : slots * sizeof(uint64_t); - const auto budget = IsBitmap() ? MinValue(MAX_BYTES / sizeof(uint64_t), build_count) * sizeof(uint64_t) - : MinValue(MAX_BYTES, pointer_table_size); - if (bytes > budget) { + const auto budget = IsBitmap() && !track_matches + ? MinValue(GetMaxBytes() / sizeof(uint64_t), build_count) * sizeof(uint64_t) + : MinValue(GetMaxBytes(), pointer_table_size); + if (bytes > budget / (track_matches ? 2 : 1)) { + return 0; + } + return bytes * (track_matches ? 2 : 1); + } + + bool Initialize(BufferAllocator &allocator, idx_t build_count, idx_t pointer_table_size) override { + const auto size = EstimateSize(build_count, pointer_table_size); + if (!size) { return false; } - entries = allocator.Allocate(bytes); + domain_size = has_bounds ? KeyDistance(max, min).lower + 1 : 0; + const auto bytes = size / (track_matches ? 2 : 1); + entries = allocator.AllocateHuge(bytes); + if (track_matches) { + match_entries = allocator.AllocateHuge(bytes); + } return true; } @@ -114,7 +137,7 @@ class TypedPerfectHashJoinTable : public PerfectHashJoinTable { const auto slot = valid ? GetIndex(Load(row + key_offset)) : domain_size; D_ASSERT(slot <= domain_size); if (IsBitmap()) { - const auto mask = uint64_t(1) << (slot % 64); + const auto mask = static_cast(1) << (slot % 64); if (parallel) { auto &word = atomic_directory[slot / 64]; if (!(word.load(std::memory_order_relaxed) & mask)) { @@ -166,23 +189,30 @@ class TypedPerfectHashJoinTable : public PerfectHashJoinTable { D_ASSERT(IsBitmap()); D_ASSERT(keys.size() <= STANDARD_VECTOR_SIZE); auto values = keys.Values(); + if (track_matches) { + return ProbeMembershipLoop(values, found_match); + } if (ShouldPrefetchMembership(values)) { return ProbeMembershipPrefetched(values, found_match); } - auto directory = GetEntries(); - idx_t match_count = 0; - for (idx_t i = 0; i < values.size(); i++) { - auto entry = values[i]; - bool found = false; - if (!entry.IsValid()) { - found = Contains(directory, domain_size); - } else if (InRange(entry.GetValue())) { - found = Contains(directory, GetIndex(entry.GetValue())); - } - found_match[i] = found; - match_count += found; + return ProbeMembershipLoop(values, found_match); + } + + idx_t SelectMatches(array_ptr rows, const TupleDataLayout &layout, idx_t &offset, + array_ptr result, bool matched) const override { + auto matches = GetMatchEntries(); + const auto key_offset = layout.GetOffsets()[0]; + idx_t count = 0; + while (offset < rows.size() && count < result.size()) { + const auto row = rows[offset++]; + const auto valid = TemplatedValidityMask(row, layout.ColumnCount()).RowIsValid(0); + const auto slot = valid ? GetIndex(Load(row + key_offset)) : domain_size; + const auto mask = static_cast(1) << (slot % 64); + const auto found = (matches[slot / 64].load(std::memory_order_relaxed) & mask) != 0; + result[count] = row; + count += found == matched; } - return match_count; + return count; } idx_t ProbeDictionary(const Vector &keys, SelectionVector &probe_sel, SelectionVector &build_sel) const override { @@ -207,6 +237,31 @@ class TypedPerfectHashJoinTable : public PerfectHashJoinTable { } private: + template + idx_t ProbeMembershipLoop(const VectorIterator &keys, unsafe_unique_array &found_match) const { + const auto directory = GetEntries(); + idx_t count = 0; + for (idx_t i = 0; i < keys.size(); i++) { + const auto entry = keys[i]; + if (entry.IsValid() && !InRange(entry.GetValue())) { + found_match[i] = false; + continue; + } + const auto slot = entry.IsValid() ? GetIndex(entry.GetValue()) : domain_size; + const auto found = Contains(directory, slot); + if (TRACK_MATCHES && found) { + const auto mask = static_cast(1) << (slot % 64); + auto &word = GetMatchEntries()[slot / 64]; + if (!(word.load(std::memory_order_relaxed) & mask)) { + word.fetch_or(mask, std::memory_order_relaxed); + } + } + found_match[i] = found; + count += found; + } + return count; + } + bool ShouldPrefetchMembership(const VectorIterator &keys) const { #if defined(__GNUC__) || defined(__clang__) if (keys.size() < PREFETCH_MIN_COUNT || EntryCount() * sizeof(uint64_t) <= PREFETCH_MIN_BYTES) { @@ -241,7 +296,7 @@ class TypedPerfectHashJoinTable : public PerfectHashJoinTable { } // Estimate distinct words after accounting for power-of-two spacing. D_ASSERT(word_variation != 0); - const auto word_stride = word_variation & (idx_t(0) - word_variation); + const auto word_stride = word_variation & (static_cast(0) - word_variation); return (max_word - min_word) / word_stride >= PREFETCH_MIN_BYTES / sizeof(uint64_t); #else return false; @@ -298,8 +353,9 @@ class TypedPerfectHashJoinTable : public PerfectHashJoinTable { } void CheckRange() { - const auto max_slots = IsBitmap() ? MAX_BYTES * 8 : MAX_BYTES / sizeof(uint64_t); - if (has_bounds && KeyDistance(max, min) >= uhugeint_t(max_slots - 1)) { + const auto max_slots = + IsBitmap() ? GetMaxBytes() * 8 / (track_matches ? 2 : 1) : GetMaxBytes() / sizeof(uint64_t); + if (has_bounds && KeyDistance(max, min) >= static_cast(max_slots - 1)) { range_too_large = true; } } @@ -314,14 +370,19 @@ class TypedPerfectHashJoinTable : public PerfectHashJoinTable { } static bool Contains(const array_ptr &directory, idx_t slot) { - return (directory[slot / 64] & (uint64_t(1) << (slot % 64))) != 0; + return (directory[slot / 64] & (static_cast(1) << (slot % 64))) != 0; } private: + idx_t GetMaxBytes() const { + return IsBitmap() ? MAX_BITMAP_BYTES : MAX_BYTES; + } + + static constexpr idx_t MAX_BITMAP_BYTES = 64ULL * 1024ULL * 1024ULL; static constexpr idx_t PREFETCH_MIN_BYTES = 1024ULL * 1024ULL; static constexpr idx_t PREFETCH_MIN_COUNT = 128; - static constexpr uint32_t MISS_BIT = uint32_t(1) << 31; - static_assert(MAX_BYTES * 8 < MISS_BIT, "Bitmap slots must leave the high bit available"); + static constexpr uint32_t MISS_BIT = static_cast(1) << 31; + static_assert(MAX_BITMAP_BYTES * 8 < MISS_BIT, "Bitmap slots must leave the high bit available"); T min {}; T max {}; @@ -330,28 +391,29 @@ class TypedPerfectHashJoinTable : public PerfectHashJoinTable { idx_t domain_size = 0; }; -unique_ptr PerfectHashJoinTable::Create(PhysicalType key_type, Type type, bool nulls_equal) { +unique_ptr PerfectHashJoinTable::Create(PhysicalType key_type, Type type, bool nulls_equal, + bool track_matches) { switch (key_type) { case PhysicalType::INT8: - return make_uniq>(type, nulls_equal); + return make_uniq>(type, nulls_equal, track_matches); case PhysicalType::INT16: - return make_uniq>(type, nulls_equal); + return make_uniq>(type, nulls_equal, track_matches); case PhysicalType::INT32: - return make_uniq>(type, nulls_equal); + return make_uniq>(type, nulls_equal, track_matches); case PhysicalType::INT64: - return make_uniq>(type, nulls_equal); + return make_uniq>(type, nulls_equal, track_matches); case PhysicalType::INT128: - return make_uniq>(type, nulls_equal); + return make_uniq>(type, nulls_equal, track_matches); case PhysicalType::UINT8: - return make_uniq>(type, nulls_equal); + return make_uniq>(type, nulls_equal, track_matches); case PhysicalType::UINT16: - return make_uniq>(type, nulls_equal); + return make_uniq>(type, nulls_equal, track_matches); case PhysicalType::UINT32: - return make_uniq>(type, nulls_equal); + return make_uniq>(type, nulls_equal, track_matches); case PhysicalType::UINT64: - return make_uniq>(type, nulls_equal); + return make_uniq>(type, nulls_equal, track_matches); case PhysicalType::UINT128: - return make_uniq>(type, nulls_equal); + return make_uniq>(type, nulls_equal, track_matches); default: return nullptr; } diff --git a/src/duckdb/src/execution/physical_operator.cpp b/src/duckdb/src/execution/physical_operator.cpp index 2cc863f73..702e97fad 100644 --- a/src/duckdb/src/execution/physical_operator.cpp +++ b/src/duckdb/src/execution/physical_operator.cpp @@ -226,17 +226,17 @@ OperatorCachingMode PhysicalOperator::SelectOperatorCachingMode(ExecutionContext return OperatorCachingMode::NONE; } else if (!context.pipeline->GetSink()) { return OperatorCachingMode::NONE; - } else { - auto partition_info = context.pipeline->GetSink()->RequiredPartitionInfo(); - if (partition_info.AnyRequired()) { - return OperatorCachingMode::PARTITIONED; - } } - if (context.pipeline->IsOrderDependent()) { + switch (context.pipeline->GetExecutionOrder()) { + case PipelineExecutionOrder::PARTITIONED: + return OperatorCachingMode::PARTITIONED; + case PipelineExecutionOrder::ORDERED: return OperatorCachingMode::ORDERED; + case PipelineExecutionOrder::UNORDERED: + return OperatorCachingMode::UNORDERED; + default: + throw InternalException("Unknown pipeline execution order"); } - - return OperatorCachingMode::UNORDERED; } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/execution/physical_plan/plan_any_join.cpp b/src/duckdb/src/execution/physical_plan/plan_any_join.cpp index 7193ad6c8..360ff7588 100644 --- a/src/duckdb/src/execution/physical_plan/plan_any_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_any_join.cpp @@ -11,9 +11,11 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalAnyJoin &op) { auto &left = CreatePlan(*op.children[0]); auto &right = CreatePlan(*op.children[1]); - // Create the blockwise NL join. - return Make(op, left, right, std::move(op.condition), op.join_type, - op.estimated_cardinality); + // Create the blockwise NL join, which emits full child layouts. + auto pruned = ExtractPrunedJoinProjection(op, left, right, true, true); + auto &join = + Make(op, left, right, std::move(op.condition), op.join_type, op.estimated_cardinality); + return RestorePrunedJoinProjection(op, join, std::move(pruned)); } } // namespace duckdb diff --git a/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp b/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp index 8227fea25..fb687d227 100644 --- a/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_asof_join.cpp @@ -268,8 +268,8 @@ optional_ptr PhysicalPlanGenerator::PlanAsOfLoopJoin(LogicalCo auto &window = Make(window_types, std::move(window_select), join_cardinality); window.children.emplace_back(probe); - auto &join = Make(join_op, build, window, std::move(join_op.conditions), join_op.join_type, - join_cardinality); + auto &join = Make(context, join_op, build, window, std::move(join_op.conditions), + join_op.join_type, join_cardinality); // Plan a projection of the compare column auto &comp_proj = Make(std::move(comp_types), std::move(comp_list), join_cardinality); @@ -472,7 +472,7 @@ optional_ptr PhysicalPlanGenerator::PlanAsOfInequalityJoin(Log auto window_types = right.GetTypes(); window_types.emplace_back(asof_type); - auto &window = Make(window_types, std::move(window_select), rhs_cardinality); + auto &window = Make(context, window_types, std::move(window_select), rhs_cardinality); window.children.emplace_back(right); // IEJoin(left, window, conditions || asof_comp ~op asof_end) @@ -498,7 +498,7 @@ optional_ptr PhysicalPlanGenerator::PlanAsOfInequalityJoin(Log JoinCondition asof_upper(std::move(left_expr), std::move(right_expr), comparison); op.conditions.emplace_back(std::move(asof_upper)); - return Make(op, left, window, std::move(op.conditions), op.join_type, lhs_cardinality); + return Make(context, op, left, window, std::move(op.conditions), op.join_type, lhs_cardinality); } } // namespace duckdb diff --git a/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp b/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp index ddc78c686..3372479d0 100644 --- a/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_comparison_join.cpp @@ -264,13 +264,13 @@ PhysicalOperator &PhysicalPlanGenerator::PlanComparisonJoin(LogicalComparisonJoi } if (can_iejoin) { - return Make(op, left, right, std::move(op.conditions), op.join_type, op.estimated_cardinality, - std::move(op.filter_pushdown)); + return Make(context, op, left, right, std::move(op.conditions), op.join_type, + op.estimated_cardinality, std::move(op.filter_pushdown)); } if (can_merge) { // range join: use piecewise merge join, which emits full child layouts auto pruned = ExtractPrunedJoinProjection(op, left, right, true, true); - auto &join = Make(op, left, right, std::move(op.conditions), op.join_type, + auto &join = Make(context, op, left, right, std::move(op.conditions), op.join_type, op.estimated_cardinality, std::move(op.filter_pushdown)); return RestorePrunedJoinProjection(op, join, std::move(pruned)); } @@ -278,7 +278,7 @@ PhysicalOperator &PhysicalPlanGenerator::PlanComparisonJoin(LogicalComparisonJoi // inequality join: use nested loop, which only applies the left map of a MARK join auto pruned = ExtractPrunedJoinProjection(op, left, right, op.join_type != JoinType::MARK, true); D_ASSERT(op.left_projection_map.empty() || op.join_type == JoinType::MARK); - auto &join = Make(op, left, right, std::move(op.conditions), op.join_type, + auto &join = Make(context, op, left, right, std::move(op.conditions), op.join_type, op.estimated_cardinality, std::move(op.filter_pushdown)); return RestorePrunedJoinProjection(op, join, std::move(pruned)); } @@ -312,7 +312,7 @@ static bool IsPruningMap(const vector &projection_map, idx_t in } PhysicalPlanGenerator::PrunedJoinProjection -PhysicalPlanGenerator::ExtractPrunedJoinProjection(LogicalComparisonJoin &op, const PhysicalOperator &left, +PhysicalPlanGenerator::ExtractPrunedJoinProjection(LogicalJoin &op, const PhysicalOperator &left, const PhysicalOperator &right, bool expand_left, bool expand_right) { PrunedJoinProjection info; const auto left_width = left.GetTypes().size(); @@ -375,7 +375,7 @@ PhysicalPlanGenerator::ExtractPrunedJoinProjection(LogicalComparisonJoin &op, co return info; } -PhysicalOperator &PhysicalPlanGenerator::RestorePrunedJoinProjection(LogicalComparisonJoin &op, PhysicalOperator &join, +PhysicalOperator &PhysicalPlanGenerator::RestorePrunedJoinProjection(LogicalJoin &op, PhysicalOperator &join, PrunedJoinProjection info) { if (!info.active) { return join; diff --git a/src/duckdb/src/execution/physical_plan/plan_copy_to_file.cpp b/src/duckdb/src/execution/physical_plan/plan_copy_to_file.cpp index bf66105ee..8feba8dee 100644 --- a/src/duckdb/src/execution/physical_plan/plan_copy_to_file.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_copy_to_file.cpp @@ -25,14 +25,22 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalCopyToFile &op, Physi } else if (op.preserve_order == PreserveOrderType::DONT_PRESERVE_ORDER) { preserve_insertion_order = false; } - if (op.per_thread_output || op.file_size_bytes.IsValid() || op.rotate || op.partition_output || - !op.partition_columns.empty() || !op.order_columns.empty()) { + if (op.per_thread_output || op.partition_output || !op.partition_columns.empty() || !op.order_columns.empty()) { if (op.preserve_order == PreserveOrderType::PRESERVE_ORDER) { throw InvalidInputException("PRESERVE_ORDER is not supported with these parameters"); } // hive-partitioning/per-thread output does not care about insertion order, and does not support batch indexes preserve_insertion_order = false; supports_batch_index = false; + } else if (op.file_size_bytes.IsValid() || op.rotate) { + // rotated files are written one after another, so a required order is kept across them: by the batch + // writer, or by sinking sequentially. An unordered source's insertion order still writes in parallel + if (op.preserve_order == PreserveOrderType::AUTOMATIC) { + preserve_insertion_order = OrderPreservationRecursive(plan) == OrderPreservationType::FIXED_ORDER; + } + if (op.use_tmp_file || !op.function.file_size_bytes) { + supports_batch_index = false; + } } auto mode = CopyFunctionExecutionMode::REGULAR_COPY_TO_FILE; if (op.function.execution_mode) { @@ -57,6 +65,11 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalCopyToFile &op, Physi cast_copy.batch_size = op.batch_size; cast_copy.batch_size_bytes = op.batch_size_bytes; + cast_copy.batches_per_file = op.batches_per_file; + cast_copy.file_size_bytes = op.file_size_bytes; + cast_copy.overwrite_mode = op.overwrite_mode; + cast_copy.filename_pattern = op.filename_pattern; + cast_copy.file_extension = op.file_extension; return copy; } diff --git a/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp b/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp index 6129a081a..e037fd340 100644 --- a/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp @@ -54,6 +54,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalRecursiveCTE &op) { vector distinct_idx, payload_idx; vector> payload_aggregates; vector> payload_comparisons; + vector> payload_distinct_from; // create a group for each target, these are the columns that should be grouped unordered_map group_by_references; @@ -115,6 +116,11 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalRecursiveCTE &op) { if (!has_key_normalizers) { key_normalizers.clear(); } + for (idx_t i = 0; i < payload_types.size(); i++) { + payload_distinct_from.push_back( + BoundComparisonExpression::CreateOnColumns(context, ExpressionType::COMPARE_DISTINCT_FROM, payload_types[i], + i, payload_types[i], payload_types.size() + i)); + } if (!op.union_all) { for (idx_t i = 0; i < payload_types.size(); i++) { unique_ptr previous = make_uniq(payload_types[i], i); @@ -158,6 +164,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalRecursiveCTE &op) { auto &cast_cte = cte.Cast(); cast_cte.payload_aggregates = std::move(payload_aggregates); cast_cte.payload_comparisons = std::move(payload_comparisons); + cast_cte.payload_distinct_from = std::move(payload_distinct_from); cast_cte.key_normalizers = std::move(key_normalizers); cast_cte.key_representative_indices = std::move(key_representative_indices); cast_cte.distinct_idx = distinct_idx; diff --git a/src/duckdb/src/execution/physical_plan/plan_set_operation.cpp b/src/duckdb/src/execution/physical_plan/plan_set_operation.cpp index 078f2b426..8a109ad4b 100644 --- a/src/duckdb/src/execution/physical_plan/plan_set_operation.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_set_operation.cpp @@ -15,26 +15,34 @@ namespace duckdb { +//! The row number of a row among those equal in all columns. The last correlated_column_count columns are compared as +//! they are, the others under their collations static vector> CreatePartitionedRowNumExpression(ClientContext &client, - const vector &types) { + const vector &types, + idx_t correlated_column_count) { vector> res; auto expr = GetBuiltinWindowFunction(client, RowNumberFun::Name, {})->Bind(client); expr->WindowStartMutable() = WindowBoundary::UNBOUNDED_PRECEDING; expr->WindowEndMutable() = WindowBoundary::UNBOUNDED_FOLLOWING; for (idx_t i = 0; i < types.size(); i++) { expr->PartitionsMutable().push_back(make_uniq(types[i], i)); - ExpressionBinder::PushCollation(client, expr->PartitionsMutable().back(), types[i]); + if (i + correlated_column_count < types.size()) { + ExpressionBinder::PushCollation(client, expr->PartitionsMutable().back(), types[i]); + } } res.push_back(std::move(expr)); return res; } -static JoinCondition CreateNotDistinctComparison(ClientContext &context, const LogicalType &type, idx_t i) { +static JoinCondition CreateNotDistinctComparison(ClientContext &context, const LogicalType &type, idx_t i, + bool push_collation) { auto left = make_uniq(type, i); auto right = make_uniq(type, i); JoinCondition cond(std::move(left), std::move(right), ExpressionType::COMPARE_NOT_DISTINCT_FROM); - ExpressionBinder::PushCollation(context, cond.LeftReference(), type); - ExpressionBinder::PushCollation(context, cond.RightReference(), type); + if (push_collation) { + ExpressionBinder::PushCollation(context, cond.LeftReference(), type); + ExpressionBinder::PushCollation(context, cond.RightReference(), type); + } return cond; } @@ -43,6 +51,10 @@ static JoinCondition CreateNotDistinctComparison(ClientContext &context, const L static vector GetComparisonTypes(ClientContext &context, const LogicalSetOperation &op, const vector &left_types, const vector &right_types) { + if (op.comparison_types.size() == left_types.size()) { + // the types the binder resolved + return op.comparison_types; + } // the types only differ in their collations here, but a collation can be missing from a child (e.g. when the // projection applying a COLLATE was removed) or from the operator (it takes the types of the left child) vector types; @@ -82,10 +94,12 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalSetOperation &op) { auto &left = children[0]; auto &right = children[1]; auto types = GetComparisonTypes(context, op, left.get().GetTypes(), right.get().GetTypes()); + D_ASSERT(op.correlated_column_count <= types.size()); vector conditions; - // create equality condition for all columns + // create equality condition for all columns, the correlated columns at the end are compared as they are for (idx_t i = 0; i < types.size(); i++) { - conditions.push_back(CreateNotDistinctComparison(context, types[i], i)); + conditions.push_back( + CreateNotDistinctComparison(context, types[i], i, i + op.correlated_column_count < types.size())); } // For EXCEPT ALL / INTERSECT ALL we push a window operator with a ROW_NUMBER into the scans and join to get bag // semantics. @@ -93,20 +107,20 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalSetOperation &op) { vector window_types = types; window_types.push_back(LogicalType::BIGINT); - auto select_list = CreatePartitionedRowNumExpression(context, types); + auto select_list = CreatePartitionedRowNumExpression(context, types, op.correlated_column_count); auto &left_window = - Make(window_types, std::move(select_list), left.get().estimated_cardinality); + Make(context, window_types, std::move(select_list), left.get().estimated_cardinality); left_window.children.push_back(left); left = left_window; - select_list = CreatePartitionedRowNumExpression(context, types); + select_list = CreatePartitionedRowNumExpression(context, types, op.correlated_column_count); auto &right_window = - Make(window_types, std::move(select_list), right.get().estimated_cardinality); + Make(context, window_types, std::move(select_list), right.get().estimated_cardinality); right_window.children.push_back(right); right = right_window; // add window expression result to join condition - conditions.push_back(CreateNotDistinctComparison(context, LogicalType::BIGINT, types.size())); + conditions.push_back(CreateNotDistinctComparison(context, LogicalType::BIGINT, types.size(), false)); // join (created below) now includes the row number result column op.types.push_back(LogicalType::BIGINT); } diff --git a/src/duckdb/src/execution/physical_plan/plan_top_n.cpp b/src/duckdb/src/execution/physical_plan/plan_top_n.cpp index a28d540a9..b2e3d8a9b 100644 --- a/src/duckdb/src/execution/physical_plan/plan_top_n.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_top_n.cpp @@ -8,8 +8,8 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalTopN &op) { D_ASSERT(op.children.size() == 1); auto &plan = CreatePlan(*op.children[0]); auto &top_n = - Make(op.types, std::move(op.orders), NumericCast(op.limit), NumericCast(op.offset), - std::move(op.dynamic_filter), op.estimated_cardinality); + Make(context, op.types, std::move(op.orders), NumericCast(op.limit), + NumericCast(op.offset), std::move(op.dynamic_filter), op.estimated_cardinality); top_n.children.push_back(plan); return top_n; } diff --git a/src/duckdb/src/execution/physical_plan/plan_window.cpp b/src/duckdb/src/execution/physical_plan/plan_window.cpp index 0e5a85065..31f8b5d40 100644 --- a/src/duckdb/src/execution/physical_plan/plan_window.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_window.cpp @@ -358,18 +358,19 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalWindow &op) { // Chain the new window operator on top of the plan if (i >= special_count) { - auto &window = Make(types, std::move(select_list), op.estimated_cardinality); + auto &window = Make(context, types, std::move(select_list), op.estimated_cardinality); window.children.push_back(plan); plan = window; } else if (has_streaming) { - auto &window = Make(types, std::move(select_list), op.estimated_cardinality); + auto &window = Make(types, std::move(select_list), op.estimated_cardinality, + op.partition_limit); window.children.push_back(plan); plan = window; } else { const auto expr_idx = matching[0]; auto &partitions = partitioned_columns[expr_idx]; - auto &window = - Make(types, std::move(select_list), op.estimated_cardinality, std::move(partitions)); + auto &window = Make(context, types, std::move(select_list), op.estimated_cardinality, + std::move(partitions)); window.children.push_back(plan); plan = window; } diff --git a/src/duckdb/src/execution/radix_ht_adaptivity.cpp b/src/duckdb/src/execution/radix_ht_adaptivity.cpp index b68711249..9d0110ce6 100644 --- a/src/duckdb/src/execution/radix_ht_adaptivity.cpp +++ b/src/duckdb/src/execution/radix_ht_adaptivity.cpp @@ -1,12 +1,34 @@ #include "duckdb/execution/radix_ht_adaptivity.hpp" #include "duckdb/common/exception.hpp" +#include "duckdb/common/helper.hpp" #include "duckdb/common/limits.hpp" #include "duckdb/execution/radix_ht_sink_state.hpp" #include "duckdb/main/client_context.hpp" namespace duckdb { +RadixHTAdaptivity::SinkResult RadixHTAdaptivity::HandleSinkBoundary(RadixHTGlobalSinkState &gstate, + RadixHTLocalSinkState &lstate, + const bool memory_pressure) { + auto &ht = *lstate.ht; + if (!memory_pressure) { + if (TryGrow(gstate, lstate)) { + return SinkResult::GROWN; + } + MaybeSkipLookups(gstate, ht); + } + + if (gstate.number_of_threads > RadixHTConfig::GROW_STRATEGY_THREAD_THRESHOLD || gstate.external) { + // Keep the materialized rows and clear only the local pointer table. + gstate.any_abandoned = true; + ht.Abandon(); + MaybeResumeLookups(ht); + return SinkResult::ABANDONED; + } + return SinkResult::UNCHANGED; +} + bool RadixHTAdaptivity::TryGrow(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate) { if (gstate.number_of_threads <= RadixHTConfig::GROW_STRATEGY_THREAD_THRESHOLD || gstate.external) { return false; @@ -86,31 +108,46 @@ bool RadixHTAdaptivity::TryGrow(RadixHTGlobalSinkState &gstate, RadixHTLocalSink return true; } -void RadixHTAdaptivity::MaybeSkipLookups(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate) { - auto &ht = *lstate.ht; - const auto &adaptivity = ht.GetAdaptivityState(); - if (gstate.external || !adaptivity.HLLEnabled() || adaptivity.LookupsSkipped() || - gstate.number_of_threads <= RadixHTConfig::GROW_STRATEGY_THREAD_THRESHOLD || - adaptivity.GetSinkCount() < LOOKUP_SAMPLE_SIZE || ht.Capacity() != gstate.config.sink_capacity) { +void RadixHTAdaptivity::MaybeSkipLookups(const RadixHTGlobalSinkState &gstate, GroupedAggregateHashTable &ht) { + const auto &state = ht.GetAdaptivityState(); + if (state.LookupsSkipped() || gstate.number_of_threads <= RadixHTConfig::GROW_STRATEGY_THREAD_THRESHOLD || + ht.Capacity() != gstate.config.sink_capacity) { return; } - const auto cycle_input = adaptivity.GetCycleInputCount(); + const auto cycle_input = state.GetCycleInputCount(); D_ASSERT(cycle_input >= ht.Count()); - const auto reduction = - cycle_input ? static_cast(cycle_input - ht.Count()) / static_cast(cycle_input) : 0; - if (reduction < MINIMUM_SMALL_TABLE_REDUCTION) { + if (cycle_input == 0) { + // Failed growth already abandoned this cycle. + return; + } + if (recent_input_rows >= LOOKUP_HISTORY_DECAY_THRESHOLD_ROWS) { + recent_input_rows /= 2; + recent_reduced_rows /= 2; + } + recent_input_rows += cycle_input; + recent_reduced_rows += cycle_input - ht.Count(); + if (state.GetSinkCount() < MIN_INPUT_ROWS_BEFORE_LOOKUP_SKIP) { + return; + } + 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) { + retry_interval_rows = ClampValue(ht.GetMaterializedCount() / LOOKUP_RETRY_MATERIALIZED_ROWS_DIVISOR, + MIN_LOOKUP_RETRY_ROWS, MAX_LOOKUP_RETRY_ROWS); ht.SkipLookups(); } } -void RadixHTAdaptivity::MaybeResumeLookups(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate) { - auto &ht = *lstate.ht; - const auto &adaptivity = ht.GetAdaptivityState(); - if (!gstate.external && !lstate.spilling && adaptivity.HLLEnabled() && adaptivity.LookupsSkipped() && - adaptivity.GetSkippedInputCount() >= LOOKUP_SAMPLE_SIZE) { +void RadixHTAdaptivity::MaybeResumeLookups(GroupedAggregateHashTable &ht) const { + const auto &state = ht.GetAdaptivityState(); + if (state.LookupsSkipped() && state.GetSkippedInputCount() >= retry_interval_rows) { ht.ResumeLookups(); } } +void RadixHTAdaptivity::Reset() { + *this = RadixHTAdaptivity(); +} + } // namespace duckdb diff --git a/src/duckdb/src/execution/radix_partitioned_hashtable.cpp b/src/duckdb/src/execution/radix_partitioned_hashtable.cpp index f32179d84..af641fea5 100644 --- a/src/duckdb/src/execution/radix_partitioned_hashtable.cpp +++ b/src/duckdb/src/execution/radix_partitioned_hashtable.cpp @@ -17,6 +17,7 @@ #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/temporary_memory_manager.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/settings.hpp" namespace duckdb { @@ -132,9 +133,10 @@ RadixHTGlobalSinkState::RadixHTGlobalSinkState(ClientContext &context_p, const R memory_limit(BufferManager::GetBufferManager(context).GetOperatorMemoryLimit()), block_alloc_size(BufferManager::GetBufferManager(context).GetBlockAllocSize()), any_combined(false), any_abandoned(false), radix_ht(radix_ht_p), - spill_plan(AggregateStateSpilling::TryCreateSpillPlan(radix_ht.GetLayout())), config(*this), - stored_allocators_size(0), finalize_done(0), scan_pin_properties(TupleDataPinProperties::DESTROY_AFTER_DONE), - count_before_combining(0), size_before_combining(0), max_partition_size(0) { + spill_plan(AggregateStateSpilling::TryCreateSpillPlan(radix_ht.GetLayout())), + force_external(Settings::Get(context)), config(*this), stored_allocators_size(0), + finalize_done(0), scan_pin_properties(TupleDataPinProperties::DESTROY_AFTER_DONE), count_before_combining(0), + size_before_combining(0), max_partition_size(0) { spill_phase = SpillPhase::NATIVE_ALLOWED; SetReservationFloor(context, MaxValue(config.GetRadixBits(), config.GetMaximumSinkRadixBits())); @@ -209,6 +211,10 @@ void RadixHTGlobalSinkState::Destroy() { RadixHTConfig::RadixHTConfig(RadixHTGlobalSinkState &sink_p) : sink(sink_p), row_width(sink.radix_ht.GetLayout().GetRowWidth()), sink_capacity(SinkCapacity()), sink_radix_bits(InitialSinkRadixBits(sink.number_of_threads)), maximum_sink_radix_bits(MaximumSinkRadixBits()) { + static_assert(MAXIMUM_INITIAL_SINK_RADIX_BITS <= MAXIMUM_FINAL_SINK_RADIX_BITS, + "Initial sink radix bits exceed the final limit"); + static_assert(MAXIMUM_FINAL_SINK_RADIX_BITS <= RadixPartitioning::MAX_RADIX_BITS, + "Sink radix bits exceed radix partitioning support"); } void RadixHTConfig::ResetForNewIteration(const idx_t scheduled_workers) { @@ -219,9 +225,33 @@ void RadixHTConfig::ResetForNewIteration(const idx_t scheduled_workers) { sink_radix_bits = InitialSinkRadixBits(MaxValue(scheduled_workers, 1)); } +// Budget row blocks and optional heap or exported-state blocks across workers, with headroom for repartitioning. +static idx_t PartitioningBytesPerPartition(const RadixHTGlobalSinkState &sink) { + const idx_t blocks_per_partition = sink.radix_ht.GetLayout().AllConstant() && !sink.spill_plan ? 2 : 4; + return sink.number_of_threads * sink.block_alloc_size * blocks_per_partition; +} + void RadixHTConfig::SetRadixBits(const idx_t &radix_bits_p) { - const auto max_bits = MinValue(maximum_sink_radix_bits, ExternalRadixBits(true)); - SetRadixBitsInternal(MinValue(radix_bits_p, max_bits), false); + const auto requested_bits = MinValue(maximum_sink_radix_bits, radix_bits_p); + // Reserve extra partitions only for workers that have started sinking. + const auto workers = MaxValue(MinValue(sink.number_of_threads, sink.active_threads.load()), 1); + const auto reserve_bits = MinValue(requested_bits, RadixPartitioning::RadixBits(workers) - 1); + const auto required = RadixPartitioning::NumberOfPartitions(reserve_bits) * PartitioningBytesPerPartition(sink); + auto &memory = *sink.temporary_memory_state; + const auto should_reserve = [&](const idx_t bits) { + return reserve_bits > bits && !sink.any_combined && !sink.external && required > memory.GetRemainingSize(); + }; + auto available_bits = ExternalRadixBits(true); + if (should_reserve(available_bits)) { + const annotated_lock_guard guard {sink.lock}; + available_bits = ExternalRadixBits(true); + if (should_reserve(available_bits)) { + // Request more space when the current reservation limits parallelism. + memory.SetRemainingSizeAndUpdateReservation(sink.context.GetContext(), required); + available_bits = ExternalRadixBits(true); + } + } + SetRadixBitsInternal(MinValue(requested_bits, available_bits), false); } bool RadixHTConfig::SetRadixBitsToExternal() { @@ -281,13 +311,11 @@ idx_t RadixHTConfig::ExternalRadixBits(const bool dynamic) const { // However, we can't go to, e.g., 256 partitions when we have 8 threads and 200 MiB of memory // Because we'll have too many pages in memory to do the partitioning in the first place - // Budget row blocks and optional heap or exported-state blocks, with headroom for repartitioning. const auto reservation = sink.temporary_memory_state->GetReservation(); // An unspillable arena cannot fund a larger partitioning working set. const auto use_reservation = dynamic && (sink.spill_plan || reservation <= sink.memory_limit); const auto memory_limit = use_reservation ? reservation : sink.memory_limit / 2; - const idx_t pages_per_partition = sink.radix_ht.GetLayout().AllConstant() && !sink.spill_plan ? 2 : 4; - const auto max_partitions = memory_limit / sink.number_of_threads / sink.block_alloc_size / pages_per_partition; + const auto max_partitions = memory_limit / PartitioningBytesPerPartition(sink); // Compute number of bits, rounded down, at least as much as initial bits const auto bits = @@ -315,6 +343,10 @@ idx_t RadixHTConfig::MaximumSinkRadixBits() const { } else { bits = MAXIMUM_FINAL_SINK_RADIX_BITS; } + if (sink.radix_ht.GetLayout().AllConstant()) { + // Allow enough fixed-width partitions to keep the available workers busy. + bits = MaxValue(bits, RadixPartitioning::RadixBitsOfPowerOfTwo(NextPowerOfTwo(sink.number_of_threads))); + } // Capped by external radix bits return MinValue(bits, ExternalRadixBits(false)); } @@ -361,6 +393,7 @@ void RadixHTLocalSinkState::ResetForReuse(const RadixPartitionedHashTable &radix registered = false; spilling = false; size_after_abandon = 0; + adaptivity.Reset(); abandoned_data.reset(); abandoned_exported_data.clear(); if (!ht) { @@ -592,7 +625,7 @@ bool ShouldExportStates(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &l // every current state is inline, and exporting would only cost return false; } - if (gstate.StatePressureExceeded(ht) || !lstate.abandoned_exported_data.empty()) { + if (gstate.force_external || gstate.StatePressureExceeded(ht) || !lstate.abandoned_exported_data.empty()) { return true; } if (!gstate.external) { @@ -693,9 +726,14 @@ void MaybeRepartition(ClientContext &context, RadixHTGlobalSinkState &gstate, Ra const auto current_radix_bits = RadixPartitioning::RadixBitsOfPowerOfTwo(partition_count); D_ASSERT(current_radix_bits <= config.GetRadixBits()); - const auto row_size_per_partition = - ht.GetMaterializedCount() * ht.GetPartitionedData().GetLayout().GetRowWidth() / partition_count; - if (row_size_per_partition > + const auto &layout = ht.GetPartitionedData().GetLayout(); + auto data_size = ht.GetMaterializedCount() * layout.GetRowWidth(); + if (!layout.AllConstant() && partition_count < gstate.number_of_threads) { + // Include heap bytes when additional partitions can expose more parallelism. + data_size = ht.GetMaterializedSize(); + } + const auto size_per_partition = data_size / partition_count; + if (size_per_partition > LossyNumericCast(config.BLOCK_FILL_FACTOR * static_cast(gstate.block_alloc_size))) { // We crossed our block filling threshold, try to increment radix bits config.SetRadixBits(current_radix_bits + config.REPARTITION_RADIX_BITS); @@ -745,24 +783,11 @@ void RadixPartitionedHashTable::Sink(ExecutionContext &context, DataChunk &chunk return; } - if (!memory_pressure) { - if (RadixHTAdaptivity::TryGrow(gstate, lstate)) { - return; - } - RadixHTAdaptivity::MaybeSkipLookups(gstate, lstate); - } - - bool abandoned = false; - if (gstate.number_of_threads > RadixHTConfig::GROW_STRATEGY_THREAD_THRESHOLD || gstate.external) { - // Keep the materialized rows and clear only the local pointer table - // We don't do this when running with 1 or 2 threads, it only makes sense when there's many threads - gstate.any_abandoned = true; - ht.Abandon(); - abandoned = true; - if (!memory_pressure) { - RadixHTAdaptivity::MaybeResumeLookups(gstate, lstate); - } + const auto adaptivity_result = lstate.adaptivity.HandleSinkBoundary(gstate, lstate, memory_pressure); + if (adaptivity_result == RadixHTAdaptivity::SinkResult::GROWN) { + return; } + bool abandoned = adaptivity_result == RadixHTAdaptivity::SinkResult::ABANDONED; // Check if we need to repartition const auto radix_bits_before = ht.GetRadixBits(); @@ -933,8 +958,9 @@ void RadixPartitionedHashTable::Finalize(ClientContext &context, GlobalSinkState // If true there is no need to combine, it was all done by a single thread in a single HT. // This is the case when only one thread contributed data and the HT never overflowed its - // capacity (which would have caused Abandon() to be called, creating duplicates). - const auto single_ht = !gstate.external && gstate.active_threads == 1 && !gstate.any_abandoned; + // capacity (which would have caused Abandon() to be called, creating duplicates) or exported states. + const auto single_ht = !gstate.external && gstate.active_threads == 1 && !gstate.any_abandoned && + gstate.uncombined_exported_data.empty(); auto &uncombined_partition_data = uncombined_data.GetPartitions(); const auto n_partitions = uncombined_partition_data.size(); @@ -1209,6 +1235,7 @@ void RadixHTLocalSourceState::Finalize(RadixHTGlobalSinkState &sink, RadixHTGlob } else { ht->Abandon(); } + const auto allocator_size = ht->GetAggregateAllocator()->AllocationSize(); // Now combine the uncombined data using this thread's HT partition.combine_chunk_count = partition.data->ChunkCount(); @@ -1238,6 +1265,7 @@ void RadixHTLocalSourceState::Finalize(RadixHTGlobalSinkState &sink, RadixHTGlob partition.allocator = ht->GetAggregateAllocator(); } else { sink.stored_allocators.emplace_back(ht->GetAggregateAllocator()); + sink.stored_allocators_size += sink.stored_allocators.back()->AllocationSize() - allocator_size; } if (task_idx == sink.partitions.size()) { ht.reset(); diff --git a/src/duckdb/src/function/aggregate/distributive/first_last_any.cpp b/src/duckdb/src/function/aggregate/distributive/first_last_any.cpp index f36a4e847..509a544c8 100644 --- a/src/duckdb/src/function/aggregate/distributive/first_last_any.cpp +++ b/src/duckdb/src/function/aggregate/distributive/first_last_any.cpp @@ -534,6 +534,14 @@ void AddFirstOperator(AggregateFunctionSet &set) { } // namespace +bool IsFirstLastOrAnyValue(const BoundAggregateFunction &function) { + // All specializations and aliases bind one of these private callbacks. An + // implementation replacement installs its own callbacks even if it keeps the name. + auto rewrite = function.GetDirectRewriteCallback(); + return rewrite == RewriteOrderedFirst || rewrite == RewriteOrderedFirst || + rewrite == RewriteOrderedFirst; +} + AggregateFunction FirstFunctionGetter::GetFunction(const LogicalType &type) { auto fun = GetFirstFunction(type); fun.SetName("first"); diff --git a/src/duckdb/src/function/aggregate/distributive/minmax.cpp b/src/duckdb/src/function/aggregate/distributive/minmax.cpp index f589acfae..9d93f3ca2 100644 --- a/src/duckdb/src/function/aggregate/distributive/minmax.cpp +++ b/src/duckdb/src/function/aggregate/distributive/minmax.cpp @@ -408,7 +408,7 @@ unique_ptr BindMinMax(BindAggregateFunctionInput &input) { arguments = std::move(expr->GetChildrenMutable()); function.ReplaceImplementation(expr->Function()); - return std::move(expr->BindInfoMutable()); + return expr->BindInfo() ? expr->BindInfo()->Copy() : nullptr; } //! BindMinMax replaces a collated min/max with arg_min/arg_max over the collation key, so the bound call has one @@ -543,12 +543,19 @@ void SpecializeMinMaxNFunction(PhysicalType arg_type, BoundAggregateFunction &fu case PhysicalType::INT64: SpecializeMinMaxNFunction, COMPARATOR>(function); break; + case PhysicalType::INT128: + SpecializeMinMaxNFunction, COMPARATOR>(function); + break; case PhysicalType::FLOAT: SpecializeMinMaxNFunction, COMPARATOR>(function); break; case PhysicalType::DOUBLE: SpecializeMinMaxNFunction, COMPARATOR>(function); break; + case PhysicalType::INTERVAL: + // sort keys do not normalize intervals, so compare them as interval_t + SpecializeMinMaxNFunction, COMPARATOR>(function); + break; default: SpecializeMinMaxNFunction(function); break; @@ -581,7 +588,7 @@ unique_ptr MinMaxNBind(BindAggregateFunctionInput &input) { auto expr = function_binder.BindAggregateFunction(collated_function, std::move(collated_arguments)); arguments = std::move(expr->GetChildrenMutable()); function.ReplaceImplementation(expr->Function()); - return std::move(expr->BindInfoMutable()); + return expr->BindInfo() ? expr->BindInfo()->Copy() : nullptr; } } diff --git a/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp b/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp index 9427266b0..c36947433 100644 --- a/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp +++ b/src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp @@ -60,7 +60,7 @@ LogicalType BufferStructType(const vector &column_types) { struct SortedAggregateBindData : public FunctionData { using Expressions = vector>; - using BindInfoPtr = unique_ptr; + using BindInfoPtr = cow_ptr; using OrderBys = vector; //! fixed_layout: the buffer struct and per-key columns to use instead of mapping the keys onto the arguments @@ -189,7 +189,7 @@ struct SortedAggregateBindData : public FunctionData { ClientContext &context; BoundAggregateFunction function; - unique_ptr bind_info; + cow_ptr bind_info; //! The sort expressions (all references as the expressions have been computed) vector orders; @@ -231,7 +231,8 @@ struct SortedAggregateFinalizeState : FunctionLocalState { explicit SortedAggregateFinalizeState(const SortedAggregateBindData &order_bind) : thread(order_bind.context), context(order_bind.context, thread, nullptr), agg_state(StateSize(order_bind)), - agg_state_vec(Value::POINTER(CastPointerToValue(agg_state.data())), count_t(1)) { + agg_state_vec(Value::POINTER(CastPointerToValue(agg_state.data())), count_t(1)), + inner_arena(BufferManager::GetBufferManager(order_bind.context).GetBufferAllocator()) { auto &buffer_allocator = BufferManager::GetBufferManager(order_bind.context).GetBufferAllocator(); rows.Initialize(buffer_allocator, {order_bind.buffered_struct_type}); scanned.Initialize(buffer_allocator, order_bind.scan_types); @@ -246,7 +247,8 @@ struct SortedAggregateFinalizeState : FunctionLocalState { } } - static unique_ptr Init(const BoundAggregateFunction &, optional_ptr bind_data) { + static unique_ptr Init(const BoundAggregateFunction &, + optional_ptr bind_data) { return make_uniq(bind_data->Cast()); } @@ -268,6 +270,8 @@ struct SortedAggregateFinalizeState : FunctionLocalState { Vector agg_state_vec; //! The local state used by the inner aggregate's finalize (may be null) unique_ptr inner_local_state; + //! The arena of the inner aggregate states, reset per batch of groups + ArenaAllocator inner_arena; }; struct SortedAggregateFunction { @@ -369,8 +373,8 @@ struct SortedAggregateFunction { state.linked_list = LinkedList(); } - static void FinalizeGroups(Vector &states, AggregateFinalizeInputData &finalize_input_data, Vector &result, - idx_t count, const idx_t offset) { + static void FinalizeGroups(Vector &states, AggregateFinalizeInputData &finalize_input_data, + ArenaAllocator &inner_allocator, Vector &result, idx_t count, const idx_t offset) { auto &order_bind = finalize_input_data.bind_data->Cast(); auto &client = order_bind.context; @@ -388,7 +392,7 @@ struct SortedAggregateFunction { // State variables auto &aggr = order_bind.function; auto bind_info = order_bind.bind_info.get(); - AggregateFinalizeInputData aggr_bind_info(aggr, bind_info, finalize_input_data.allocator, + AggregateFinalizeInputData aggr_bind_info(aggr, bind_info, inner_allocator, finalize_state.inner_local_state.get()); // Inner aggregate APIs @@ -545,16 +549,26 @@ struct SortedAggregateFunction { static void Finalize(Vector &states, AggregateFinalizeInputData &finalize_input_data, Vector &result, idx_t count, const idx_t offset) { + // The inner states can reference the results they finalized to, so they can only be + // reclaimed when the local state outlives the result + D_ASSERT(finalize_input_data.local_state); + auto &finalize_state = finalize_input_data.local_state->Cast(); + const auto reclaim = !finalize_input_data.OwnsLocalState(); + if (reclaim && offset == 0) { + finalize_state.inner_arena.Reset(); + } + auto &inner_allocator = reclaim ? finalize_state.inner_arena : finalize_input_data.allocator; // Internally we can only handle 2^16 rows, so chunk them up const idx_t group_limit = NumericLimits::Maximum(); if (count <= group_limit) { - FinalizeGroups(states, finalize_input_data, result, count, offset); + FinalizeGroups(states, finalize_input_data, inner_allocator, result, count, offset); return; } for (idx_t group_offset = 0; group_offset < count; group_offset += group_limit) { const auto group_count = MinValue(group_limit, count - group_offset); Vector group_states(states, group_offset, group_offset + group_count); - FinalizeGroups(group_states, finalize_input_data, result, group_count, offset + group_offset); + FinalizeGroups(group_states, finalize_input_data, inner_allocator, result, group_count, + offset + group_offset); } } }; diff --git a/src/duckdb/src/function/aggregate_function.cpp b/src/duckdb/src/function/aggregate_function.cpp index e83141052..384f3dae7 100644 --- a/src/duckdb/src/function/aggregate_function.cpp +++ b/src/duckdb/src/function/aggregate_function.cpp @@ -49,7 +49,7 @@ AggregateInputData::AggregateInputData(const AggregateObject &aggr, ArenaAllocat } AggregateFinalizeInputData::AggregateFinalizeInputData(const BoundAggregateFunction &function_p, - optional_ptr bind_data_p, + optional_ptr bind_data_p, ArenaAllocator &allocator_p, optional_ptr local_state_p) : AggregateInputData(function_p, bind_data_p, allocator_p), local_state(local_state_p) { @@ -84,7 +84,7 @@ void AggregateFinalizeInputData::InitializeLocalState() { bool AggregateFunctionProperties::operator==(const AggregateFunctionProperties &rhs) const { return FunctionProperties::operator==(rhs) && order_dependent == rhs.order_dependent && distinct_dependent == rhs.distinct_dependent && single_value_identity == rhs.single_value_identity && - is_holistic == rhs.is_holistic; + is_holistic == rhs.is_holistic && combine_source_retention == rhs.combine_source_retention; } bool AggregateFunctionProperties::operator!=(const AggregateFunctionProperties &rhs) const { return !(*this == rhs); diff --git a/src/duckdb/src/function/aggregate_state_serialization.cpp b/src/duckdb/src/function/aggregate_state_serialization.cpp index 3e5419f6b..f87ad5248 100644 --- a/src/duckdb/src/function/aggregate_state_serialization.cpp +++ b/src/duckdb/src/function/aggregate_state_serialization.cpp @@ -14,7 +14,7 @@ namespace duckdb { namespace { template -void TemplateDispatch(PhysicalType type, ARGS &&... args) { +void TemplateDispatch(PhysicalType type, ARGS &&...args) { switch (type) { case PhysicalType::BOOL: OP::template Operation(std::forward(args)...); @@ -332,7 +332,7 @@ void AggregateStateSerialization::SerializeStates(const AggregateStateLayout &la } void AggregateStateSerialization::SerializeStates(const BoundAggregateFunction &aggr, - optional_ptr bind_data, + optional_ptr bind_data, const AggregateStateLayout &layout, Vector &states, idx_t count, Vector &result, ArenaAllocator &allocator, idx_t offset) { if (aggr.HasExportAggregateStateCallback()) { diff --git a/src/duckdb/src/function/built_in_functions.cpp b/src/duckdb/src/function/built_in_functions.cpp index 3dee9aabc..eb345dc51 100644 --- a/src/duckdb/src/function/built_in_functions.cpp +++ b/src/duckdb/src/function/built_in_functions.cpp @@ -4,7 +4,6 @@ #include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp" #include "duckdb/main/extension_entries.hpp" #include "duckdb/parser/parsed_data/create_aggregate_function_info.hpp" -#include "duckdb/parser/parsed_data/create_collation_info.hpp" #include "duckdb/parser/parsed_data/create_copy_function_info.hpp" #include "duckdb/parser/parsed_data/create_pragma_function_info.hpp" #include "duckdb/parser/parsed_data/create_scalar_function_info.hpp" @@ -24,13 +23,6 @@ BuiltinFunctions::BuiltinFunctions(CatalogTransaction transaction, Catalog &cata BuiltinFunctions::~BuiltinFunctions() { } -void BuiltinFunctions::AddCollation(string name, ScalarFunction function, bool combinable, - bool not_required_for_equality) { - CreateCollationInfo info(Identifier(std::move(name)), std::move(function), combinable, not_required_for_equality); - info.internal = true; - catalog.CreateCollation(transaction, info); -} - void BuiltinFunctions::AddFunction(AggregateFunctionSet set) { CreateAggregateFunctionInfo info(std::move(set)); info.internal = true; @@ -144,20 +136,33 @@ void BuiltinFunctions::RegisterExtensionOverloads() { #endif ScalarFunctionSet current_set; for (auto &entry : EXTENSION_FUNCTION_OVERLOADS) { - vector arguments; - auto splits = StringUtil::Split(entry.signature, ">"); - auto return_type = DBConfig::ParseLogicalType(splits[1]); - auto parameters = Value(splits[0]).DefaultCastAs(LogicalType::LIST(LogicalType::VARCHAR)); - for (auto ¶m : ListValue::GetChildren(parameters)) { - arguments.push_back(DBConfig::ParseLogicalType(param.GetValue())); - } if (entry.type != CatalogType::SCALAR_FUNCTION_ENTRY) { throw InternalException( "Extension function overloads only supported for scalar functions currently - %s has a different type", entry.name); } - ScalarFunction function(entry.name, std::move(arguments), std::move(return_type), nullptr); + auto splits = StringUtil::Split(entry.signature, ">"); + auto return_type = DBConfig::ParseLogicalType(splits[1]); + auto parameter_types = + ListValue::GetChildren(Value(splits[0]).DefaultCastAs(LogicalType::LIST(LogicalType::VARCHAR))); + auto parameter_names = + ListValue::GetChildren(Value(entry.parameters).DefaultCastAs(LogicalType::LIST(LogicalType::VARCHAR))); + + FunctionSignature signature; + if (parameter_types.size() == parameter_names.size()) { + for (idx_t i = 0; i < parameter_types.size(); i++) { + signature.AddParameter(Identifier(parameter_names[i].GetValue()), + DBConfig::ParseLogicalType(parameter_types[i].GetValue())); + } + } else { + for (auto ¶m : parameter_types) { + signature.AddParameter(DBConfig::ParseLogicalType(param.GetValue())); + } + } + signature.SetReturnType(std::move(return_type)); + + ScalarFunction function(entry.name, std::move(signature), nullptr); function.SetBindExpressionCallback(BindExtensionFunction); function.SetExtraFunctionInfo(entry.extension); diff --git a/src/duckdb/src/function/builtin_encodings.cpp b/src/duckdb/src/function/builtin_encodings.cpp new file mode 100644 index 000000000..e095d4f87 --- /dev/null +++ b/src/duckdb/src/function/builtin_encodings.cpp @@ -0,0 +1,191 @@ +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/common/exception.hpp" +#include "duckdb/common/exception/conversion_exception.hpp" +#include "duckdb/function/built_in_functions.hpp" +#include "duckdb/function/encoding_function.hpp" +#include "duckdb/parser/parsed_data/create_scalar_function_info.hpp" +#include "duckdb/parser/parsed_data/create_schema_info.hpp" + +namespace duckdb { + +namespace { + +void DecodeLatin1ToUTF8(const char *input, idx_t input_size, bool is_last, char *output, idx_t &consumed, + idx_t &written) { + idx_t out = 0; + for (idx_t i = 0; i < input_size; i++) { + const auto ch = static_cast(input[i]); + if (ch > 0x7F && ch <= 0x9F) { + throw InvalidInputException("File is not latin-1 encoded"); + } + if (ch <= 0x7F) { + output[out++] = static_cast(ch); + } else { + output[out++] = static_cast(0xc2 + (ch > 0xbf)); + output[out++] = static_cast((ch & 0x3f) + 0x80); + } + } + consumed = input_size; + written = out; +} + +uint16_t LoadUTF16(const char *input, idx_t pos) { + return static_cast(static_cast(input[pos]) | + (static_cast(input[pos + 1]) << 8)); +} + +void EncodeUTF8ToLatin1(const char *input, idx_t input_size, char *output, idx_t &written) { + idx_t out = 0; + idx_t pos = 0; + while (pos < input_size) { + const auto lead = static_cast(input[pos]); + if (lead <= 0x7F) { + output[out++] = static_cast(lead); + pos++; + continue; + } + // a two byte sequence U+0080..U+07FF, valid UTF-8 is guaranteed by VARCHAR + uint32_t code_point = 0; + idx_t length = 1; + if (lead >= 0xF0) { + length = 4; + } else if (lead >= 0xE0) { + length = 3; + } else { + length = 2; + code_point = ((lead & 0x1F) << 6) | (static_cast(input[pos + 1]) & 0x3F); + } + if (length != 2 || code_point > 0xFF || code_point <= 0x9F) { + throw ConversionException("Could not encode the character at byte %llu in latin-1", pos); + } + output[out++] = static_cast(code_point); + pos += length; + } + written = out; +} + +void EncodeUTF8ToUTF16(const char *input, idx_t input_size, char *output, idx_t &written) { + idx_t out = 0; + idx_t pos = 0; + auto store = [&](uint16_t unit) { + output[out++] = static_cast(unit & 0xFF); + output[out++] = static_cast(unit >> 8); + }; + while (pos < input_size) { + const auto lead = static_cast(input[pos]); + uint32_t code_point; + idx_t length; + if (lead <= 0x7F) { + code_point = lead; + length = 1; + } else if (lead < 0xE0) { + code_point = ((lead & 0x1F) << 6) | (static_cast(input[pos + 1]) & 0x3F); + length = 2; + } else if (lead < 0xF0) { + code_point = ((lead & 0x0F) << 12) | ((static_cast(input[pos + 1]) & 0x3F) << 6) | + (static_cast(input[pos + 2]) & 0x3F); + length = 3; + } else { + code_point = ((lead & 0x07) << 18) | ((static_cast(input[pos + 1]) & 0x3F) << 12) | + ((static_cast(input[pos + 2]) & 0x3F) << 6) | + (static_cast(input[pos + 3]) & 0x3F); + length = 4; + } + if (code_point >= 0x10000) { + code_point -= 0x10000; + store(static_cast(0xD800 + (code_point >> 10))); + store(static_cast(0xDC00 + (code_point & 0x3FF))); + } else { + store(static_cast(code_point)); + } + pos += length; + } + written = out; +} + +void DecodeUTF16ToUTF8(const char *input, idx_t input_size, bool is_last, char *output, idx_t &consumed, + idx_t &written) { + idx_t pos = 0; + idx_t out = 0; + while (pos < input_size) { + if (pos + 1 >= input_size) { + if (is_last) { + throw InvalidInputException("Input is not valid UTF-16"); + } + break; + } + const uint16_t ch = LoadUTF16(input, pos); + if (ch >= 0xD800 && ch <= 0xDFFF) { + if (ch >= 0xDC00) { + // low surrogate without a preceding high surrogate + throw InvalidInputException("Input is not valid UTF-16"); + } + if (pos + 3 >= input_size) { + if (is_last) { + throw InvalidInputException("Input is not valid UTF-16"); + } + // the low surrogate follows in the next buffer + break; + } + const uint16_t low = LoadUTF16(input, pos + 2); + if (low < 0xDC00 || low > 0xDFFF) { + throw InvalidInputException("Input is not valid UTF-16"); + } + const uint32_t code_point = 0x10000 + ((static_cast(ch - 0xD800)) << 10) + (low - 0xDC00); + output[out++] = static_cast(0xF0 | (code_point >> 18)); + output[out++] = static_cast(0x80 | ((code_point >> 12) & 0x3F)); + output[out++] = static_cast(0x80 | ((code_point >> 6) & 0x3F)); + output[out++] = static_cast(0x80 | (code_point & 0x3F)); + pos += 4; + continue; + } + if (ch <= 0x007F) { + output[out++] = static_cast(ch); + } else if (ch <= 0x07FF) { + output[out++] = static_cast(0xC0 | (ch >> 6)); + output[out++] = static_cast(0x80 | (ch & 0x3F)); + } else { + output[out++] = static_cast(0xE0 | (ch >> 12)); + output[out++] = static_cast(0x80 | ((ch >> 6) & 0x3F)); + output[out++] = static_cast(0x80 | (ch & 0x3F)); + } + pos += 2; + } + consumed = pos; + written = out; +} + +} // namespace + +void BuiltinFunctions::RegisterEncodingFunctions() { + CreateSchemaInfo schema; + schema.SetQualifiedName(QualifiedName({Identifier(EncodingFunction::SCHEMA)}, Identifier())); + schema.internal = true; + schema.on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; + catalog.CreateSchema(transaction, schema); + + // Wrap the codecs in lambdas, a std::function holding a function pointer exports its typeinfo + decode_t latin1_decode = [](const char *input, idx_t input_size, bool is_last, char *output, idx_t &consumed, + idx_t &written) { + DecodeLatin1ToUTF8(input, input_size, is_last, output, consumed, written); + }; + encode_t latin1_encode = [](const char *input, idx_t input_size, char *output, idx_t &written) { + EncodeUTF8ToLatin1(input, input_size, output, written); + }; + decode_t utf16_decode = [](const char *input, idx_t input_size, bool is_last, char *output, idx_t &consumed, + idx_t &written) { + DecodeUTF16ToUTF8(input, input_size, is_last, output, consumed, written); + }; + encode_t utf16_encode = [](const char *input, idx_t input_size, char *output, idx_t &written) { + EncodeUTF8ToUTF16(input, input_size, output, written); + }; + for (auto &set : {EncodingFunction::Create("latin-1", latin1_decode, latin1_encode, 1, 2), + EncodingFunction::Create("utf-16", utf16_decode, utf16_encode, 4, 2)}) { + CreateScalarFunctionInfo info(set); + EncodingFunction::SetSchema(info); + info.internal = true; + catalog.CreateFunction(transaction, info); + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/function/cast/blob_cast.cpp b/src/duckdb/src/function/cast/blob_cast.cpp index 65f90e17f..e0134d696 100644 --- a/src/duckdb/src/function/cast/blob_cast.cpp +++ b/src/duckdb/src/function/cast/blob_cast.cpp @@ -17,6 +17,7 @@ BoundCastInfo DefaultCasts::BlobCastSwitch(BindCastInput &input, const LogicalTy case LogicalTypeId::BIT: return BoundCastInfo(&VectorCastHelpers::TryCastStringLoop); case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: return BlobToGeoCast(input, source, target); default: return DefaultCasts::TryVectorNullCast; diff --git a/src/duckdb/src/function/cast/cast_function_set.cpp b/src/duckdb/src/function/cast/cast_function_set.cpp index 26b6ec25a..d852f8fb2 100644 --- a/src/duckdb/src/function/cast/cast_function_set.cpp +++ b/src/duckdb/src/function/cast/cast_function_set.cpp @@ -201,6 +201,14 @@ static auto RelaxedTypeMatch(MAP &map, const LogicalType &type) -> decltype(map. } return map.find(LogicalType::ANY); } + case LogicalTypeId::GEOGRAPHY: { + // a GEOGRAPHY with a CRS matches the casts of the GEOGRAPHY without a CRS + auto entry = map.find(LogicalType::GEOGRAPHY()); + if (entry != map.end()) { + return entry; + } + return map.find(LogicalType::ANY); + } default: return map.find(LogicalType::ANY); } diff --git a/src/duckdb/src/function/cast/cast_statistics.cpp b/src/duckdb/src/function/cast/cast_statistics.cpp index e21c919c9..87ea64ccf 100644 --- a/src/duckdb/src/function/cast/cast_statistics.cpp +++ b/src/duckdb/src/function/cast/cast_statistics.cpp @@ -281,6 +281,10 @@ unique_ptr CastStatistics::TryPropagate(const BaseStatistics &st // type set and null-ness are unchanged: propagate the statistics as-is. return stats.Copy().ToUnique(); } + if (source.id() == LogicalTypeId::GEOGRAPHY && target.id() == LogicalTypeId::GEOGRAPHY) { + // Same as geometry -> geometry: only the CRS changes, so the (geodetic) statistics carry over as-is. + return stats.Copy().ToUnique(); + } if (source.id() == LogicalTypeId::ARRAY && target.id() == LogicalTypeId::LIST) { return StatisticsPropagateArrayToList(stats, source, target); } diff --git a/src/duckdb/src/function/cast/decimal_cast.cpp b/src/duckdb/src/function/cast/decimal_cast.cpp index ea0ebf168..ba64a71f8 100644 --- a/src/duckdb/src/function/cast/decimal_cast.cpp +++ b/src/duckdb/src/function/cast/decimal_cast.cpp @@ -1,9 +1,11 @@ #include "duckdb/function/cast/default_casts.hpp" #include "duckdb/function/cast/vector_cast_helpers.hpp" +#include "duckdb/function/cast/wide_decimal_cast.hpp" #include "duckdb/common/vector_operations/general_cast.hpp" #include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/bignum.hpp" #include "duckdb/common/vector_operations/unary_executor.hpp" #include "duckdb/common/types/cast_helpers.hpp" @@ -142,7 +144,7 @@ struct DecimalScaleDownOperator { // This function detects if we can scale a decimal down to another. template static bool CanScaleDownDecimal(INPUT_TYPE input, DecimalScaleInput &data) { - int64_t divisor = UnsafeNumericCast(data.factor); + const auto divisor = data.factor; auto value = input % divisor; auto rounded_input = input; if (rounded_input < 0) { @@ -155,21 +157,6 @@ static bool CanScaleDownDecimal(INPUT_TYPE input, DecimalScaleInput return rounded_input < data.limit && rounded_input > -data.limit; } -template <> -bool CanScaleDownDecimal(hugeint_t input, DecimalScaleInput &data) { - auto divisor = UnsafeNumericCast(data.factor); - hugeint_t value = input % divisor; - hugeint_t rounded_input = input; - if (rounded_input < 0) { - rounded_input *= -1; - value *= -1; - } - if (value >= divisor / 2) { - rounded_input += divisor; - } - return rounded_input < data.limit && rounded_input > -data.limit; -} - struct DecimalScaleDownCheckOperator { template static RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, DecimalScaleInput &data) { @@ -216,7 +203,14 @@ struct BignumDecimalScaleInput { uint32_t source_scale_p, uint32_t target_width_p, uint32_t target_scale_p) : result(result_p), vector_cast_data(result, parameters), source_width(source_width_p), source_scale(source_scale_p), target_width(target_width_p), target_scale(target_scale_p), - context(DefaultCasts::WideDecimalCastContext(parameters)) { + fallback(DefaultCasts::WideDecimalCastContext(parameters)), + rescale_state((parameters.local_state ? parameters.local_state->Cast() : fallback) + .GetRescaleState()) { + const auto source_integer_digits = source_width - source_scale; + const auto target_integer_digits = target_width - target_scale; + // Scaling down can round into an extra integer digit. + check_width = target_scale >= source_scale ? source_integer_digits > target_integer_digits + : source_integer_digits >= target_integer_digits; } Vector &result; @@ -225,39 +219,29 @@ struct BignumDecimalScaleInput { uint32_t source_scale; uint32_t target_width; uint32_t target_scale; - optional_ptr context; + bool check_width; + WideDecimalCastState fallback; + DecimalHelper::RescaleState &rescale_state; }; -//! The unscaled value of a decimal as a BIGNUM (the blob of a fixed-size tier is written into "blob") -static bignum_t UnscaledBignum(bignum_t input, string &blob) { - return input; -} - -template -static bignum_t UnscaledBignum(INPUT_TYPE input, string &blob) { - blob = DecimalHelper::FromInteger(hugeint_t(input)); - return bignum_t(string_t(blob)); -} - struct BignumDecimalScaleOperator { template static RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, BignumDecimalScaleInput &data) { - string unscaled_blob; - auto unscaled = UnscaledBignum(input, unscaled_blob); - string rescaled; - if (!DecimalHelper::TryRescale(unscaled, data.source_scale, data.target_width, data.target_scale, - rescaled, data.context)) { + data.rescale_state.Reset(); + auto rescaled = + DecimalHelper::Rescale(data.rescale_state, input, data.source_scale, data.target_scale); + if (data.check_width && !DecimalHelper::FitsWidth(rescaled, data.target_width)) { auto error = StringUtil::Format("Casting value \"%s\" to type %s failed: value is out of range!", Decimal::ToString(input, data.source_width, data.source_scale), data.result.GetType().ToString()); return HandleVectorCastError::Operation(std::move(error), mask, idx, data.vector_cast_data); } if constexpr (std::is_same::value) { - return bignum_t(StringVector::AddStringOrBlob(data.result, rescaled.data(), rescaled.size())); + return bignum_t(StringVector::AddStringOrBlob(data.result, rescaled.data)); } else { // the checked width guarantees the value fits the integer hugeint_t value; - if (!DecimalHelper::TryToHugeint(bignum_t(string_t(rescaled)), value)) { + if (!DecimalHelper::TryToHugeint(rescaled, value)) { throw InternalException("Rescaled decimal does not fit a HUGEINT despite the width check"); } return Cast::Operation(value); @@ -301,6 +285,9 @@ static bool DecimalDecimalCastSwitch(Vector &source, Vector &result, idx_t count source.GetType().Verify(); result.GetType().Verify(); + if (result.GetType().InternalType() == PhysicalType::VARCHAR) { + return TemplatedBignumDecimalScale(source, result, count, parameters); + } // we need to either multiply or divide by the difference in scales if (result_scale >= source_scale) { // multiply @@ -317,8 +304,6 @@ static bool DecimalDecimalCastSwitch(Vector &source, Vector &result, idx_t count case PhysicalType::INT128: return TemplatedDecimalScaleUp(source, result, count, parameters); - case PhysicalType::VARCHAR: - return TemplatedBignumDecimalScale(source, result, count, parameters); default: throw NotImplementedException("Unimplemented internal type for decimal"); } @@ -333,8 +318,6 @@ static bool DecimalDecimalCastSwitch(Vector &source, Vector &result, idx_t count return TemplatedDecimalScaleDown(source, result, count, parameters); case PhysicalType::INT128: return TemplatedDecimalScaleDown(source, result, count, parameters); - case PhysicalType::VARCHAR: - return TemplatedBignumDecimalScale(source, result, count, parameters); default: throw NotImplementedException("Unimplemented internal type for decimal"); } diff --git a/src/duckdb/src/function/cast/default_casts.cpp b/src/duckdb/src/function/cast/default_casts.cpp index 9f97afbf6..85fbd4dde 100644 --- a/src/duckdb/src/function/cast/default_casts.cpp +++ b/src/duckdb/src/function/cast/default_casts.cpp @@ -194,6 +194,7 @@ BoundCastInfo DefaultCasts::GetDefaultCastFunction(BindCastInput &input, const L case LogicalTypeId::ARRAY: return ArrayCastSwitch(input, source, target); case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: return GeoCastSwitch(input, source, target); case LogicalTypeId::TYPE: return TypeCastSwitch(input, source, target); diff --git a/src/duckdb/src/function/cast/geo_casts.cpp b/src/duckdb/src/function/cast/geo_casts.cpp index a1de3d7d4..53e7cab20 100644 --- a/src/duckdb/src/function/cast/geo_casts.cpp +++ b/src/duckdb/src/function/cast/geo_casts.cpp @@ -4,6 +4,8 @@ #include "duckdb/function/cast/vector_cast_helpers.hpp" #include "duckdb/common/exception/binder_exception.hpp" #include "duckdb/common/error_data.hpp" +#include "duckdb/common/operator/cast_operators.hpp" +#include "duckdb/common/optional.hpp" namespace duckdb { @@ -32,31 +34,89 @@ struct TryCastBlobToGeometry { } }; +// BLOB -> GEOGRAPHY additionally validates the canonical coordinate ranges, like ST_GeogFromWKB +struct TryCastBlobToGeography { + template + static bool Operation(SRC input, DST &result, Vector &result_vector, CastParameters ¶meters) { + try { + if (!Geometry::FromBinary(input, result, StringVector::GetStringHeap(result_vector), true)) { + return false; + } + } catch (InvalidInputException &ex) { + ErrorData error(ex); + HandleCastError::AssignError("Could not convert BLOB to GEOGRAPHY: " + error.RawMessage(), parameters); + return false; + } + if (!Geometry::IsValidGeography(result)) { + HandleCastError::AssignError("Could not convert BLOB to GEOGRAPHY: coordinates are outside the canonical " + "ranges (longitude/X must be within [-180, 180], latitude/Y within [-90, 90])", + parameters); + return false; + } + return true; + } +}; + BoundCastInfo DefaultCasts::BlobToGeoCast(BindCastInput &input, const LogicalType &source, const LogicalType &target) { + if (target.id() == LogicalTypeId::GEOGRAPHY) { + return BoundCastInfo(&VectorCastHelpers::TryCastStringLoop); + } return BoundCastInfo(&VectorCastHelpers::TryCastStringLoop); } +// Validating reinterpret cast used for GEOMETRY -> GEOGRAPHY: the WKB representation is unchanged, but every +// geometry must lie within the canonical GEOGRAPHY coordinate ranges. Out-of-range rows error (CAST) or NULL +// (TRY_CAST). +static bool GeometryToGeographyCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters) { + bool success = true; + UnaryExecutor::Execute(source, result, count, [&](const string_t &input) -> optional { + if (!Geometry::IsValidGeography(input)) { + HandleCastError::AssignError( + "Cannot cast GEOMETRY to GEOGRAPHY: coordinates are outside the canonical ranges " + "(longitude/X must be within [-180, 180], latitude/Y within [-90, 90])", + parameters); + success = false; + return optional(); + } + return optional(input); + }); + // The result strings alias the source WKB blobs, so keep the source heap alive. + StringVector::AddHeapReference(result, source); + return success; +} + +// GEOMETRY/GEOGRAPHY only carry CRS metadata; a CRS-erasing or CRS-preserving cast keeps the coordinates intact. +// We only reject when both sides carry an explicit, non-equal CRS. +static void CheckCRSCompatible(const LogicalType &source, const LogicalType &target) { + if (GeoType::HasCRS(source) && GeoType::HasCRS(target)) { + auto &source_crs = GeoType::GetCRS(source); + auto &target_crs = GeoType::GetCRS(target); + if (!source_crs.Equals(target_crs)) { + const auto kind_name = [](const LogicalType &type) { + return type.id() == LogicalTypeId::GEOGRAPHY ? "GEOGRAPHY" : "GEOMETRY"; + }; + throw BinderException("Cannot cast %s with CRS '%s' to %s with different CRS '%s'", kind_name(source), + source_crs.GetIdentifier(), kind_name(target), target_crs.GetIdentifier()); + } + } +} + BoundCastInfo DefaultCasts::GeoCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target) { - // now switch on the result type + // Dispatched when the source is GEOMETRY or GEOGRAPHY. Switch on the target type. switch (target.id()) { case LogicalTypeId::VARCHAR: return GeometryToVarcharCast; case LogicalTypeId::BLOB: return GeometryToBlobCast; - case LogicalTypeId::GEOMETRY: { - // If the coordinate reference systems differ, we may not be able to cast - if (GeoType::HasCRS(source) && GeoType::HasCRS(target)) { - auto &target_crs = GeoType::GetCRS(target); - auto &source_crs = GeoType::GetCRS(source); - - // TODO: Use client context (and allow extensions) to determine if the cast is okay (crs's are equivalent) - - if (!source_crs.Equals(target_crs)) { - throw BinderException("Cannot cast GEOMETRY with CRS '" + source_crs.GetIdentifier() + - "' to GEOMETRY with different CRS '" + target_crs.GetIdentifier() + "'"); - } + case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: { + CheckCRSCompatible(source, target); + if (source.id() == LogicalTypeId::GEOMETRY && target.id() == LogicalTypeId::GEOGRAPHY) { + // Explicit GEOMETRY -> GEOGRAPHY: validate that coordinates are within the canonical ranges. + return GeometryToGeographyCast; } - // The actual data representation stays the same, so we can do a reinterpret cast + // GEOMETRY -> GEOMETRY, GEOGRAPHY -> GEOGRAPHY, and GEOGRAPHY -> GEOMETRY: the data representation is + // identical, so we can reinterpret. (GEOGRAPHY -> GEOMETRY needs no validation.) return DefaultCasts::ReinterpretCast; } default: diff --git a/src/duckdb/src/function/cast/string_cast.cpp b/src/duckdb/src/function/cast/string_cast.cpp index 7e3f12e5c..ddd63af1a 100644 --- a/src/duckdb/src/function/cast/string_cast.cpp +++ b/src/duckdb/src/function/cast/string_cast.cpp @@ -500,6 +500,8 @@ BoundCastInfo DefaultCasts::StringCastSwitch(BindCastInput &input, const Logical return BoundCastInfo(&VectorCastHelpers::TryCastStringLoop); case LogicalTypeId::GEOMETRY: return BoundCastInfo(&VectorCastHelpers::TryCastStringLoop); + case LogicalTypeId::GEOGRAPHY: + return BoundCastInfo(&VectorCastHelpers::TryCastStringLoop); case LogicalTypeId::SQLNULL: return &DefaultCasts::TryVectorNullCast; case LogicalTypeId::VARCHAR: diff --git a/src/duckdb/src/function/cast/variant/from_variant.cpp b/src/duckdb/src/function/cast/variant/from_variant.cpp index bce2c050d..e41dd96df 100644 --- a/src/duckdb/src/function/cast/variant/from_variant.cpp +++ b/src/duckdb/src/function/cast/variant/from_variant.cpp @@ -522,6 +522,9 @@ class VariantVarcharSerializer { static bool VisitGeometry(const string_t &, VariantVarcharSerializer &, bool) { return false; } + static bool VisitGeography(const string_t &, VariantVarcharSerializer &, bool) { + return false; + } static bool VisitBitstring(const string_t &, VariantVarcharSerializer &, bool) { return false; } @@ -1191,6 +1194,11 @@ static bool CastVariant(FromVariantConversionData &conversion_data, Vector &resu return CastVariantToPrimitive>( conversion_data, result, sel, offset, count, row, string_payload); } + case LogicalTypeId::GEOGRAPHY: { + StringConversionPayload string_payload(result); + return CastVariantToPrimitive>( + conversion_data, result, sel, offset, count, row, string_payload); + } case LogicalTypeId::VARCHAR: { if (target_type.IsJSONType()) { return CastVariantToJSON(conversion_data, result, sel, offset, count, row); @@ -1375,6 +1383,7 @@ BoundCastInfo DefaultCasts::VariantCastSwitch(BindCastInput &input, const Logica case LogicalTypeId::ARRAY: return BoundCastInfo(CastFromVARIANT, std::move(cast_data)); case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: return BoundCastInfo(CastFromVARIANT, std::move(cast_data)); case LogicalTypeId::VARCHAR: { return BoundCastInfo(CastFromVARIANT, std::move(cast_data)); diff --git a/src/duckdb/src/function/cast/variant/to_json.cpp b/src/duckdb/src/function/cast/variant/to_json.cpp index 891f214d2..f6dc3940f 100644 --- a/src/duckdb/src/function/cast/variant/to_json.cpp +++ b/src/duckdb/src/function/cast/variant/to_json.cpp @@ -127,6 +127,11 @@ struct JSONConverterBase { return yyjson_mut_strncpy(doc, val_str.c_str(), val_str.size()); } + static yyjson_mut_val *VisitGeography(const string_t &str, yyjson_mut_doc *doc) { + auto val_str = Value::GEOGRAPHY(const_data_ptr_cast(str.GetData()), str.GetSize()).ToString(); + return yyjson_mut_strncpy(doc, val_str.c_str(), val_str.size()); + } + static yyjson_mut_val *VisitBitstring(const string_t &str, yyjson_mut_doc *doc) { auto val_str = Value::BIT(const_data_ptr_cast(str.GetData()), str.GetSize()).ToString(); return yyjson_mut_strncpy(doc, val_str.c_str(), val_str.size()); diff --git a/src/duckdb/src/function/cast_rules.cpp b/src/duckdb/src/function/cast_rules.cpp index 2c5dd2da7..78e3ad0e8 100644 --- a/src/duckdb/src/function/cast_rules.cpp +++ b/src/duckdb/src/function/cast_rules.cpp @@ -43,6 +43,10 @@ static int64_t TargetTypeCost(const LogicalType &type) { return 160; case LogicalTypeId::ANY: return int64_t(AnyType::GetCastScore(type)); + case LogicalTypeId::GEOGRAPHY: + // Cost slightly higher than GEOMETRY (default) so that untyped NULL/literal arguments prefer the + // GEOMETRY overload of functions overloaded on both, instead of being ambiguous. + return 111; case LogicalTypeId::TEMPLATE: // we can cast anything to a template type, but prefer to cast to anything else! return 1000000; @@ -422,6 +426,11 @@ int64_t CastRules::ImplicitCast(const LogicalType &from, const LogicalType &to) if (to.id() == LogicalTypeId::VARCHAR && to.GetAlias().empty()) { return 1; } + if (to.id() == LogicalTypeId::GEOGRAPHY) { + // Prefer GEOMETRY over GEOGRAPHY for untyped string literals (see TargetTypeCost), so functions + // overloaded on both resolve unambiguously. + return 21; + } return 20; } if (from.id() == LogicalTypeId::INTEGER_LITERAL) { diff --git a/src/duckdb/src/function/compression_config.cpp b/src/duckdb/src/function/compression_config.cpp index 1fb5cd43c..57d82700a 100644 --- a/src/duckdb/src/function/compression_config.cpp +++ b/src/duckdb/src/function/compression_config.cpp @@ -206,9 +206,8 @@ reference DBConfig::GetCompressionFunction(Compressio const PhysicalType physical_type) const { auto result = compression_functions->GetCompressionFunction(type, physical_type); if (!result) { - throw InternalException( - "Could not find compression function \"%s\" for physical type \"%s\". Load result: %s. %s", - EnumUtil::ToString(type), EnumUtil::ToString(physical_type)); + throw InternalException("Could not find compression function \"%s\" for physical type \"%s\"", + EnumUtil::ToString(type), EnumUtil::ToString(physical_type)); } return *result; } diff --git a/src/duckdb/src/function/copy_blob.cpp b/src/duckdb/src/function/copy_blob.cpp index 0b4360c1c..a0c428d9f 100644 --- a/src/duckdb/src/function/copy_blob.cpp +++ b/src/duckdb/src/function/copy_blob.cpp @@ -64,7 +64,7 @@ struct WriteBlobGlobalState final : public GlobalFunctionData { mutex lock; }; -unique_ptr WriteBlobInitializeGlobal(ClientContext &context, FunctionData &bind_data, +unique_ptr WriteBlobInitializeGlobal(ClientContext &context, const FunctionData &bind_data, const string &file_path) { auto &bdata = bind_data.Cast(); auto &fs = FileSystem::GetFileSystem(context); @@ -83,7 +83,7 @@ unique_ptr WriteBlobInitializeGlobal(ClientContext &context, //---------------------------------------------------------------------------------------------------------------------- struct WriteBlobLocalState final : public LocalFunctionData {}; -unique_ptr WriteBlobInitializeLocal(ExecutionContext &context, FunctionData &bind_data) { +unique_ptr WriteBlobInitializeLocal(ExecutionContext &context, const FunctionData &bind_data) { return make_uniq_base(); } @@ -101,7 +101,7 @@ void WriteBlobData(QueryContext &query_context, FileHandle &handle, data_ptr_t b //---------------------------------------------------------------------------------------------------------------------- // Sink //---------------------------------------------------------------------------------------------------------------------- -void WriteBlobSink(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +void WriteBlobSink(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate, DataChunk &input) { D_ASSERT(input.ColumnCount() == 1); @@ -127,7 +127,7 @@ struct WriteBlobPreparedBatch final : public PreparedBatchData { vector blobs; }; -unique_ptr WriteBlobPrepareBatch(ClientContext &context, FunctionData &bind_data, +unique_ptr WriteBlobPrepareBatch(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, unique_ptr collection) { auto result = make_uniq(); @@ -149,7 +149,7 @@ unique_ptr WriteBlobPrepareBatch(ClientContext &context, Func //---------------------------------------------------------------------------------------------------------------------- // Flush Batch //---------------------------------------------------------------------------------------------------------------------- -void WriteBlobFlushBatch(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +void WriteBlobFlushBatch(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, PreparedBatchData &batch) { auto &state = gstate.Cast(); auto &blob_batch = batch.Cast(); @@ -164,14 +164,14 @@ void WriteBlobFlushBatch(ClientContext &context, FunctionData &bind_data, Global //---------------------------------------------------------------------------------------------------------------------- // Combine //---------------------------------------------------------------------------------------------------------------------- -void WriteBlobCombine(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +void WriteBlobCombine(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate) { } //---------------------------------------------------------------------------------------------------------------------- // Finalize //---------------------------------------------------------------------------------------------------------------------- -void WriteBlobFinalize(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate) { +void WriteBlobFinalize(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate) { auto &state = gstate.Cast(); lock_guard glock(state.lock); diff --git a/src/duckdb/src/function/encoding_function.cpp b/src/duckdb/src/function/encoding_function.cpp index 2d428744e..6e54763ca 100644 --- a/src/duckdb/src/function/encoding_function.cpp +++ b/src/duckdb/src/function/encoding_function.cpp @@ -1,180 +1,202 @@ #include "duckdb/function/encoding_function.hpp" -#include "duckdb/main/config.hpp" -#include "duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp" +#include "duckdb/common/exception.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/common/vector/vector_iterator.hpp" +#include "duckdb/common/vector/vector_writer.hpp" +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp" +#include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" +#include "duckdb/execution/expression_executor.hpp" +#include "duckdb/function/built_in_functions.hpp" +#include "duckdb/function/function_binder.hpp" +#include "duckdb/planner/expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" namespace duckdb { -struct DefaultEncodeMethod { - string name; - encode_t encode_function; - idx_t ratio; - idx_t bytes_per_iteration; -}; - -void DecodeUTF16ToUTF8(CSVEncoderBuffer &encoded_buffer, char *target_buffer, idx_t &target_buffer_current_position, - const idx_t target_buffer_size, char *remaining_bytes_buffer, idx_t &remaining_bytes_size, - EncodingFunction *encoding_function) { - auto encoded_ptr = encoded_buffer.Ptr(); - for (; encoded_buffer.cur_pos < encoded_buffer.actual_encoded_buffer_size; encoded_buffer.cur_pos += 2) { - if (target_buffer_current_position == target_buffer_size) { - // We are done - return; - } - if (encoded_buffer.cur_pos + 1 >= encoded_buffer.actual_encoded_buffer_size) { - if (encoded_buffer.last_buffer) { - throw InvalidInputException("File is not utf-16 encoded"); - } - // the second byte is passed on to the next buffer - return; - } - const uint16_t ch = - static_cast(static_cast(encoded_ptr[encoded_buffer.cur_pos]) | - (static_cast(encoded_ptr[encoded_buffer.cur_pos + 1]) << 8)); - if (ch >= 0xD800 && ch <= 0xDFFF) { - if (ch >= 0xDC00) { - // low surrogate without a preceding high surrogate - throw InvalidInputException("File is not utf-16 encoded"); - } - if (encoded_buffer.cur_pos + 3 >= encoded_buffer.actual_encoded_buffer_size) { - if (encoded_buffer.last_buffer) { - throw InvalidInputException("File is not utf-16 encoded"); - } - // the low surrogate is passed on to the next buffer together with the high surrogate - return; - } - const uint16_t low = - static_cast(static_cast(encoded_ptr[encoded_buffer.cur_pos + 2]) | - (static_cast(encoded_ptr[encoded_buffer.cur_pos + 3]) << 8)); - if (low < 0xDC00 || low > 0xDFFF) { - throw InvalidInputException("File is not utf-16 encoded"); - } - const uint32_t code_point = 0x10000 + ((static_cast(ch - 0xD800)) << 10) + (low - 0xDC00); - const char utf8[4] = { - static_cast(0xF0 | (code_point >> 18)), static_cast(0x80 | ((code_point >> 12) & 0x3F)), - static_cast(0x80 | ((code_point >> 6) & 0x3F)), static_cast(0x80 | (code_point & 0x3F))}; - idx_t written = 0; - while (written < 4 && target_buffer_current_position < target_buffer_size) { - target_buffer[target_buffer_current_position++] = utf8[written++]; - } - if (written < 4) { - // We are done, but we have to store the remaining bytes for the next chunk! - encoded_buffer.cur_pos += 4; - remaining_bytes_size = 0; - for (; written < 4; written++) { - remaining_bytes_buffer[remaining_bytes_size++] = utf8[written]; - } - return; - } - // skip the low surrogate, the loop skips the high surrogate - encoded_buffer.cur_pos += 2; - continue; - } - if (ch <= 0x007F) { - // 1-byte UTF-8 for ASCII characters - target_buffer[target_buffer_current_position++] = static_cast(ch & 0x7F); - } else if (ch <= 0x07FF) { - // 2-byte UTF-8 - target_buffer[target_buffer_current_position++] = static_cast(0xC0 | (ch >> 6)); - if (target_buffer_current_position == target_buffer_size) { - // We are done, but we have to store one byte for the next chunk! - encoded_buffer.cur_pos += 2; - remaining_bytes_buffer[0] = static_cast(0x80 | (ch & 0x3F)); - remaining_bytes_size = 1; - return; - } - target_buffer[target_buffer_current_position++] = static_cast(0x80 | (ch & 0x3F)); - } else { - // 3-byte UTF-8 - target_buffer[target_buffer_current_position++] = static_cast(0xE0 | (ch >> 12)); - if (target_buffer_current_position == target_buffer_size) { - // We are done, but we have to store two bytes for the next chunk! - encoded_buffer.cur_pos += 2; - remaining_bytes_buffer[0] = static_cast(0x80 | ((ch >> 6) & 0x3F)); - remaining_bytes_buffer[1] = static_cast(0x80 | (ch & 0x3F)); - remaining_bytes_size = 2; - return; - } - target_buffer[target_buffer_current_position++] = static_cast(0x80 | ((ch >> 6) & 0x3F)); - if (target_buffer_current_position == target_buffer_size) { - // We are done, but we have to store one byte for the next chunk! - encoded_buffer.cur_pos += 2; - remaining_bytes_buffer[0] = static_cast(0x80 | (ch & 0x3F)); - remaining_bytes_size = 1; - return; - } - target_buffer[target_buffer_current_position++] = static_cast(0x80 | (ch & 0x3F)); - } - } +string EncodingFunction::FunctionName(const string &encoding_name) { + return StringUtil::Lower(encoding_name); } -void DecodeLatin1ToUTF8(CSVEncoderBuffer &encoded_buffer, char *target_buffer, idx_t &target_buffer_current_position, - const idx_t target_buffer_size, char *remaining_bytes_buffer, idx_t &remaining_bytes_size, - EncodingFunction *encoding_function) { - auto encoded_ptr = encoded_buffer.Ptr(); - for (; encoded_buffer.cur_pos < encoded_buffer.actual_encoded_buffer_size; encoded_buffer.cur_pos++) { - if (target_buffer_current_position == target_buffer_size) { - // We are done - return; - } - const unsigned char ch = static_cast(encoded_ptr[encoded_buffer.cur_pos]); - if (ch > 0x7F && ch <= 0x9F) { - throw InvalidInputException("File is not latin-1 encoded"); - } - if (ch <= 0x7F) { - // ASCII: 1 byte in UTF-8 - target_buffer[target_buffer_current_position++] = static_cast(ch); - } else { - // Non-ASCII: 2 bytes in UTF-8 - target_buffer[target_buffer_current_position++] = static_cast(0xc2 + (ch > 0xbf)); - if (target_buffer_current_position == target_buffer_size) { - // We are done, but we have to store one byte for the next chunk! - encoded_buffer.cur_pos++; - remaining_bytes_buffer[0] = static_cast((ch & 0x3f) + 0x80); - remaining_bytes_size = 1; - return; - } - target_buffer[target_buffer_current_position++] = static_cast((ch & 0x3f) + 0x80); - } - } +void EncodingFunction::SetSchema(CreateFunctionInfo &info) { + info.SetQualifiedName( + QualifiedName(Identifier::InvalidCatalog(), Identifier(SCHEMA), info.GetQualifiedName().Name())); } -void DecodeUTF8(CSVEncoderBuffer &encoded_buffer, char *target_buffer, idx_t &target_buffer_current_position, - const idx_t target_buffer_size, char *remaining_bytes_buffer, idx_t &remaining_bytes_size, - EncodingFunction *encoding_function) { - throw InternalException("Decode UTF8 is not a valid function, and should be verified one level up."); +LogicalType EncodingFunction::StreamResultType() { + child_list_t children; + children.emplace_back("decoded", LogicalType::VARCHAR); + children.emplace_back("consumed", LogicalType::BIGINT); + return LogicalType::STRUCT(std::move(children)); } -void EncodingFunctionSet::Initialize(DBConfig &config) { - config.RegisterEncodeFunction({"utf-8", DecodeUTF8, 1, 1}); - config.RegisterEncodeFunction({"latin-1", DecodeLatin1ToUTF8, 2, 1}); - config.RegisterEncodeFunction({"utf-16", DecodeUTF16ToUTF8, 3, 4}); -} +ScalarFunctionSet EncodingFunction::Create(const string &encoding_name, decode_t decode, const encode_t &encode, + idx_t minimum_input_window, idx_t max_output_bytes) { + D_ASSERT(decode && minimum_input_window > 0 && max_output_bytes > 0); + const Identifier name(FunctionName(encoding_name)); -void DBConfig::RegisterEncodeFunction(const EncodingFunction &function) const { - lock_guard l(encoding_functions->lock); - const auto name = function.GetName(); - if (encoding_functions->functions.find(name) != encoding_functions->functions.end()) { - throw InvalidInputException("Decoding function with name %s already registered", name); + ScalarFunction decode_all(name, vector {LogicalType::BLOB}, LogicalType::VARCHAR, + [decode, max_output_bytes](DataChunk &args, ExpressionState &, Vector &result) { + auto inputs = args.data[0].Values(); + auto writer = FlatVector::Writer(result, args.size()); + for (auto entry : inputs) { + if (!entry.IsValid()) { + writer.WriteNull(); + continue; + } + auto input = entry.GetValue(); + const idx_t capacity = input.GetSize() * max_output_bytes; + auto &output = writer.WriteEmptyString(capacity); + idx_t consumed = 0; + idx_t written = 0; + decode(input.GetData(), input.GetSize(), true, output.GetDataWriteable(), + consumed, written); + output.SetSizeAndFinalize(UnsafeNumericCast(written), capacity); + } + }); + decode_all.GetSignature().GetParameter(0).SetName(Identifier("data")); + decode_all.SetFallible(); + decode_all.GetProperties().SetProperty(MINIMUM_INPUT_WINDOW_PROPERTY, + Value::BIGINT(NumericCast(minimum_input_window))); + + ScalarFunction decode_stream( + name, vector {LogicalType::BLOB, LogicalType::BOOLEAN}, StreamResultType(), + [decode, max_output_bytes](DataChunk &args, ExpressionState &, Vector &result) { + auto inputs = args.data[0].Values(); + auto is_last = args.data[1].Values(); + auto writer = FlatVector::Writer>(result, args.size()); + for (auto entry : inputs) { + if (!entry.IsValid() || !is_last[entry.GetIndex()].IsValid()) { + writer.WriteNull(); + continue; + } + auto input = entry.GetValue(); + const bool last = is_last[entry.GetIndex()].GetValue(); + writer.WriteValue([&](auto &decoded_writer, auto &consumed_writer) { + const idx_t capacity = input.GetSize() * max_output_bytes; + auto &output = decoded_writer.WriteEmptyString(capacity); + idx_t consumed = 0; + idx_t written = 0; + decode(input.GetData(), input.GetSize(), last, output.GetDataWriteable(), consumed, written); + output.SetSizeAndFinalize(UnsafeNumericCast(written), capacity); + consumed_writer.WriteValue(UnsafeNumericCast(consumed)); + }); + } + }); + decode_stream.GetSignature().GetParameter(0).SetName(Identifier("data")); + decode_stream.GetSignature().GetParameter(1).SetName(Identifier("is_last")); + decode_stream.SetFallible(); + decode_stream.GetProperties().SetProperty(MINIMUM_INPUT_WINDOW_PROPERTY, + Value::BIGINT(NumericCast(minimum_input_window))); + + ScalarFunctionSet set(name); + set.AddFunction(std::move(decode_all)); + set.AddFunction(std::move(decode_stream)); + if (encode) { + ScalarFunction encode_all(name, vector {LogicalType::VARCHAR}, LogicalType::BLOB, + [encode, minimum_input_window](DataChunk &args, ExpressionState &, Vector &result) { + auto inputs = args.data[0].Values(); + auto writer = FlatVector::Writer(result, args.size()); + for (auto entry : inputs) { + if (!entry.IsValid()) { + writer.WriteNull(); + continue; + } + auto input = entry.GetValue(); + const idx_t capacity = input.GetSize() * minimum_input_window; + auto &output = writer.WriteEmptyString(capacity); + idx_t written = 0; + encode(input.GetData(), input.GetSize(), output.GetDataWriteable(), written); + output.SetSizeAndFinalize(UnsafeNumericCast(written), capacity); + } + }); + encode_all.GetSignature().GetParameter(0).SetName(Identifier("string")); + encode_all.SetFallible(); + encode_all.GetProperties().SetProperty(MINIMUM_INPUT_WINDOW_PROPERTY, + Value::BIGINT(NumericCast(minimum_input_window))); + set.AddFunction(std::move(encode_all)); } - encoding_functions->functions[name] = function; + return set; } -optional_ptr DBConfig::GetEncodeFunction(const string &name) const { - lock_guard l(encoding_functions->lock); - // Check if the function is already loaded into the global compression functions. - if (encoding_functions->functions.find(name) != encoding_functions->functions.end()) { - return &encoding_functions->functions[name]; +optional_ptr EncodingFunction::Find(ClientContext &context, const string &encoding_name) { + // look in the encodings schema directly: the generic lookup would autoload extensions by function name + auto lookup = [&]() -> optional_ptr { + auto transaction = CatalogTransaction::GetSystemCatalogTransaction(context); + auto &schema = Catalog::GetSystemCatalog(context).GetSchema(transaction, Identifier(SCHEMA)); + auto entry = + schema.GetEntry(transaction, CatalogType::SCALAR_FUNCTION_ENTRY, Identifier(FunctionName(encoding_name))); + if (!entry) { + return nullptr; + } + return &entry->Cast(); + }; + auto entry = lookup(); + if (!entry && Catalog::TryAutoLoad(context, "encodings")) { + entry = lookup(); } - return nullptr; + return entry; } -vector> DBConfig::GetLoadedEncodedFunctions() const { - lock_guard l(encoding_functions->lock); - vector> result; - for (auto &function : encoding_functions->functions) { - result.push_back(function.second); +vector EncodingFunction::GetEncodings(ClientContext &context) { + vector result {"utf-8"}; + auto &schema = Catalog::GetSystemCatalog(context).GetSchema(context, Identifier(SCHEMA)); + schema.Scan(context, CatalogType::SCALAR_FUNCTION_ENTRY, [&](CatalogEntry &entry) { + if (entry.type == CatalogType::SCALAR_FUNCTION_ENTRY) { + result.push_back(entry.name.GetIdentifierName()); + } + }); + std::sort(result.begin(), result.end()); + return result; +} + +unique_ptr EncodingFunction::BindCall(ClientContext &context, vector> &children, + bool is_encode) { + D_ASSERT(children.size() == 2); + if (children[1]->HasParameter()) { + throw ParameterNotResolvedException(); + } + if (!children[1]->IsFoldable()) { + if (is_encode) { + throw BinderException("encode: the encoding must be a constant"); + } + return nullptr; + } + auto value = ExpressionExecutor::EvaluateScalar(context, *children[1]); + if (value.IsNull()) { + if (is_encode) { + return make_uniq(Value(LogicalType::BLOB)); + } + return nullptr; + } + auto encoding_name = StringUtil::Lower(value.ToString()); + if (!is_encode && (encoding_name == "strict" || encoding_name == "replace" || encoding_name == "ignore")) { + // the error option of decode + return nullptr; + } + vector> arguments; + arguments.push_back(std::move(children[0])); + FunctionBinder binder(context); + if (encoding_name == "utf-8") { + return binder.BindScalarFunction(Identifier::DefaultSchema(), Identifier(is_encode ? "encode" : "decode"), + std::move(arguments)); + } + auto entry = Find(context, encoding_name); + if (!entry) { + string error = + StringUtil::Format("Unknown encoding \"%s\". The currently supported encodings are:", value.ToString()); + for (auto &name : GetEncodings(context)) { + error += "\n* " + name; + } + throw BinderException(error); + } + ErrorData error; + auto result = binder.BindScalarFunction(*entry, std::move(arguments), error); + if (!result) { + error.Throw(); } return result; } + } // namespace duckdb diff --git a/src/duckdb/src/function/function.cpp b/src/duckdb/src/function/function.cpp index be7baa9cb..3fea985a0 100644 --- a/src/duckdb/src/function/function.cpp +++ b/src/duckdb/src/function/function.cpp @@ -7,6 +7,10 @@ #include "duckdb/function/function_binder.hpp" #include "duckdb/function/scalar/string_functions.hpp" #include "duckdb/function/scalar_function.hpp" +#include "duckdb/planner/collation_binding.hpp" +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/parser/parsed_data/create_schema_info.hpp" +#include "duckdb/parser/parsed_data/create_scalar_function_info.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/common/types/decimal.hpp" @@ -112,7 +116,41 @@ bool FunctionProperties::operator==(const FunctionProperties &rhs) const { return stability == rhs.stability && null_handling == rhs.null_handling && errors == rhs.errors && collation_handling == rhs.collation_handling && capture_argument_aliases == rhs.capture_argument_aliases && requires_expression_names == rhs.requires_expression_names && - requires_ordered_execution == rhs.requires_ordered_execution; + requires_ordered_execution == rhs.requires_ordered_execution && GenericPropertiesEqual(rhs); +} + +bool FunctionProperties::GenericPropertiesEqual(const FunctionProperties &rhs) const { + if (generic_properties.size() != rhs.generic_properties.size()) { + return false; + } + for (auto &entry : generic_properties) { + auto other = rhs.GetProperty(entry.first); + if (!other || !Value::NotDistinctFrom(entry.second, *other)) { + return false; + } + } + return true; +} + +void FunctionProperties::SetProperty(const string &name, Value value) { + generic_properties[name] = std::move(value); +} + +optional_ptr FunctionProperties::GetProperty(const string &name) const { + auto entry = generic_properties.find(name); + if (entry == generic_properties.end()) { + return nullptr; + } + return &entry->second; +} + +bool FunctionProperties::GetBooleanProperty(const string &name) const { + auto value = GetProperty(name); + // only a BOOLEAN value is a flag - anything else reads as false rather than failing every lookup + if (!value || value->IsNull() || value->type().id() != LogicalTypeId::BOOLEAN) { + return false; + } + return BooleanValue::Get(*value); } bool FunctionProperties::operator!=(const FunctionProperties &rhs) const { @@ -258,6 +296,31 @@ string SimpleFunction::ToString() const { } // add your initializer for new functions here +void BuiltinFunctions::AddCollation(const string &name, ScalarFunction function, bool combinable) { + function.SetName(Identifier(name)); + if (combinable) { + CollationFunctions::SetCombinable(function); + } + CreateScalarFunctionInfo info(std::move(function)); + info.SetQualifiedName( + QualifiedName(info.GetQualifiedName().Catalog(), CollationFunctions::GetSchema(), info.GetFunctionName())); + info.internal = true; + catalog.CreateFunction(transaction, info); +} + +void BuiltinFunctions::RegisterCollations() { + // the collations are the scalar functions of their own schema + CreateSchemaInfo schema; + schema.SetQualifiedName(QualifiedName({CollationFunctions::GetSchema()}, Identifier())); + schema.internal = true; + schema.on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; + catalog.CreateSchema(transaction, schema); + + AddCollation("nocase", LowerFun::GetFunction(), true); + AddCollation("noaccent", StripAccentsFun::GetFunction(), true); + AddCollation("nfc", NFCNormalizeFun::GetFunction()); +} + void BuiltinFunctions::Initialize() { RegisterTableScanFunctions(); RegisterSQLiteFunctions(); @@ -269,10 +332,9 @@ void BuiltinFunctions::Initialize() { RegisterCopyFunctions(); - // initialize collations - AddCollation("nocase", LowerFun::GetFunction(), true); - AddCollation("noaccent", StripAccentsFun::GetFunction(), true); - AddCollation("nfc", NFCNormalizeFun::GetFunction()); + RegisterCollations(); + + RegisterEncodingFunctions(); RegisterExtensionOverloads(); } diff --git a/src/duckdb/src/function/function_binder.cpp b/src/duckdb/src/function/function_binder.cpp index aac4f4a5f..1214c720a 100644 --- a/src/duckdb/src/function/function_binder.cpp +++ b/src/duckdb/src/function/function_binder.cpp @@ -1541,7 +1541,7 @@ FunctionBinder::ResolveScalarFunction(const FunctionBinding &binding, vectorGetStatementProperties(); - FunctionModifiedDatabasesInput input(bind_info, properties); + FunctionModifiedDatabasesInput input(bind_info.get(), properties); bound_function.GetModifiedDatabasesCallback()(context, input); } diff --git a/src/duckdb/src/function/function_list.cpp b/src/duckdb/src/function/function_list.cpp index 731853f91..e066fb216 100644 --- a/src/duckdb/src/function/function_list.cpp +++ b/src/duckdb/src/function/function_list.cpp @@ -88,7 +88,7 @@ static const StaticFunctionDefinition function[] = { DUCKDB_SCALAR_FUNCTION(NotLikeFun), DUCKDB_SCALAR_FUNCTION(NotILikeFun), DUCKDB_SCALAR_FUNCTION_SET(OperatorModuloFun), - DUCKDB_SCALAR_FUNCTION_ALIAS(StIntersectsExtentFunAlias), + DUCKDB_SCALAR_FUNCTION_SET_ALIAS(StIntersectsExtentFunAlias), DUCKDB_SCALAR_FUNCTION_SET(OperatorMultiplyFun), DUCKDB_SCALAR_FUNCTION_SET(OperatorAddFun), DUCKDB_SCALAR_FUNCTION_SET(OperatorSubtractFun), @@ -240,14 +240,15 @@ static const StaticFunctionDefinition function[] = { DUCKDB_SCALAR_FUNCTION_SET(SHA1Fun), DUCKDB_SCALAR_FUNCTION_SET(SHA256Fun), DUCKDB_SCALAR_FUNCTION_ALIAS(SplitFun), - DUCKDB_SCALAR_FUNCTION_ALIAS(StAsbinaryFun), - DUCKDB_SCALAR_FUNCTION(StAstextFun), - DUCKDB_SCALAR_FUNCTION(StAswkbFun), - DUCKDB_SCALAR_FUNCTION_ALIAS(StAswktFun), - DUCKDB_SCALAR_FUNCTION(StCrsFun), + DUCKDB_SCALAR_FUNCTION_SET_ALIAS(StAsbinaryFun), + DUCKDB_SCALAR_FUNCTION_SET(StAstextFun), + DUCKDB_SCALAR_FUNCTION_SET(StAswkbFun), + DUCKDB_SCALAR_FUNCTION_SET_ALIAS(StAswktFun), + DUCKDB_SCALAR_FUNCTION_SET(StCrsFun), + DUCKDB_SCALAR_FUNCTION(StGeogfromwkbFun), DUCKDB_SCALAR_FUNCTION(StGeomfromwkbFun), - DUCKDB_SCALAR_FUNCTION(StIntersectsExtentFun), - DUCKDB_SCALAR_FUNCTION(StSetcrsFun), + DUCKDB_SCALAR_FUNCTION_SET(StIntersectsExtentFun), + DUCKDB_SCALAR_FUNCTION_SET(StSetcrsFun), DUCKDB_SCALAR_FUNCTION_ALIAS(StrSplitFun), DUCKDB_SCALAR_FUNCTION_SET_ALIAS(StrSplitRegexFun), DUCKDB_SCALAR_FUNCTION_SET(StrfTimeFun), @@ -284,7 +285,7 @@ static const StaticFunctionDefinition function[] = { DUCKDB_SCALAR_FUNCTION(VariantNormalizeFun), DUCKDB_SCALAR_FUNCTION_SET(VariantTypeFun), DUCKDB_SCALAR_FUNCTION(VariantTypeofFun), - DUCKDB_SCALAR_FUNCTION(VertexExtractFun), + DUCKDB_SCALAR_FUNCTION_SET(VertexExtractFun), DUCKDB_SCALAR_FUNCTION_SET(WriteLogFun), DUCKDB_SCALAR_FUNCTION(ConcatOperatorFun), DUCKDB_SCALAR_FUNCTION(LikeFun), diff --git a/src/duckdb/src/function/macro_function.cpp b/src/duckdb/src/function/macro_function.cpp index 281bae58b..524e0c7cd 100644 --- a/src/duckdb/src/function/macro_function.cpp +++ b/src/duckdb/src/function/macro_function.cpp @@ -50,8 +50,12 @@ MacroBindResult MacroFunction::BindMacroFunction( Binder &binder, const vector> &functions, const Identifier &name, FunctionExpression &function_expr, vector> &positional_arguments, InsertionOrderPreservingMap, Identifier, identifier_map_t> &named_arguments, - idx_t depth) { + idx_t depth, optional_ptr calling_binder) { ExpressionBinder expr_binder(binder, binder.context); + if (calling_binder) { + // binding an argument can expand the macro again: continue the expression depth of the call + expr_binder.ContinueStackDepth(*calling_binder); + } expr_binder.lambda_bindings = binder.lambda_bindings; // Figure out whether we even need to bind arguments diff --git a/src/duckdb/src/function/scalar/comparison/between.cpp b/src/duckdb/src/function/scalar/comparison/between.cpp index 07af88c26..f2ed539c2 100644 --- a/src/duckdb/src/function/scalar/comparison/between.cpp +++ b/src/duckdb/src/function/scalar/comparison/between.cpp @@ -1,4 +1,6 @@ #include "duckdb/common/serializer/deserializer.hpp" +#include "duckdb/execution/expression_executor.hpp" +#include "duckdb/execution/expression_executor_state.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/smaller_binary.hpp" #include "duckdb/common/vector_operations/unary_executor.hpp" @@ -7,56 +9,50 @@ #include "duckdb/parser/expression/between_expression.hpp" #include "duckdb/parser/expression/comparison_expression.hpp" #include "duckdb/planner/expression/bound_between_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/legacy_bound_between_expression.hpp" namespace duckdb { struct BetweenFunctionData : public FunctionData { - BetweenFunctionData(bool lower_inclusive, bool upper_inclusive) - : lower_inclusive(lower_inclusive), upper_inclusive(upper_inclusive) { + BetweenFunctionData(bool lower_inclusive, bool upper_inclusive, unique_ptr comparison) + : lower_inclusive(lower_inclusive), upper_inclusive(upper_inclusive), comparison(std::move(comparison)) { } bool lower_inclusive; bool upper_inclusive; + //! "input lower AND input upper" over the (input, lower, upper) arguments + unique_ptr comparison; public: unique_ptr Copy() const override { - return make_uniq(lower_inclusive, upper_inclusive); + return make_uniq(lower_inclusive, upper_inclusive, comparison->Copy()); }; bool Equals(const FunctionData &other_p) const override { auto &other = other_p.Cast(); - return lower_inclusive == other.lower_inclusive && upper_inclusive == other.upper_inclusive; + return lower_inclusive == other.lower_inclusive && upper_inclusive == other.upper_inclusive && + comparison->Equals(*other.comparison); } }; -void BetweenFunction(DataChunk &args, ExpressionState &state, Vector &result) { - auto &between_expr = state.expr.Cast(); - bool upper_inclusive = BoundBetweenExpression::UpperInclusive(between_expr); - bool lower_inclusive = BoundBetweenExpression::LowerInclusive(between_expr); +struct BetweenLocalState : public FunctionLocalState { + BetweenLocalState(Context &context, const BetweenFunctionData &data) : executor(context, *data.comparison) { + } - Vector intermediate1(LogicalType::BOOLEAN); - Vector intermediate2(LogicalType::BOOLEAN); + ExpressionExecutor executor; +}; - const auto &input = args.data[0]; - const auto &lower = args.data[1]; - const auto &upper = args.data[2]; +static unique_ptr BetweenInitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, + optional_ptr bind_data) { + return make_uniq(state.GetContext(), bind_data->Cast()); +} - if (upper_inclusive && lower_inclusive) { - VectorOperations::GreaterThanEquals(input, lower, intermediate1); - VectorOperations::LessThanEquals(input, upper, intermediate2); - } else if (lower_inclusive) { - VectorOperations::GreaterThanEquals(input, lower, intermediate1); - VectorOperations::LessThan(input, upper, intermediate2); - } else if (upper_inclusive) { - VectorOperations::GreaterThan(input, lower, intermediate1); - VectorOperations::LessThanEquals(input, upper, intermediate2); - } else { - VectorOperations::GreaterThan(input, lower, intermediate1); - VectorOperations::LessThan(input, upper, intermediate2); - } - VectorOperations::And(intermediate1, intermediate2, result); +void BetweenFunction(DataChunk &args, ExpressionState &state, Vector &result) { + auto &lstate = ExecuteFunctionState::GetFunctionState(state)->Cast(); + lstate.executor.ExecuteExpression(args, result); } #if !DUCKDB_SMALLER_BINARY(between_select) @@ -101,33 +97,12 @@ struct ExclusiveBetweenOperator { }; template -static idx_t BetweenSelectGeneric(const Vector &input, const Vector &lower, const Vector &upper, - optional_ptr sel, idx_t count, - optional_ptr true_sel, optional_ptr false_sel) { - // fallback for types without a templated select path (e.g. nested types): - // evaluate the boolean result like the execute path and turn it into a selection - Vector intermediate1(LogicalType::BOOLEAN); - Vector intermediate2(LogicalType::BOOLEAN); - Vector result(LogicalType::BOOLEAN); - if (OP::LOWER_INCLUSIVE) { - VectorOperations::GreaterThanEquals(input, lower, intermediate1); - } else { - VectorOperations::GreaterThan(input, lower, intermediate1); - } - if (OP::UPPER_INCLUSIVE) { - VectorOperations::LessThanEquals(input, upper, intermediate2); - } else { - VectorOperations::LessThan(input, upper, intermediate2); - } - VectorOperations::And(intermediate1, intermediate2, result); - return UnaryExecutor::Select( - result, sel.get(), count, [](bool value) { return value; }, true_sel.get(), false_sel.get()); -} - -template -static idx_t BetweenLoopTypeSwitch(const Vector &input, const Vector &lower, const Vector &upper, - optional_ptr sel, idx_t count, - optional_ptr true_sel, optional_ptr false_sel) { +static idx_t BetweenLoopTypeSwitch(BetweenLocalState &lstate, DataChunk &args, optional_ptr sel, + idx_t count, optional_ptr true_sel, + optional_ptr false_sel) { + const auto &input = args.data[0]; + const auto &lower = args.data[1]; + const auto &upper = args.data[2]; switch (input.GetType().InternalType()) { case PhysicalType::BOOL: case PhysicalType::INT8: @@ -171,8 +146,13 @@ static idx_t BetweenLoopTypeSwitch(const Vector &input, const Vector &lower, con case PhysicalType::INTERVAL: return TernaryExecutor::Select(input, lower, upper, sel, count, true_sel, false_sel); - default: - return BetweenSelectGeneric(input, lower, upper, sel, count, true_sel, false_sel); + default: { + // types without a templated select path (e.g. nested types): the arguments are dense, 'sel' maps their rows + Vector result(LogicalType::BOOLEAN); + lstate.executor.ExecuteExpression(args, result); + return UnaryExecutor::Select( + result, sel.get(), count, [](bool value) { return value; }, true_sel.get(), false_sel.get()); + } } } @@ -182,35 +162,39 @@ idx_t BetweenSelect(DataChunk &args, ExpressionState &state, optional_ptrCast(); auto count = args.size(); if (upper_inclusive && lower_inclusive) { - return BetweenLoopTypeSwitch(input, lower, upper, sel, count, true_sel, - false_sel); + return BetweenLoopTypeSwitch(lstate, args, sel, count, true_sel, false_sel); } else if (lower_inclusive) { - return BetweenLoopTypeSwitch(input, lower, upper, sel, count, true_sel, - false_sel); + return BetweenLoopTypeSwitch(lstate, args, sel, count, true_sel, false_sel); } else if (upper_inclusive) { - return BetweenLoopTypeSwitch(input, lower, upper, sel, count, true_sel, - false_sel); + return BetweenLoopTypeSwitch(lstate, args, sel, count, true_sel, false_sel); } else { - return BetweenLoopTypeSwitch(input, lower, upper, sel, count, true_sel, false_sel); + return BetweenLoopTypeSwitch(lstate, args, sel, count, true_sel, false_sel); } } #endif -unique_ptr BoundBetweenExpression::Create(unique_ptr input, unique_ptr lower, - unique_ptr upper, bool lower_inclusive, - bool upper_inclusive) { +unique_ptr BoundBetweenExpression::Create(ClientContext &context, unique_ptr input, + unique_ptr lower, unique_ptr upper, + bool lower_inclusive, bool upper_inclusive) { vector> children; children.push_back(std::move(input)); children.push_back(std::move(lower)); children.push_back(std::move(upper)); - auto function_data = make_uniq(lower_inclusive, upper_inclusive); + auto &input_type = children[0]->GetReturnType(); + auto lower_comparison = BoundComparisonExpression::CreateOnColumns( + context, BoundBetweenExpression::LowerComparisonType(lower_inclusive), input_type, 0, + children[1]->GetReturnType(), 1); + auto upper_comparison = BoundComparisonExpression::CreateOnColumns( + context, BoundBetweenExpression::UpperComparisonType(upper_inclusive), input_type, 0, + children[2]->GetReturnType(), 2); + auto comparison = make_uniq(ExpressionType::CONJUNCTION_AND, + std::move(lower_comparison), std::move(upper_comparison)); + auto function_data = make_uniq(lower_inclusive, upper_inclusive, std::move(comparison)); auto result = make_uniq(BoundScalarFunction(BetweenFun::GetFunction()), std::move(children), std::move(function_data), false); @@ -246,17 +230,19 @@ unique_ptr BetweenLegacySerializeCallback(FunctionToStringInput &inp between_info.upper_inclusive); } -void BetweenFunctionSerialize(Serializer &serializer, const optional_ptr bind_data_p, +void BetweenFunctionSerialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundScalarFunction &function) { auto &bind_data = bind_data_p->Cast(); serializer.WriteProperty(100, "lower_inclusive", bind_data.lower_inclusive); serializer.WriteProperty(101, "upper_inclusive", bind_data.upper_inclusive); + serializer.WriteProperty(102, "comparison", bind_data.comparison); } unique_ptr BetweenFunctionDeserialize(Deserializer &deserializer, BoundScalarFunction &function) { auto lower_inclusive = deserializer.ReadProperty(100, "lower_inclusive"); auto upper_inclusive = deserializer.ReadProperty(101, "upper_inclusive"); - return make_uniq(lower_inclusive, upper_inclusive); + auto comparison = deserializer.ReadProperty>(102, "comparison"); + return make_uniq(lower_inclusive, upper_inclusive, std::move(comparison)); } ScalarFunction BetweenFun::GetFunction() { @@ -269,6 +255,7 @@ ScalarFunction BetweenFun::GetFunction() { between_fun.SetToStringCallback(BetweenToString); between_fun.SetGetExpressionTypeCallback(BetweenGetExpressionType); between_fun.SetLegacySerializeCallback(BetweenLegacySerializeCallback); + between_fun.SetInitStateCallback(BetweenInitLocalState); between_fun.SetSerializeCallback(BetweenFunctionSerialize); between_fun.SetDeserializeCallback(BetweenFunctionDeserialize); #if !DUCKDB_SMALLER_BINARY(between_select) diff --git a/src/duckdb/src/function/scalar/comparison/comparison.cpp b/src/duckdb/src/function/scalar/comparison/comparison.cpp index 84c12509e..0224d458f 100644 --- a/src/duckdb/src/function/scalar/comparison/comparison.cpp +++ b/src/duckdb/src/function/scalar/comparison/comparison.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/type_visitor.hpp" #include "duckdb/common/enums/expression_type.hpp" #include "duckdb/common/smaller_binary.hpp" #include "duckdb/function/scalar/comparison_functions.hpp" @@ -6,10 +7,17 @@ #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/planner/expression_binder.hpp" namespace duckdb { +bool BoundComparisonExpression::EqualityPreservesValueRepresentation(const LogicalType &type) { + return !TypeVisitor::Contains(type, [](const LogicalType &child) { + return child.IsFloating() || child.id() == LogicalTypeId::INTERVAL || child.id() == LogicalTypeId::VARIANT; + }); +} + template void ComparisonFunction(DataChunk &args, ExpressionState &state, Vector &result) { (void)state; @@ -96,7 +104,7 @@ static unique_ptr ComparisonBind(BindScalarFunctionInput &input) { } //! The arguments of a deserialized comparison have already been cast - so it should not be bound again -static void ComparisonSerialize(Serializer &serializer, const optional_ptr bind_data, +static void ComparisonSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { } @@ -180,6 +188,14 @@ ScalarFunction IsNotDistinctFromFun::GetFunction() { //===--------------------------------------------------------------------===// // BoundComparisonExpression //===--------------------------------------------------------------------===// +unique_ptr BoundComparisonExpression::CreateOnColumns(ClientContext &context, ExpressionType type, + const LogicalType &left_type, idx_t left_idx, + const LogicalType &right_type, idx_t right_idx) { + (void)context; + return Create(type, make_uniq(left_type, left_idx), + make_uniq(right_type, right_idx)); +} + unique_ptr BoundComparisonExpression::Create(ExpressionType type, unique_ptr left, unique_ptr right) { vector> children; diff --git a/src/duckdb/src/function/scalar/compressed_materialization/compress_geometry.cpp b/src/duckdb/src/function/scalar/compressed_materialization/compress_geometry.cpp index 827f7e287..9551d9666 100644 --- a/src/duckdb/src/function/scalar/compressed_materialization/compress_geometry.cpp +++ b/src/duckdb/src/function/scalar/compressed_materialization/compress_geometry.cpp @@ -82,7 +82,7 @@ void GeometryPointDecompressFunction(DataChunk &args, ExpressionState &state, Ve } } -void CMGeometryPointCompressSerialize(Serializer &serializer, const optional_ptr bind_data, +void CMGeometryPointCompressSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { serializer.WriteProperty(100, "arguments", function.GetArguments()); serializer.WriteProperty(101, "return_type", function.GetReturnType()); @@ -95,7 +95,7 @@ unique_ptr CMGeometryPointCompressDeserialize(Deserializer &deseri return nullptr; } -void CMGeometryPointDecompressSerialize(Serializer &serializer, const optional_ptr bind_data, +void CMGeometryPointDecompressSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { serializer.WriteProperty(100, "arguments", function.GetArguments()); serializer.WriteProperty(101, "return_type", function.GetReturnType()); diff --git a/src/duckdb/src/function/scalar/compressed_materialization/compress_integral.cpp b/src/duckdb/src/function/scalar/compressed_materialization/compress_integral.cpp index 05806a431..0bc6b5390 100644 --- a/src/duckdb/src/function/scalar/compressed_materialization/compress_integral.cpp +++ b/src/duckdb/src/function/scalar/compressed_materialization/compress_integral.cpp @@ -187,7 +187,7 @@ scalar_function_t GetIntegralDecompressFunctionInputSwitch(const LogicalType &in } } -void CMIntegralSerialize(Serializer &serializer, const optional_ptr bind_data, +void CMIntegralSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { serializer.WriteProperty(100, "arguments", function.GetArguments()); serializer.WriteProperty(101, "return_type", function.GetReturnType()); diff --git a/src/duckdb/src/function/scalar/compressed_materialization/compress_string.cpp b/src/duckdb/src/function/scalar/compressed_materialization/compress_string.cpp index 434a250dd..6f0dcc14e 100644 --- a/src/duckdb/src/function/scalar/compressed_materialization/compress_string.cpp +++ b/src/duckdb/src/function/scalar/compressed_materialization/compress_string.cpp @@ -126,7 +126,7 @@ struct StringDecompressLocalState : public FunctionLocalState { } static unique_ptr Init(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { return make_uniq(state.GetContext()); } @@ -215,7 +215,7 @@ scalar_function_t GetStringDecompressFunctionSwitch(const LogicalType &input_typ } } -void CMStringCompressSerialize(Serializer &serializer, const optional_ptr bind_data, +void CMStringCompressSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { serializer.WriteProperty(100, "arguments", function.GetArguments()); serializer.WriteProperty(101, "return_type", function.GetReturnType()); @@ -228,7 +228,7 @@ unique_ptr CMStringCompressDeserialize(Deserializer &deserializer, return nullptr; } -void CMStringDecompressSerialize(Serializer &serializer, const optional_ptr bind_data, +void CMStringDecompressSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { serializer.WriteProperty(100, "arguments", function.GetArguments()); } diff --git a/src/duckdb/src/function/scalar/create_sort_key.cpp b/src/duckdb/src/function/scalar/create_sort_key.cpp index 5ca15fcc4..82d40bd19 100644 --- a/src/duckdb/src/function/scalar/create_sort_key.cpp +++ b/src/duckdb/src/function/scalar/create_sort_key.cpp @@ -452,12 +452,12 @@ struct SortKeyChunk { // Get Sort Key Length //===--------------------------------------------------------------------===// struct SortKeyLengthInfo { - explicit SortKeyLengthInfo(idx_t size) : constant_length(0) { - variable_lengths.resize(size, 0); + SortKeyLengthInfo(unsafe_vector &lengths, idx_t size) : constant_length(0), variable_lengths(lengths) { + variable_lengths.assign(size, 0); } idx_t constant_length; - unsafe_vector variable_lengths; + unsafe_vector &variable_lengths; }; static void GetSortKeyLengthRecursive(SortKeyVectorData &vector_data, SortKeyChunk chunk, SortKeyLengthInfo &result); @@ -867,24 +867,25 @@ void FinalizeSortData(Vector &result, idx_t size, const SortKeyLengthInfo &key_l void CreateSortKeyInternal(vector> &sort_key_data, const vector &modifiers, const bool &all_constant, Vector &result, - idx_t row_count) { + idx_t row_count, CreateSortKeyState &state) { // two phases // a) get the length of the final sorted key // b) allocate the sorted key and construct // we do all of this in a vectorized manner - SortKeyLengthInfo key_lengths(row_count); + SortKeyLengthInfo key_lengths(state.lengths, row_count); for (auto &vector_data : sort_key_data) { GetSortKeyLength(*vector_data, key_lengths); } // allocate the empty sort keys - auto data_pointers = unique_ptr(new data_ptr_t[row_count]); - PrepareSortData(result, row_count, key_lengths, data_pointers.get(), all_constant); + auto &data_pointers = state.data_pointers; + data_pointers.resize(row_count); + PrepareSortData(result, row_count, key_lengths, data_pointers.data(), all_constant); - unsafe_vector offsets; - offsets.resize(row_count, 0); + auto &offsets = state.offsets; + offsets.assign(row_count, 0); // now construct the sort keys for (idx_t c = 0; c < sort_key_data.size(); c++) { - SortKeyConstructInfo info(modifiers[c], offsets, data_pointers.get()); + SortKeyConstructInfo info(modifiers[c], offsets, data_pointers.data()); ConstructSortKey(*sort_key_data[c], info); } FinalizeSortData(result, row_count, key_lengths, offsets); @@ -956,30 +957,38 @@ static void AssertSortKeyRoundTrip(vector> &sort_k } // namespace void CreateSortKeyHelpers::CreateSortKey(const Vector &input, OrderModifiers order_modifier, Vector &result) { + CreateSortKeyState state; // prepare the sort key data const auto input_count = input.size(); vector modifiers {order_modifier}; vector> sort_key_data; sort_key_data.push_back(make_uniq(input, input_count, order_modifier)); - CreateSortKeyInternal(sort_key_data, modifiers, false, result, input_count); + CreateSortKeyInternal(sort_key_data, modifiers, false, result, input_count, state); } void CreateSortKeyHelpers::CreateSortKey(DataChunk &input, const vector &modifiers, Vector &result) { + CreateSortKeyState state; + CreateSortKey(input, modifiers, result, state); +} + +void CreateSortKeyHelpers::CreateSortKey(DataChunk &input, const vector &modifiers, Vector &result, + CreateSortKeyState &state) { vector> sort_key_data; D_ASSERT(modifiers.size() == input.ColumnCount()); for (idx_t r = 0; r < modifiers.size(); r++) { sort_key_data.push_back(make_uniq(input.data[r], input.size(), modifiers[r])); } - CreateSortKeyInternal(sort_key_data, modifiers, false, result, input.size()); + CreateSortKeyInternal(sort_key_data, modifiers, false, result, input.size(), state); } void CreateSortKeyHelpers::CreateSortKey(const Vector &input, idx_t input_count, OrderModifiers order_modifier, Vector &result) { + CreateSortKeyState state; vector modifiers {order_modifier}; vector> sort_key_data; sort_key_data.push_back(make_uniq(input, input_count, order_modifier)); - CreateSortKeyInternal(sort_key_data, modifiers, false, result, input_count); + CreateSortKeyInternal(sort_key_data, modifiers, false, result, input_count, state); } void CreateSortKeyHelpers::CreateSortKeyWithValidity(const Vector &input, Vector &result, @@ -1013,6 +1022,11 @@ void CreateSortKeyHelpers::CreateSortKeyWithValidity(const Vector &input, Vector } } +static unique_ptr InitCreateSortKeyState(ExpressionState &, const BoundFunctionExpression &, + optional_ptr) { + return make_uniq(); +} + static void CreateSortKeyFunction(DataChunk &args, ExpressionState &state, Vector &result) { auto &bind_data = state.expr.Cast().BindInfo()->Cast(); @@ -1021,12 +1035,23 @@ static void CreateSortKeyFunction(DataChunk &args, ExpressionState &state, Vecto for (idx_t c = 0; c < args.ColumnCount(); c += 2) { sort_key_data.push_back(make_uniq(args.data[c], args.size(), bind_data.modifiers[c / 2])); } - CreateSortKeyInternal(sort_key_data, bind_data.modifiers, bind_data.all_constant, result, args.size()); + auto &key_state = ExecuteFunctionState::GetFunctionState(state)->Cast(); + CreateSortKeyInternal(sort_key_data, bind_data.modifiers, bind_data.all_constant, result, args.size(), key_state); #ifdef DEBUG AssertSortKeyRoundTrip(sort_key_data, bind_data.modifiers, result, args.size()); #endif } +bool CreateSortKeyHelpers::IsNonNullSortKey(const Expression &expression) { + if (expression.GetExpressionClass() != ExpressionClass::BOUND_FUNCTION) { + return false; + } + auto &function = expression.Cast().Function(); + return function.GetBindCallback() == CreateSortKeyBind && + function.GetNullHandling() == FunctionNullHandling::SPECIAL_HANDLING && + function.GetProperties().GetBooleanProperty(NON_NULL_RESULT_PROPERTY); +} + //===--------------------------------------------------------------------===// // Decode Sort Key //===--------------------------------------------------------------------===// @@ -1159,6 +1184,17 @@ struct DecodeSortKeyData { } }; +struct DecodeSortKeyState : FunctionLocalState { + vector rows; + vector swapped; + vector columns; +}; + +static unique_ptr InitDecodeSortKeyState(ExpressionState &, const BoundFunctionExpression &, + optional_ptr) { + return make_uniq(); +} + void DecodeSortKeyRecursive(DecodeSortKeyData decode_data[], DecodeSortKeyVectorData &vector_data, Vector &result, idx_t result_offset, idx_t count); @@ -1440,8 +1476,10 @@ static void DecodeSortKeyFunction(DataChunk &args, ExpressionState &state, Vecto // However, all the actual values should be valid, so we assert that // Construct utility for all sort keys that we will decode - vector decode_data(count); - vector bswapped_ints(count); + auto &decode_state = ExecuteFunctionState::GetFunctionState(state)->Cast(); + auto &decode_data = decode_state.rows; + auto &bswapped_ints = decode_state.swapped; + decode_data.resize(count); if (sort_key_vec.GetType() == LogicalType::BLOB) { const auto sort_keys = UnifiedVectorFormat::GetData(sort_key_vec_format); if (sort_key_vec_format.sel->IsSet()) { @@ -1458,6 +1496,7 @@ static void DecodeSortKeyFunction(DataChunk &args, ExpressionState &state, Vecto } } else { D_ASSERT(sort_key_vec.GetType() == LogicalType::BIGINT); + bswapped_ints.resize(count); const auto sort_keys = UnifiedVectorFormat::GetData(sort_key_vec_format); if (sort_key_vec_format.sel->IsSet()) { for (idx_t i = 0; i < count; i++) { @@ -1480,8 +1519,10 @@ static void DecodeSortKeyFunction(DataChunk &args, ExpressionState &state, Vecto auto &child_vectors = StructVector::GetEntries(result); for (idx_t c = 0; c < StructType::GetChildCount(result_type); c++) { auto &child_vector = child_vectors[c]; - DecodeSortKeyVectorData sort_key_data(child_vector.GetType(), bind_data.modifiers[c]); - DecodeSortKeyRecursive(decode_data.data(), sort_key_data, child_vector, 0, count); + if (c == decode_state.columns.size()) { + decode_state.columns.emplace_back(child_vector.GetType(), bind_data.modifiers[c]); + } + DecodeSortKeyRecursive(decode_data.data(), decode_state.columns[c], child_vector, 0, count); } } @@ -1494,6 +1535,8 @@ ScalarFunction CreateSortKeyFun::GetFunction() { sort_key_function.GetSignature().GetParameter(0).SetName("key1"); sort_key_function.GetSignature().AddArgs("args", LogicalType::ANY); sort_key_function.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); + sort_key_function.GetProperties().SetProperty(CreateSortKeyHelpers::NON_NULL_RESULT_PROPERTY, Value::BOOLEAN(true)); + sort_key_function.SetInitStateCallback(InitCreateSortKeyState); return sort_key_function; } @@ -1512,6 +1555,7 @@ unique_ptr DecodeSortKeyFun::Bind(unique_ptr sort_key, c bind_data->all_constant = all_constant; ScalarFunction definition("decode_sort_key", {sort_key->GetReturnType()}, LogicalType::STRUCT(std::move(columns)), DecodeSortKeyFunction); + definition.SetInitStateCallback(InitDecodeSortKeyState); BoundScalarFunction function(definition); vector> children; children.push_back(std::move(sort_key)); @@ -1524,6 +1568,7 @@ ScalarFunction DecodeSortKeyFun::GetFunction() { {{"sort_key", LogicalType::ANY}, {"col", LogicalType::VARCHAR}, {"sort_specifier", LogicalType::VARCHAR}}, LogicalType::STRUCT({{"any", LogicalType::ANY}}), DecodeSortKeyFunction, DecodeSortKeyBind); sort_key_function.GetSignature().AddArgs("args", LogicalType::VARCHAR); + sort_key_function.SetInitStateCallback(InitDecodeSortKeyState); return sort_key_function; } diff --git a/src/duckdb/src/function/scalar/date/strftime.cpp b/src/duckdb/src/function/scalar/date/strftime.cpp index 710509c24..c30fb550c 100644 --- a/src/duckdb/src/function/scalar/date/strftime.cpp +++ b/src/duckdb/src/function/scalar/date/strftime.cpp @@ -129,12 +129,12 @@ inline timestamp_ns_t StrpTimeResult(StrpTimeFormat::ParseResult &parsed) { } template -inline bool StrpTimeTryResult(StrpTimeFormat &format, string_t &input, T &result, string &error) { +inline bool StrpTimeTryResult(const StrpTimeFormat &format, string_t &input, T &result, string &error) { return format.TryParseTimestamp(input, result, error); } template <> -inline bool StrpTimeTryResult(StrpTimeFormat &format, string_t &input, timestamp_ns_t &result, string &error) { +inline bool StrpTimeTryResult(const StrpTimeFormat &format, string_t &input, timestamp_ns_t &result, string &error) { return format.TryParseTimestampNS(input, result, error); } diff --git a/src/duckdb/src/function/scalar/generic/error.cpp b/src/duckdb/src/function/scalar/generic/error.cpp index 37b53a60a..889f42c40 100644 --- a/src/duckdb/src/function/scalar/generic/error.cpp +++ b/src/duckdb/src/function/scalar/generic/error.cpp @@ -18,6 +18,13 @@ static void ErrorFunction(DataChunk &args, ExpressionState &state, Vector &resul } // namespace +bool ErrorFun::IsError(const BoundScalarFunction &function) { + using error_callback_t = void (*)(DataChunk &, ExpressionState &, Vector &); + auto &callback = function.GetDefinition()->GetCallbacks().function; + optional_ptr target = callback.target(); + return target && *target == ErrorFunction; +} + ScalarFunction ErrorFun::GetFunction() { auto fun = ScalarFunction("error", {}, LogicalType::SQLNULL, ErrorFunction); fun.GetSignature().AddParameter("message", LogicalType::VARCHAR); diff --git a/src/duckdb/src/function/scalar/generic/invoke.cpp b/src/duckdb/src/function/scalar/generic/invoke.cpp index 42a45928e..37a952f9e 100644 --- a/src/duckdb/src/function/scalar/generic/invoke.cpp +++ b/src/duckdb/src/function/scalar/generic/invoke.cpp @@ -36,7 +36,7 @@ struct LambdaInvokeData final : public LambdaFunctionData { } //! Serializes a lambda function's bind data - static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, + static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundScalarFunction &function) { auto &bind_data = bind_data_p->Cast(); serializer.WritePropertyWithDefault(101, "lambda_expr", bind_data.lambda_expr, unique_ptr()); @@ -78,7 +78,7 @@ struct LambdaInvokeState final : public FunctionLocalState { } static unique_ptr Init(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { auto &bdata = bind_data->Cast(); if (!bdata.lambda_expr) { throw InternalException("Invoke function is missing its bound lambda expression"); diff --git a/src/duckdb/src/function/scalar/geometry/geometry_functions.cpp b/src/duckdb/src/function/scalar/geometry/geometry_functions.cpp index 42b1cd1e0..7d38115d7 100644 --- a/src/duckdb/src/function/scalar/geometry/geometry_functions.cpp +++ b/src/duckdb/src/function/scalar/geometry/geometry_functions.cpp @@ -97,6 +97,34 @@ ScalarFunction StGeomfromwkbFun::GetFunction() { return function; } +static void FromWKBGeographyFunction(DataChunk &input, ExpressionState &state, Vector &result) { + Geometry::FromBinary(input.data[0], result, input.size(), true); + + // Validate that all geographies fall within the canonical coordinate ranges. + UnifiedVectorFormat vdata; + result.ToUnifiedFormat(vdata); + const auto blobs = UnifiedVectorFormat::GetData(vdata); + for (idx_t i = 0; i < input.size(); i++) { + const auto idx = vdata.sel->get_index(i); + if (!vdata.validity.RowIsValid(idx)) { + continue; + } + if (!Geometry::IsValidGeography(blobs[idx])) { + throw InvalidInputException("ST_GeogFromWKB: coordinates are outside the canonical GEOGRAPHY ranges " + "(longitude/X must be within [-180, 180], latitude/Y within [-90, 90])"); + } + } +} + +ScalarFunction StGeogfromwkbFun::GetFunction() { + ScalarFunction function({}, LogicalType::GEOGRAPHY(), FromWKBGeographyFunction); + function.GetSignature().AddParameter("wkb", LogicalType::BLOB); + function.SetStatisticsCallback(FromWKBStats); + // throws when the input is not valid WKB, or is outside the canonical GEOGRAPHY ranges + function.SetFallible(); + return function; +} + static void ToWKBFunction(DataChunk &input, ExpressionState &state, Vector &result) { UnaryExecutor::Execute(input.data[0], result, [&](const string_t &geom) { // TODO: convert to internal representation @@ -106,10 +134,14 @@ static void ToWKBFunction(DataChunk &input, ExpressionState &state, Vector &resu StringVector::AddHeapReference(input.data[0], result); } -ScalarFunction StAswkbFun::GetFunction() { - ScalarFunction function({}, LogicalType::BLOB, ToWKBFunction); - function.GetSignature().AddParameter("geom", LogicalType::GEOMETRY()); - return function; +ScalarFunctionSet StAswkbFun::GetFunctions() { + ScalarFunctionSet set; + for (const auto &geo_type : {LogicalType::GEOMETRY(), LogicalType::GEOGRAPHY()}) { + ScalarFunction function({}, LogicalType::BLOB, ToWKBFunction); + function.GetSignature().AddParameter("geom", geo_type); + set.AddFunction(function); + } + return set; } static void ToWKTFunction(DataChunk &input, ExpressionState &state, Vector &result) { @@ -118,20 +150,25 @@ static void ToWKTFunction(DataChunk &input, ExpressionState &state, Vector &resu [&](const string_t &geom) { return Geometry::ToString(heap, geom); }); } -ScalarFunction StAstextFun::GetFunction() { - ScalarFunction function({}, LogicalType::VARCHAR, ToWKTFunction); - function.GetSignature().AddParameter("geom", LogicalType::GEOMETRY()); - return function; +ScalarFunctionSet StAstextFun::GetFunctions() { + ScalarFunctionSet set; + for (const auto &geo_type : {LogicalType::GEOMETRY(), LogicalType::GEOGRAPHY()}) { + ScalarFunction function({}, LogicalType::VARCHAR, ToWKTFunction); + function.GetSignature().AddParameter("geom", geo_type); + set.AddFunction(function); + } + return set; } +template static void IntersectsExtentFunction(DataChunk &input, ExpressionState &state, Vector &result) { BinaryExecutor::Execute( input.data[0], input.data[1], result, [](const string_t &lhs_geom, const string_t &rhs_geom) { auto lhs_extent = GeometryExtent::Empty(); auto rhs_extent = GeometryExtent::Empty(); - const auto lhs_is_empty = Geometry::GetExtent(lhs_geom, lhs_extent) == 0; - const auto rhs_is_empty = Geometry::GetExtent(rhs_geom, rhs_extent) == 0; + const auto lhs_is_empty = Geometry::GetExtent(lhs_geom, lhs_extent, MODEL) == 0; + const auto rhs_is_empty = Geometry::GetExtent(rhs_geom, rhs_extent, MODEL) == 0; if (lhs_is_empty || rhs_is_empty) { // One of the geometries is empty @@ -139,7 +176,7 @@ static void IntersectsExtentFunction(DataChunk &input, ExpressionState &state, V } // Don't take Z and M into account for intersection test - return lhs_extent.IntersectsXY(rhs_extent); + return lhs_extent.IntersectsXY(rhs_extent, MODEL); }); } @@ -147,6 +184,7 @@ static void IntersectsExtentFunction(DataChunk &input, ExpressionState &state, V // boxes intersect. One argument must be a constant geometry; the other is the column we prune against. Both // operands' statistics are derived for us (the constant's geometry stats already carry its bounding box, and // the column's look through any CRS-only cast), so this works regardless of which side the constant is on. +template static FilterPropagateResult IntersectsExtentFilterPrune(const FunctionStatisticsPruneInput &input) { auto &children = input.function.GetChildren(); if (children.size() != 2) { @@ -183,11 +221,11 @@ static FilterPropagateResult IntersectsExtentFilterPrune(const FunctionStatistic // An empty constant geometry never intersects anything. return FilterPropagateResult::FILTER_ALWAYS_FALSE; } - if (!const_extent.IntersectsXY(col_extent)) { + if (!const_extent.IntersectsXY(col_extent, MODEL)) { // The column zonemap does not intersect the constant: no row can match. return FilterPropagateResult::FILTER_ALWAYS_FALSE; } - if (const_extent.ContainsXY(col_extent)) { + if (const_extent.ContainsXY(col_extent, MODEL)) { // The constant fully covers the column zonemap, so every row that is represented in the zonemap // matches. Rows that are not represented in it do not: NULL rows (the predicate evaluates to NULL // for them) and empty geometries (which contribute no vertices, but never intersect anything). @@ -200,13 +238,24 @@ static FilterPropagateResult IntersectsExtentFilterPrune(const FunctionStatistic return FilterPropagateResult::NO_PRUNING_POSSIBLE; } -ScalarFunction StIntersectsExtentFun::GetFunction() { - ScalarFunction function({}, LogicalType::BOOLEAN, IntersectsExtentFunction); - function.GetSignature() +ScalarFunctionSet StIntersectsExtentFun::GetFunctions() { + ScalarFunctionSet set; + + ScalarFunction geom_func({}, LogicalType::BOOLEAN, IntersectsExtentFunction); + geom_func.GetSignature() .AddParameter("geom1", LogicalType::GEOMETRY()) .AddParameter("geom2", LogicalType::GEOMETRY()); - function.SetFilterPruneCallback(IntersectsExtentFilterPrune); - return function; + geom_func.SetFilterPruneCallback(IntersectsExtentFilterPrune); + set.AddFunction(geom_func); + + ScalarFunction geog_func({}, LogicalType::BOOLEAN, IntersectsExtentFunction); + geog_func.GetSignature() + .AddParameter("geom1", LogicalType::GEOGRAPHY()) + .AddParameter("geom2", LogicalType::GEOGRAPHY()); + geog_func.SetFilterPruneCallback(IntersectsExtentFilterPrune); + set.AddFunction(geog_func); + + return set; } static Value GetCRSValue(const LogicalType &logical_type) { @@ -223,9 +272,13 @@ static void CRSFunction(DataChunk &args, ExpressionState &state, Vector &result) result.Reference(GetCRSValue(type), count_t(args.size())); } +static bool IsGeoType(LogicalTypeId id) { + return id == LogicalTypeId::GEOMETRY || id == LogicalTypeId::GEOGRAPHY; +} + static unique_ptr BindCRSFunctionExpression(FunctionBindExpressionInput &input) { const auto &return_type = input.children[0]->GetReturnType(); - if (return_type.id() != LogicalTypeId::GEOMETRY) { + if (!IsGeoType(return_type.id())) { // parameter - unknown return type return nullptr; } @@ -235,7 +288,7 @@ static unique_ptr BindCRSFunctionExpression(FunctionBindExpressionIn static void CRSFunctionResolveTypes(ResolveScalarFunctionTypesInput &input) { auto &argument_type = input.GetArgumentType(0); - if (argument_type.id() != LogicalTypeId::GEOMETRY) { + if (!IsGeoType(argument_type.id())) { return; } @@ -243,18 +296,29 @@ static void CRSFunctionResolveTypes(ResolveScalarFunctionTypesInput &input) { input.GetBoundFunction().GetArguments()[0] = argument_type; } -ScalarFunction StCrsFun::GetFunction() { - ScalarFunction geom_func({}, LogicalType::VARCHAR, CRSFunction); - geom_func.SetResolveTypesCallback(CRSFunctionResolveTypes); - geom_func.GetSignature().AddParameter("geom", LogicalType::GEOMETRY()); - geom_func.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); - geom_func.SetBindExpressionCallback(BindCRSFunctionExpression); - return geom_func; +ScalarFunctionSet StCrsFun::GetFunctions() { + ScalarFunctionSet set; + for (const auto &geo_type : {LogicalType::GEOMETRY(), LogicalType::GEOGRAPHY()}) { + ScalarFunction func({}, LogicalType::VARCHAR, CRSFunction); + func.SetResolveTypesCallback(CRSFunctionResolveTypes); + func.GetSignature().AddParameter("geom", geo_type); + func.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); + func.SetBindExpressionCallback(BindCRSFunctionExpression); + set.AddFunction(func); + } + return set; } static unique_ptr SetCRSBind(BindScalarFunctionInput &input) { auto &context = input.GetClientContext(); auto &bound_function = input.GetBoundFunction(); + auto &arguments = input.GetArguments(); + + // Preserve the input kind (GEOMETRY vs GEOGRAPHY) in the result type. + const bool is_geography = arguments[0]->GetReturnType().id() == LogicalTypeId::GEOGRAPHY; + const auto make_type = [&](const string &crs) { + return is_geography ? LogicalType::GEOGRAPHY(crs) : LogicalType::GEOMETRY(crs); + }; // Check if the CRS is set in the second argument const auto crs_val = input.GetConstant(1); @@ -267,10 +331,10 @@ static unique_ptr SetCRSBind(BindScalarFunctionInput &input) { // Try to convert to identify const auto lookup = CoordinateReferenceSystem::TryIdentify(context, crs_str); if (lookup) { - bound_function.SetReturnType(LogicalType::GEOMETRY(lookup->GetDefinition())); + bound_function.SetReturnType(make_type(lookup->GetDefinition())); } else { // Pass on the raw string (better than nothing) - bound_function.SetReturnType(LogicalType::GEOMETRY(crs_str)); + bound_function.SetReturnType(make_type(crs_str)); } return nullptr; } @@ -279,10 +343,14 @@ static void SetCRSFunction(DataChunk &args, ExpressionState &state, Vector &resu result.Reinterpret(args.data[0]); } -ScalarFunction StSetcrsFun::GetFunction() { - ScalarFunction geom_func({}, LogicalType::GEOMETRY(), SetCRSFunction, SetCRSBind); - geom_func.GetSignature().AddParameter("geom", LogicalType::GEOMETRY()).AddParameter("crs", LogicalType::VARCHAR); - return geom_func; +ScalarFunctionSet StSetcrsFun::GetFunctions() { + ScalarFunctionSet set; + for (const auto &geo_type : {LogicalType::GEOMETRY(), LogicalType::GEOGRAPHY()}) { + ScalarFunction func({}, geo_type, SetCRSFunction, SetCRSBind); + func.GetSignature().AddParameter("geom", geo_type).AddParameter("crs", LogicalType::VARCHAR); + set.AddFunction(func); + } + return set; } namespace { @@ -383,8 +451,13 @@ static auto VertexExtractStats(ClientContext &context, FunctionStatisticsInput & } if (bind_data.vertex_index == 0 && extent.HasXY()) { // X - NumericStats::SetMin(new_stats, extent.x_min); - NumericStats::SetMax(new_stats, extent.x_max); + // A GEOGRAPHY extent is a longitude arc (it may wrap, and +180/-180 are the same longitude), so + // it is converted to a plain numeric range over the stored coordinate values. + const auto geometry_model = Geometry::GetModel(input.child_stats[0].GetType()); + double x_min, x_max; + extent.GetNumericXRange(geometry_model, x_min, x_max); + NumericStats::SetMin(new_stats, x_min); + NumericStats::SetMax(new_stats, x_max); return new_stats.ToUnique(); } if (bind_data.vertex_index == 1 && extent.HasXY()) { // Y @@ -466,15 +539,20 @@ static auto VertexExtractFunction(DataChunk &input, ExpressionState &state, Vect }); } -ScalarFunction VertexExtractFun::GetFunction() { - auto fun = ScalarFunction({}, LogicalTypeId::DOUBLE, VertexExtractFunction, VertexExtractBind, VertexExtractStats); - fun.GetSignature() - .AddParameter("geom", LogicalType::GEOMETRY()) - .AddParameter("coordinate", LogicalTypeId::VARCHAR) - .SetReturnType(LogicalType::DOUBLE); +ScalarFunctionSet VertexExtractFun::GetFunctions() { + ScalarFunctionSet set; + for (const auto &geo_type : {LogicalType::GEOMETRY(), LogicalType::GEOGRAPHY()}) { + auto fun = + ScalarFunction({}, LogicalTypeId::DOUBLE, VertexExtractFunction, VertexExtractBind, VertexExtractStats); + fun.GetSignature() + .AddParameter("geom", geo_type) + .AddParameter("coordinate", LogicalTypeId::VARCHAR) + .SetReturnType(LogicalType::DOUBLE); - fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); - return fun; + fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); + set.AddFunction(fun); + } + return set; } } // namespace duckdb diff --git a/src/duckdb/src/function/scalar/operator/arithmetic.cpp b/src/duckdb/src/function/scalar/operator/arithmetic.cpp index 80b83fa8f..55cded9ed 100644 --- a/src/duckdb/src/function/scalar/operator/arithmetic.cpp +++ b/src/duckdb/src/function/scalar/operator/arithmetic.cpp @@ -354,8 +354,7 @@ unique_ptr PropagateNumericStats(ClientContext &context, Functio } else { // no potential overflow: replace with non-overflowing operator if (input.bind_data) { - auto &bind_data = input.bind_data->Cast(); - bind_data.check_overflow = false; + input.bind_data.write().Cast().check_overflow = false; } if constexpr (HasBignumOperation::value) { expr.FunctionMutable().SetFunctionCallback( @@ -520,7 +519,7 @@ void DecimalAddSubtractResolveTypes(ResolveScalarFunctionTypesInput &input) { } } -void SerializeDecimalArithmetic(Serializer &serializer, const optional_ptr bind_data_p, +void SerializeDecimalArithmetic(Serializer &serializer, const optional_ptr bind_data_p, const BoundScalarFunction &function) { auto &bind_data = bind_data_p->Cast(); serializer.WriteProperty(100, "check_overflow", bind_data.check_overflow); diff --git a/src/duckdb/src/function/scalar/operator/cast.cpp b/src/duckdb/src/function/scalar/operator/cast.cpp index 09f0eea27..e4bc72046 100644 --- a/src/duckdb/src/function/scalar/operator/cast.cpp +++ b/src/duckdb/src/function/scalar/operator/cast.cpp @@ -20,12 +20,6 @@ static BoundCastInfo BindCastScalarFunction(ClientContext &context, const Logica return cast_functions.GetCastFunction(source, target, input); } -static BoundCastInfo BindDefaultCastScalarFunction(const LogicalType &source, const LogicalType &target) { - CastFunctionSet cast_functions; - auto input = GetCastFunctionInput::Default(); - return cast_functions.GetCastFunction(source, target, input); -} - //! Casts to UNION types must run even for constant NULL inputs (the union member tag is set even for NULL values), //! so we disable the executor's constant-NULL short-circuit for those. For all other targets casts propagate NULLs //! normally, and using default NULL handling keeps Expression::PropagatesNullValues() accurate for the optimizer. @@ -51,27 +45,25 @@ static bool BoundCastCanThrow(const BoundCastInfo &bound_cast, const LogicalType } struct CastFunctionData : public FunctionData { - CastFunctionData(LogicalType source_type_p, LogicalType target_type_p, BoundCastInfo bound_cast_p, bool try_cast_p, - bool is_default_cast_p) + CastFunctionData(LogicalType source_type_p, LogicalType target_type_p, BoundCastInfo bound_cast_p, bool try_cast_p) : source_type(std::move(source_type_p)), target_type(std::move(target_type_p)), - bound_cast(std::move(bound_cast_p)), try_cast(try_cast_p), is_default_cast(is_default_cast_p) { + bound_cast(std::move(bound_cast_p)), try_cast(try_cast_p) { } LogicalType source_type; LogicalType target_type; BoundCastInfo bound_cast; bool try_cast; - bool is_default_cast; public: unique_ptr Copy() const override { - return make_uniq(source_type, target_type, bound_cast.Copy(), try_cast, is_default_cast); + return make_uniq(source_type, target_type, bound_cast.Copy(), try_cast); } bool Equals(const FunctionData &other_p) const override { auto &other = other_p.Cast(); return source_type == other.source_type && target_type == other.target_type && try_cast == other.try_cast && - is_default_cast == other.is_default_cast && bound_cast.Equals(other.bound_cast); + bound_cast.Equals(other.bound_cast); } }; @@ -95,7 +87,7 @@ void CastFunction(DataChunk &args, ExpressionState &state, Vector &result) { } static unique_ptr CastInitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { auto &cast_data = bind_data->Cast(); if (!cast_data.bound_cast.HasInitLocalState()) { return nullptr; @@ -126,34 +118,29 @@ static ExpressionType CastGetExpressionType(FunctionToStringInput &input) { static unique_ptr CastLegacySerializeCallback(FunctionToStringInput &input) { auto &cast_data = input.bind_data->Cast(); - if (cast_data.is_default_cast) { - throw NotImplementedException("Default casts cannot be represented by the legacy cast format"); - } return make_uniq(input.GetChild(0).Copy(), cast_data.target_type, cast_data.try_cast); } -static void CastFunctionSerialize(Serializer &serializer, const optional_ptr bind_data_p, +static void CastFunctionSerialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundScalarFunction &function) { auto &bind_data = bind_data_p->Cast(); serializer.WriteProperty(100, "try_cast", bind_data.try_cast); - serializer.WriteProperty(101, "is_default_cast", bind_data.is_default_cast); } static unique_ptr CastFunctionDeserialize(Deserializer &deserializer, BoundScalarFunction &function) { auto try_cast = deserializer.ReadProperty(100, "try_cast"); - auto is_default_cast = deserializer.ReadPropertyWithDefault(101, "is_default_cast"); + deserializer.ReadDeletedProperty(101, "is_default_cast"); auto &context = deserializer.Get(); // the target type is the return type of the function (set by the function serializer) auto target_type = deserializer.Get(); auto source_type = function.GetArguments()[0]; - auto bound_cast = is_default_cast ? BindDefaultCastScalarFunction(source_type, target_type) - : BindCastScalarFunction(context, source_type, target_type); + auto bound_cast = BindCastScalarFunction(context, source_type, target_type); if (BoundCastCanThrow(bound_cast, source_type, target_type, try_cast)) { function.SetErrorMode(FunctionErrors::CAN_THROW_RUNTIME_ERROR); } function.SetStability(bound_cast.GetStability()); SetCastNullHandling(function, target_type); - return make_uniq(source_type, target_type, std::move(bound_cast), try_cast, is_default_cast); + return make_uniq(source_type, target_type, std::move(bound_cast), try_cast); } ScalarFunction CastFun::GetFunction() { @@ -172,8 +159,8 @@ ScalarFunction CastFun::GetFunction() { //===--------------------------------------------------------------------===// // BoundCastExpression //===--------------------------------------------------------------------===// -static unique_ptr CreateCastExpression(unique_ptr child, const LogicalType &target_type, - BoundCastInfo bound_cast, bool try_cast, bool is_default_cast) { +unique_ptr BoundCastExpression::Create(unique_ptr child, const LogicalType &target_type, + BoundCastInfo bound_cast, bool try_cast) { auto source_type = child->GetReturnType(); auto query_location = child->GetQueryLocation(); @@ -182,8 +169,7 @@ static unique_ptr CreateCastExpression(unique_ptr child, auto can_throw = BoundCastCanThrow(bound_cast, source_type, target_type, try_cast); auto stability = bound_cast.GetStability(); - auto function_data = - make_uniq(source_type, target_type, std::move(bound_cast), try_cast, is_default_cast); + auto function_data = make_uniq(source_type, target_type, std::move(bound_cast), try_cast); auto scalar_function = CastFun::GetFunction(); scalar_function.SetReturnType(target_type); @@ -200,16 +186,6 @@ static unique_ptr CreateCastExpression(unique_ptr child, true, Identifier(), query_location); } -unique_ptr BoundCastExpression::Create(unique_ptr child, const LogicalType &target_type, - BoundCastInfo bound_cast, bool try_cast) { - return CreateCastExpression(std::move(child), target_type, std::move(bound_cast), try_cast, false); -} - -unique_ptr BoundCastExpression::CreateDefault(unique_ptr child, const LogicalType &target_type, - BoundCastInfo bound_cast, bool try_cast) { - return CreateCastExpression(std::move(child), target_type, std::move(bound_cast), try_cast, true); -} - bool BoundCastExpression::IsCast(const Expression &expr) { return expr.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION && expr.GetExpressionType() == ExpressionType::OPERATOR_CAST; @@ -244,16 +220,12 @@ bool BoundCastExpression::HasValidBindData(const BoundFunctionExpression &cast_e data.target_type == cast_expr.GetReturnType(); } -bool BoundCastExpression::IsDefaultCast(const BoundFunctionExpression &cast_expr) { - return cast_expr.BindInfo()->Cast().is_default_cast; -} - const BoundCastInfo &BoundCastExpression::GetBoundCast(const BoundFunctionExpression &cast_expr) { return cast_expr.BindInfo()->Cast().bound_cast; } BoundCastInfo &BoundCastExpression::GetBoundCastMutable(BoundFunctionExpression &cast_expr) { - return cast_expr.BindInfo()->Cast().bound_cast; + return cast_expr.BindInfoMutable().write().Cast().bound_cast; } unique_ptr BoundCastExpression::PropagateStatistics(BoundFunctionExpression &cast_expr, @@ -263,7 +235,7 @@ unique_ptr BoundCastExpression::PropagateStatistics(BoundFunctio cast_expr.Function().GetNullHandling() == FunctionNullHandling::DEFAULT_NULL_HANDLING) { return BaseStatistics::FromConstant(Value(cast_expr.GetReturnType())).ToUnique(); } - auto &cast_data = cast_expr.BindInfoMutable()->Cast(); + auto &cast_data = cast_expr.BindInfoMutable().write().Cast(); auto result = cast_data.bound_cast.PropagateStatistics(cast_data.source_type, cast_data.target_type, child_stats, context); if (cast_data.try_cast && result) { diff --git a/src/duckdb/src/function/scalar/sequence/nextval.cpp b/src/duckdb/src/function/scalar/sequence/nextval.cpp index 8191a3697..fa5f267de 100644 --- a/src/duckdb/src/function/scalar/sequence/nextval.cpp +++ b/src/duckdb/src/function/scalar/sequence/nextval.cpp @@ -70,7 +70,7 @@ bool RowIsValid(const unique_ptr> &entries, idx_t i) { } unique_ptr NextValLocalFunction(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { if (!bind_data) { return nullptr; } @@ -132,7 +132,7 @@ unique_ptr NextValBind(BindScalarFunctionInput &input) { return make_uniq(seq); } -void Serialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &) { +void Serialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &) { auto &next_val_bind_data = bind_data->Cast(); serializer.WritePropertyWithDefault(100, "sequence_create_info", next_val_bind_data.create_info); } diff --git a/src/duckdb/src/function/scalar/strftime_format.cpp b/src/duckdb/src/function/scalar/strftime_format.cpp index 889d82d13..04e6755b7 100644 --- a/src/duckdb/src/function/scalar/strftime_format.cpp +++ b/src/duckdb/src/function/scalar/strftime_format.cpp @@ -167,7 +167,7 @@ idx_t StrfTimeFormat::GetLength(date_t date, int32_t data[8], const char *tz_nam return size; } -idx_t StrfTimeFormat::GetLength(date_t date, dtime_t time, int32_t utc_offset, const char *tz_name) { +idx_t StrfTimeFormat::GetLength(date_t date, dtime_t time, int32_t utc_offset, const char *tz_name) const { if (!var_length_specifiers.empty()) { int32_t data[8]; Date::Convert(date, data[0], data[1], data[2]); @@ -457,13 +457,13 @@ void StrfTimeFormat::FormatStringNS(date_t date, int32_t data[8], const char *tz memcpy(target, literals[i].c_str(), literals[i].size()); } -void StrfTimeFormat::FormatString(date_t date, int32_t data[8], const char *tz_name, char *target) { +void StrfTimeFormat::FormatString(date_t date, int32_t data[8], const char *tz_name, char *target) const { data[6] *= Interval::NANOS_PER_MICRO; FormatStringNS(date, data, tz_name, target); data[6] /= Interval::NANOS_PER_MICRO; } -void StrfTimeFormat::FormatString(date_t date, dtime_t time, char *target) { +void StrfTimeFormat::FormatString(date_t date, dtime_t time, char *target) const { int32_t data[8]; // year, month, day, hour, min, sec, µs, offset Date::Convert(date, data[0], data[1], data[2]); Time::Convert(time, data[3], data[4], data[5], data[6]); @@ -672,7 +672,7 @@ string StrTimeFormat::ParseFormatSpecifier(const string &format_string, StrTimeF return string(); } -void StrfTimeFormat::ConvertDateVector(const Vector &input, Vector &result) { +void StrfTimeFormat::ConvertDateVector(const Vector &input, Vector &result) const { D_ASSERT(input.GetType().id() == LogicalTypeId::DATE); D_ASSERT(result.GetType().id() == LogicalTypeId::VARCHAR); auto &heap = StringVector::GetStringHeap(result); @@ -738,7 +738,7 @@ string_t StrfTimeFormat::ConvertTimestampValue(const timestamp_ns_t &input, Stri } } -void StrfTimeFormat::ConvertTimestampVector(const Vector &input, Vector &result) { +void StrfTimeFormat::ConvertTimestampVector(const Vector &input, Vector &result) const { D_ASSERT(input.GetType().id() == LogicalTypeId::TIMESTAMP || input.GetType().id() == LogicalTypeId::TIMESTAMP_TZ); D_ASSERT(result.GetType().id() == LogicalTypeId::VARCHAR); auto &heap = StringVector::GetStringHeap(result); @@ -746,7 +746,7 @@ void StrfTimeFormat::ConvertTimestampVector(const Vector &input, Vector &result) [&](timestamp_t ts) { return ConvertTimestampValue(ts, heap); }); } -void StrfTimeFormat::ConvertTimestampNSVector(const Vector &input, Vector &result) { +void StrfTimeFormat::ConvertTimestampNSVector(const Vector &input, Vector &result) const { D_ASSERT(input.GetType().id() == LogicalTypeId::TIMESTAMP_NS || input.GetType().id() == LogicalTypeId::TIMESTAMP_TZ_NS); D_ASSERT(result.GetType().id() == LogicalTypeId::VARCHAR); diff --git a/src/duckdb/src/function/scalar/string/concat.cpp b/src/duckdb/src/function/scalar/string/concat.cpp index e370de038..02984ec56 100644 --- a/src/duckdb/src/function/scalar/string/concat.cpp +++ b/src/duckdb/src/function/scalar/string/concat.cpp @@ -38,10 +38,20 @@ unique_ptr ConcatFunctionData::Copy() const { return make_uniq(return_type, is_operator); } +struct ConcatLocalState : public FunctionLocalState { + vector lengths; +}; + +unique_ptr InitConcatState(ExpressionState &, const BoundFunctionExpression &, + optional_ptr) { + return make_uniq(); +} + void StringConcatFunction(DataChunk &args, ExpressionState &state, Vector &result) { // iterate over the vectors to count how large the final string will be idx_t constant_lengths = 0; - vector result_lengths(args.size(), 0); + auto &result_lengths = ExecuteFunctionState::GetFunctionState(state)->Cast().lengths; + result_lengths.assign(args.size(), 0); for (idx_t col_idx = 0; col_idx < args.ColumnCount(); col_idx++) { const auto &input = args.data[col_idx]; D_ASSERT(input.GetType().InternalType() == PhysicalType::VARCHAR); @@ -363,6 +373,7 @@ ScalarFunction ListConcatFun::GetFunction() { fun.GetSignature().AddArgs("args", LogicalType::LIST(LogicalType::ANY)); fun.SetResolveTypesCallback(ConcatFunctionResolveTypes); fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); + fun.SetInitStateCallback(InitConcatState); return fun; } @@ -380,6 +391,7 @@ ScalarFunction ConcatFun::GetFunction() { concat.GetSignature().AddArgs("args", LogicalType::ANY); concat.SetResolveTypesCallback(ConcatFunctionResolveTypes); concat.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); + concat.SetInitStateCallback(InitConcatState); return concat; } diff --git a/src/duckdb/src/function/scalar/string/like.cpp b/src/duckdb/src/function/scalar/string/like.cpp index edfe6c4ba..07cb99eef 100644 --- a/src/duckdb/src/function/scalar/string/like.cpp +++ b/src/duckdb/src/function/scalar/string/like.cpp @@ -285,7 +285,7 @@ struct LikeMatcher : public FunctionData { has_start_percentage(has_start_percentage), has_end_percentage(has_end_percentage) { } - bool Match(string_t &str) { + bool Match(string_t &str) const { auto str_data = const_uchar_ptr_cast(str.GetData()); auto str_len = str.GetSize(); idx_t segment_idx = 0; diff --git a/src/duckdb/src/function/scalar/string/regexp.cpp b/src/duckdb/src/function/scalar/string/regexp.cpp index 97e54c83f..29e929110 100644 --- a/src/duckdb/src/function/scalar/string/regexp.cpp +++ b/src/duckdb/src/function/scalar/string/regexp.cpp @@ -62,7 +62,7 @@ bool RegexpBaseBindData::Equals(const FunctionData &other_p) const { } unique_ptr RegexInitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { auto &info = bind_data->Cast(); if (info.constant_pattern) { return make_uniq(info); diff --git a/src/duckdb/src/function/scalar/string/regexp/regexp_extract_all.cpp b/src/duckdb/src/function/scalar/string/regexp/regexp_extract_all.cpp index 6d81c6ae8..338074112 100644 --- a/src/duckdb/src/function/scalar/string/regexp/regexp_extract_all.cpp +++ b/src/duckdb/src/function/scalar/string/regexp/regexp_extract_all.cpp @@ -16,8 +16,9 @@ using regexp_util::CreateStringPiece; using regexp_util::ParseRegexOptions; using regexp_util::TryParseConstantPattern; -unique_ptr -RegexpExtractAll::InitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, FunctionData *bind_data) { +unique_ptr RegexpExtractAll::InitLocalState(ExpressionState &state, + const BoundFunctionExpression &expr, + optional_ptr bind_data) { auto &info = bind_data->Cast(); if (info.constant_pattern) { return make_uniq(info, true); @@ -27,7 +28,7 @@ RegexpExtractAll::InitLocalState(ExpressionState &state, const BoundFunctionExpr unique_ptr RegexpExtractAllStruct::InitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { auto &info = bind_data->Cast(); if (info.constant_pattern) { return make_uniq(info, true); diff --git a/src/duckdb/src/function/scalar/struct/remap_struct.cpp b/src/duckdb/src/function/scalar/struct/remap_struct.cpp index 79b16a0cb..e276238e9 100644 --- a/src/duckdb/src/function/scalar/struct/remap_struct.cpp +++ b/src/duckdb/src/function/scalar/struct/remap_struct.cpp @@ -90,8 +90,12 @@ void RemapChildVectors(const Vector &result, const vector> &in auto &nested_default = defaults[remap.default_index.GetIndex()]; if (nested_default.GetType().id() == LogicalTypeId::STRUCT && result_vectors[i].get().GetType().id() == LogicalTypeId::STRUCT) { - RemapNested(nested_default, nested_default, result_vectors[i], count, remap.child_remap_info); - if (has_top_level_null) { + auto &nested_result = result_vectors[i].get(); + RemapNested(nested_default, nested_default, nested_result, count, remap.child_remap_info); + // a NULL default leaves the result a constant NULL, which is already NULL in every row + bool default_is_null = nested_result.GetVectorType() == VectorType::CONSTANT_VECTOR && + ConstantVector::IsNull(nested_result); + if (has_top_level_null && !default_is_null) { FlatVector::SetValidity(result_vectors[i], FlatVector::Validity(result)); PropagateStructNulls(result_vectors[i], FlatVector::Validity(result), count); } diff --git a/src/duckdb/src/function/scalar/system/aggregate_export.cpp b/src/duckdb/src/function/scalar/system/aggregate_export.cpp index 6bfad32c9..087e3c61e 100644 --- a/src/duckdb/src/function/scalar/system/aggregate_export.cpp +++ b/src/duckdb/src/function/scalar/system/aggregate_export.cpp @@ -58,20 +58,20 @@ struct ExportAggregateBindData : public FunctionData { return aggr == other.aggr && state_size == other.state_size; } - static ExportAggregateBindData &GetFrom(ExpressionState &state) { + static const ExportAggregateBindData &GetFrom(ExpressionState &state) { auto &func_expr = state.expr.Cast(); return func_expr.BindInfo()->Cast(); } }; -static AggregateStateLayout GetLayout(const BoundAggregateFunction &aggr, optional_ptr bind_data) { +static AggregateStateLayout GetLayout(const BoundAggregateFunction &aggr, optional_ptr bind_data) { return aggr.GetStateType(bind_data); } // destroys the temporary underlying-aggregate states referenced by `states` (no-op if the aggregate has no // destructor). the combine/finalize paths below initialize underlying states into scratch buffers - without this // their owned heap (e.g. approx_top_k's hash map, approx_quantile's t-digest) would leak. -static void DestroyExportStates(const BoundAggregateFunction &aggr, optional_ptr bind_data, +static void DestroyExportStates(const BoundAggregateFunction &aggr, optional_ptr bind_data, Vector &states, idx_t count, ArenaAllocator &allocator) { if (count == 0 || !aggr.HasStateDestructorCallback()) { return; @@ -98,7 +98,7 @@ struct CombineState : public FunctionLocalState { }; unique_ptr InitCombineState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data_p) { + optional_ptr bind_data_p) { auto &bind_data = bind_data_p->Cast(); return make_uniq(bind_data); } @@ -120,7 +120,7 @@ struct FinalizeState : public FunctionLocalState { }; unique_ptr InitFinalizeState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data_p) { + optional_ptr bind_data_p) { auto &bind_data = bind_data_p->Cast(); return make_uniq(bind_data); } @@ -546,9 +546,15 @@ void CombineAggrUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx target_data.WriteValue(state_values[i].GetValue()); } + // when the targets never keep source memory, the temporary states go into a scratch arena freed per call + unique_ptr scratch; + if (underlying_aggr.GetCombineSourceRetention() == AggregateCombineSourceRetention::NEVER_RETAINS) { + scratch = make_uniq(aggr_input_data.allocator.GetUnderlyingAllocator()); + } + auto &source_allocator = scratch ? *scratch : aggr_input_data.allocator; try { AggregateStateSerialization::DeserializeStates(underlying_aggr, layout, inputs[0], count, temp_state_buf.get(), - aggr_input_data.allocator, StateMemoryOwnership::BORROWED); + source_allocator, StateMemoryOwnership::BORROWED); AggregateInputData combine_input(bind_data.aggr, bind_data.bind_data.get(), aggr_input_data.allocator, AggregateCombineType::ALLOW_DESTRUCTIVE); if (input_count == 2) { @@ -556,10 +562,10 @@ void CombineAggrUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx } underlying_aggr.GetStateCombineCallback()(source_vec, target_vec, combine_input, count); } catch (...) { - DestroyExportStates(underlying_aggr, bind_data.bind_data.get(), source_vec, count, aggr_input_data.allocator); + DestroyExportStates(underlying_aggr, bind_data.bind_data.get(), source_vec, count, source_allocator); throw; } - DestroyExportStates(underlying_aggr, bind_data.bind_data.get(), source_vec, count, aggr_input_data.allocator); + DestroyExportStates(underlying_aggr, bind_data.bind_data.get(), source_vec, count, source_allocator); } void CombineAggrFinalize(Vector &state, AggregateFinalizeInputData &aggr_input_data, Vector &result, idx_t count, @@ -625,7 +631,7 @@ string OrderModifierToString(OrderType order_type, OrderByNullType null_order) { // the state layout (a struct) is aliased to AGGREGATE_STATE, with the function name and signature stored in the // extension type info so that the aggregate can be re-bound later (e.g. by FINALIZE/COMBINE) LogicalType CreateAggregateStateType(const BoundAggregateFunction &bound_function, - optional_ptr bind_data) { + optional_ptr bind_data) { auto layout = bound_function.GetStateType(bind_data); auto ext_info = make_uniq(); EncodeStateParameters(*ext_info, bound_function, layout); @@ -635,7 +641,8 @@ LogicalType CreateAggregateStateType(const BoundAggregateFunction &bound_functio // constructs the AGGREGATE_STATE type for an ordered aggregate - the state is the buffer of values // (LIST), with the inner signature and the ORDER BY spec stored in the extension info LogicalType CreateSortedAggregateStateType(const BoundAggregateFunction &inner_function, - optional_ptr inner_bind_data, const LogicalType &buffer_struct, + optional_ptr inner_bind_data, + const LogicalType &buffer_struct, const vector &orders) { LogicalType state_layout = LogicalType::LIST(buffer_struct); auto ext_info = make_uniq(); @@ -932,6 +939,23 @@ void ExportAggregateFunction::GetSortedStateOrders(const LogicalType &state_type ParseOrderBys(order_entry->second, StructType::GetChildTypes(buffer_struct).size(), orders); } +bool ExportAggregateFunction::TryGetCombinedStateLayout(const BoundAggregateFunction &function, + optional_ptr bind_data, + AggregateStateLayout &layout) { + if (!bind_data || function.GetStateCombineCallback() != CombineAggrStateCombine) { + return false; + } + auto &combine_data = bind_data->Cast(); + auto &aggr = combine_data.aggr; + // states with explicit export / import callbacks are not described by their field layout alone + if (!aggr.HasGetStateTypeCallback() || aggr.HasExportAggregateStateCallback() || + aggr.HasImportAggregateStateCallback()) { + return false; + } + layout = aggr.GetStateType(combine_data.bind_data.get()); + return true; +} + void ExportAggregateFunction::SetStateExport(BoundAggregateExpression &aggregate, LogicalType state_layout) { auto &bound_function = aggregate.FunctionMutable(); // functions with an explicit export callback use it as the finalize; others use the field-based serialization diff --git a/src/duckdb/src/function/scalar/variant/variant_comparator.cpp b/src/duckdb/src/function/scalar/variant/variant_comparator.cpp index de6987d07..8ea0535ed 100644 --- a/src/duckdb/src/function/scalar/variant/variant_comparator.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_comparator.cpp @@ -193,6 +193,7 @@ bool EncodeVariantNode(const VariantNode &it, SINK &sink, vector> CreateCastExpressions(WriteCSVData &bind_data, ClientContext &context, +static vector> CreateCastExpressions(const WriteCSVData &bind_data, ClientContext &context, const vector &names, const vector &sql_types) { auto &options = bind_data.options; - auto &formats = options.write_date_format; + auto formats = options.write_date_format; bool has_dateformat = !formats[LogicalTypeId::DATE].IsNull(); bool has_timestampformat = !formats[LogicalTypeId::TIMESTAMP].IsNull(); @@ -229,7 +229,8 @@ static void CSVListCopyOptions(ClientContext &context, CopyOptionsInput &input) //===--------------------------------------------------------------------===// struct LocalWriteCSVData : public LocalFunctionData { public: - LocalWriteCSVData(ClientContext &context, vector> &expressions, const idx_t &flush_size) + LocalWriteCSVData(ClientContext &context, const vector> &expressions, + const idx_t &flush_size) : executor(context, expressions), writer_local_state(context, flush_size) { } @@ -254,7 +255,7 @@ static unique_ptr OpenCSVFileWriter(ClientContext &context, con } struct GlobalWriteCSVData : public GlobalFunctionData { - GlobalWriteCSVData(CSVReaderOptions &options, ClientContext &context, const string &file_path, + GlobalWriteCSVData(const CSVReaderOptions &options, ClientContext &context, const string &file_path, FileCompressionType compression_p) : file_writer(OpenCSVFileWriter(context, file_path, std::move(compression_p))), writer(options, *file_writer), compression(file_writer->GetFileCompressionType()) { @@ -307,7 +308,7 @@ struct GlobalWriteCSVData : public GlobalFunctionData { vector> local_states; }; -static unique_ptr WriteCSVInitializeLocal(ExecutionContext &context, FunctionData &bind_data) { +static unique_ptr WriteCSVInitializeLocal(ExecutionContext &context, const FunctionData &bind_data) { auto &csv_data = bind_data.Cast(); auto local_data = make_uniq(context.client, csv_data.cast_expressions, csv_data.flush_size); @@ -319,7 +320,7 @@ static unique_ptr WriteCSVInitializeLocal(ExecutionContext &c return std::move(local_data); } -static unique_ptr WriteCSVInitializeGlobal(ClientContext &context, FunctionData &bind_data, +static unique_ptr WriteCSVInitializeGlobal(ClientContext &context, const FunctionData &bind_data, const string &file_path) { auto &csv_data = bind_data.Cast(); auto &options = csv_data.options; @@ -340,7 +341,7 @@ static void WriteCSVChunkInternal(CSVWriter &writer, CSVWriterState &writer_loca writer.WriteChunk(cast_chunk, writer_local_state); } -static void WriteCSVSink(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +static void WriteCSVSink(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate, DataChunk &input) { auto &local_data = lstate.Cast(); auto &global_state = gstate.Cast(); @@ -352,7 +353,7 @@ static void WriteCSVSink(ExecutionContext &context, FunctionData &bind_data, Glo //===--------------------------------------------------------------------===// // Combine //===--------------------------------------------------------------------===// -static void WriteCSVCombine(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +static void WriteCSVCombine(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate) { auto &local_data = lstate.Cast(); auto &global_state = gstate.Cast(); @@ -362,7 +363,7 @@ static void WriteCSVCombine(ExecutionContext &context, FunctionData &bind_data, //===--------------------------------------------------------------------===// // Finalize //===--------------------------------------------------------------------===// -void WriteCSVFinalize(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate) { +void WriteCSVFinalize(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate) { auto &global_state = gstate.Cast(); auto &writer = global_state.GetWriter(); auto &csv_data = bind_data.Cast(); @@ -399,7 +400,7 @@ struct WriteCSVBatchData : public PreparedBatchData { unique_ptr writer_local_state; }; -unique_ptr WriteCSVPrepareBatch(ClientContext &context, FunctionData &bind_data, +unique_ptr WriteCSVPrepareBatch(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, unique_ptr collection) { auto &csv_data = bind_data.Cast(); @@ -427,7 +428,7 @@ unique_ptr WriteCSVPrepareBatch(ClientContext &context, Funct //===--------------------------------------------------------------------===// // Flush Batch //===--------------------------------------------------------------------===// -void WriteCSVFlushBatch(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +void WriteCSVFlushBatch(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, PreparedBatchData &batch) { auto &csv_batch = batch.Cast(); auto &global_state = gstate.Cast(); diff --git a/src/duckdb/src/function/table/read_csv.cpp b/src/duckdb/src/function/table/read_csv.cpp index f09127d84..805ddc73d 100644 --- a/src/duckdb/src/function/table/read_csv.cpp +++ b/src/duckdb/src/function/table/read_csv.cpp @@ -109,7 +109,7 @@ void ReadCSVTableFunction::ReadCSVAddNamedParameters(TableFunction &table_functi }); } -static void CSVReaderSerialize(Serializer &serializer, const optional_ptr bind_data_p, +static void CSVReaderSerialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundTableFunction &function) { throw NotImplementedException("CSVReaderSerialize not implemented"); // auto &bind_data = bind_data_p->Cast(); @@ -156,7 +156,7 @@ static bool PushdownProjectionExpression(ClientContext &context, const TableFunc } const auto &cast = input.expr.Cast(); const auto &target_type = cast.GetReturnType(); - auto &bind_data = input.get.bind_data->Cast(); + auto &bind_data = input.get.bind_data.write().Cast(); // With a custom schema (the 'schema' option, or a MultiFileReader that binds its own schema) the files are mapped // onto that schema, not onto bind_data.columns, so retyping the columns would not reach the column mapping. // See test/optimizer/pushdown/csv_type_pushdown_schema.test @@ -189,7 +189,7 @@ static bool PushdownProjectionExpressionMultiFile(ClientContext &context, if (!PushdownProjectionExpression(context, input)) { return false; } - auto &bind_data = input.get.bind_data->Cast(); + auto &bind_data = input.get.bind_data.write().Cast(); auto &data = bind_data.bind_data->Cast(); const idx_t idx = input.get.GetColumnIds()[input.column_index].GetPrimaryIndex(); if (idx < data.options.expected_types.size()) { diff --git a/src/duckdb/src/function/table/read_duckdb.cpp b/src/duckdb/src/function/table/read_duckdb.cpp index 9626ae7f6..ec4f57a4d 100644 --- a/src/duckdb/src/function/table/read_duckdb.cpp +++ b/src/duckdb/src/function/table/read_duckdb.cpp @@ -528,7 +528,7 @@ void ReadDuckDBAddNamedParameters(TableFunction &table_function) { }); } -static vector DuckDBGetRowIdColumns(ClientContext &, optional_ptr) { +static vector DuckDBGetRowIdColumns(ClientContext &, optional_ptr) { vector result; result.emplace_back(MultiFileReader::COLUMN_IDENTIFIER_FILE_INDEX); result.emplace_back(COLUMN_IDENTIFIER_ROW_ID); diff --git a/src/duckdb/src/function/table/system/create_external_resource.cpp b/src/duckdb/src/function/table/system/create_external_resource.cpp index f8250b833..80b4cf822 100644 --- a/src/duckdb/src/function/table/system/create_external_resource.cpp +++ b/src/duckdb/src/function/table/system/create_external_resource.cpp @@ -289,7 +289,8 @@ static void CreateExternalResourceFunction(ClientContext &context, TableFunction auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(bind_data.timeout_seconds); while (true) { // Cooperative cancellation: this blocking loop never yields back to the executor, so surface a - // pending Ctrl-C / max_execution_time ourselves (InterruptCheck throws InterruptException on either). + // pending Ctrl-C / max_execution_time ourselves. Polls are seconds apart, so the throttled + // FastInterruptCheck() would almost never look at the deadline here. context.InterruptCheck(); auto status_sql = "SELECT state, result FROM " + QualifiedName::Parse(type->status_function).ToString() + "(" + handle.ToSQLString() + ")"; @@ -332,8 +333,8 @@ static void CreateExternalResourceFunction(ClientContext &context, TableFunction break; } // Interruptible wait: sleep the poll interval in short slices, checking for cancellation between them. - // The slice is small so InterruptCheck() is called often enough to honor max_execution_time promptly - // (its deadline check is throttled to run every Nth call). + // FastInterruptCheck() only reads the clock every 256th call, which would delay noticing max_execution_time + // by more than a second at this slice size, so the deadline is checked on every slice. auto poll_until = std::chrono::steady_clock::now() + std::chrono::seconds(bind_data.poll_interval_seconds); while (std::chrono::steady_clock::now() < poll_until) { context.InterruptCheck(); diff --git a/src/duckdb/src/function/table/system/duckdb_columns.cpp b/src/duckdb/src/function/table/system/duckdb_columns.cpp index 2428f4fb0..300ca954d 100644 --- a/src/duckdb/src/function/table/system/duckdb_columns.cpp +++ b/src/duckdb/src/function/table/system/duckdb_columns.cpp @@ -92,7 +92,10 @@ static unique_ptr DuckDBColumnsBind(ClientContext &context, TableF names.emplace_back("generation_expression"); return_types.emplace_back(LogicalType::VARCHAR); - return SystemCatalogScanner::CreateBindData(names, return_types, "table_name", "table_oid"); + SystemCatalogIdentityColumns columns; + columns.entry_name = "table_name"; + columns.entry_oid = "table_oid"; + return SystemCatalogScanner::CreateBindData(names, return_types, columns); } static unique_ptr DuckDBColumnsInit(ClientContext &context, TableFunctionInitInput &input) { diff --git a/src/duckdb/src/function/table/system/duckdb_databases.cpp b/src/duckdb/src/function/table/system/duckdb_databases.cpp index 36a5c7bd1..09a7ad53a 100644 --- a/src/duckdb/src/function/table/system/duckdb_databases.cpp +++ b/src/duckdb/src/function/table/system/duckdb_databases.cpp @@ -10,7 +10,8 @@ struct DuckDBDatabasesData : public GlobalTableFunctionState { DuckDBDatabasesData() : offset(0) { } - vector> entries; + //! Rows are materialized at init so that no database reference outlives it + vector> rows; idx_t offset; }; @@ -51,85 +52,72 @@ static unique_ptr DuckDBDatabasesBind(ClientContext &context, Tabl return nullptr; } -unique_ptr DuckDBDatabasesInit(ClientContext &context, TableFunctionInitInput &input) { - auto result = make_uniq(); - - // scan all the schemas for tables and collect them and collect them - auto &db_manager = DatabaseManager::Get(context); - result->entries = db_manager.GetDatabases(context); - return std::move(result); -} - -void DuckDBDatabasesFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { - auto &data = data_p.global_state->Cast(); - if (data.offset >= data.entries.size()) { - // finished returning values - return; +static vector DuckDBDatabasesRow(AttachedDatabase &attached) { + auto &catalog = attached.GetCatalog(); + bool is_internal = attached.IsSystem() || attached.IsTemporary(); + string cipher_str; + Value db_path; + if (!is_internal) { + bool in_memory = catalog.InMemory(); + if (!in_memory) { + db_path = Value(catalog.GetDBPath()); + } + if (catalog.IsEncrypted()) { + cipher_str = catalog.GetEncryptionCipher(); + } } - // start returning values - // either fill up the chunk or return all the remaining columns - idx_t count = 0; - + InsertionOrderPreservingMap options_map; + for (const auto &option : attached.GetAttachOptions()) { + options_map.insert(option.first, option.second.ToString()); + } + vector row; // database_name, VARCHAR - auto &database_name = output.data[0]; + row.push_back(Value(attached.GetName())); // database_oid, BIGINT - auto &database_oid = output.data[1]; + row.push_back(Value::BIGINT(NumericCast(attached.oid))); // path, VARCHAR - auto &path = output.data[2]; + row.push_back(std::move(db_path)); // comment, VARCHAR - auto &comment = output.data[3]; + row.push_back(Value(attached.comment)); // tags, MAP - auto &tags = output.data[4]; + row.push_back(Value::MAP(attached.tags)); // internal, BOOLEAN - auto &internal = output.data[5]; + row.push_back(Value::BOOLEAN(is_internal)); // type, VARCHAR - auto &type = output.data[6]; + row.push_back(Value(catalog.GetCatalogType())); // readonly, BOOLEAN - auto &readonly = output.data[7]; + row.push_back(Value::BOOLEAN(attached.IsReadOnly())); // encrypted, BOOLEAN - auto &encrypted = output.data[8]; + row.push_back(Value::BOOLEAN(catalog.IsEncrypted())); // cipher, VARCHAR - auto &cipher = output.data[9]; + row.push_back(cipher_str.empty() ? Value() : Value(cipher_str)); // options, MAP - auto &options = output.data[10]; - - while (data.offset < data.entries.size() && count < STANDARD_VECTOR_SIZE) { - auto &entry = data.entries[data.offset++]; - auto &attached = *entry; - auto &catalog = attached.GetCatalog(); - if (attached.GetVisibility() == AttachVisibility::HIDDEN) { - continue; - } + row.push_back(Value::MAP(options_map)); + return row; +} - database_name.Append(Value(attached.GetName())); - database_oid.Append(Value::BIGINT(NumericCast(attached.oid))); - bool is_internal = attached.IsSystem() || attached.IsTemporary(); - bool is_readonly = attached.IsReadOnly(); - string cipher_str; - Value db_path; - if (!is_internal) { - bool in_memory = catalog.InMemory(); - if (!in_memory) { - db_path = Value(catalog.GetDBPath()); - } - if (catalog.IsEncrypted()) { - cipher_str = catalog.GetEncryptionCipher(); - } - } - path.Append(db_path); - comment.Append(Value(attached.comment)); - tags.Append(Value::MAP(attached.tags)); - internal.Append(Value::BOOLEAN(is_internal)); - type.Append(Value(catalog.GetCatalogType())); - readonly.Append(Value::BOOLEAN(is_readonly)); - encrypted.Append(Value::BOOLEAN(catalog.IsEncrypted())); - cipher.Append(cipher_str.empty() ? Value() : Value(cipher_str)); - InsertionOrderPreservingMap options_map; - for (const auto &option : attached.GetAttachOptions()) { - options_map.insert(option.first, option.second.ToString()); +unique_ptr DuckDBDatabasesInit(ClientContext &context, TableFunctionInitInput &input) { + auto result = make_uniq(); + + auto &db_manager = DatabaseManager::Get(context); + for (auto &entry : db_manager.GetDatabases(context)) { + if (entry->GetVisibility() != AttachVisibility::HIDDEN) { + result->rows.push_back(DuckDBDatabasesRow(*entry)); } - options.Append(Value::MAP(options_map)); + // a concurrent DETACH can have left this as the last reference + AttachedDatabase::InvokeCloseIfLastReference(entry, context); + } + return std::move(result); +} +void DuckDBDatabasesFunction(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++]; + for (idx_t col = 0; col < row.size(); col++) { + output.data[col].Append(row[col]); + } count++; } } diff --git a/src/duckdb/src/function/table/system/duckdb_functions.cpp b/src/duckdb/src/function/table/system/duckdb_functions.cpp index 231148f80..6dcb304a4 100644 --- a/src/duckdb/src/function/table/system/duckdb_functions.cpp +++ b/src/duckdb/src/function/table/system/duckdb_functions.cpp @@ -1,4 +1,5 @@ #include "duckdb/function/table/system_functions.hpp" +#include "duckdb/function/table/system_catalog_scanner.hpp" #include "duckdb/common/atomic.hpp" #include "duckdb/catalog/catalog.hpp" @@ -31,6 +32,7 @@ struct DuckDBFunctionsData : public GlobalTableFunctionState { idx_t offset_in_entry; //! The offset, published once per chunk (for progress) atomic progress_offset {0}; + SystemCatalogScannerStats stats; }; static unique_ptr DuckDBFunctionsBind(ClientContext &context, TableFunctionBindInput &input, @@ -98,32 +100,33 @@ static unique_ptr DuckDBFunctionsBind(ClientContext &context, Tabl names.emplace_back("categories"); return_types.emplace_back(LogicalType::LIST(LogicalType::VARCHAR)); - return nullptr; -} - -static void ExtractFunctionsFromSchema(ClientContext &context, SchemaCatalogEntry &schema, - DuckDBFunctionsData &result) { - schema.Scan(context, CatalogType::SCALAR_FUNCTION_ENTRY, - [&](CatalogEntry &entry) { result.entries.push_back(entry); }); - schema.Scan(context, CatalogType::TABLE_FUNCTION_ENTRY, - [&](CatalogEntry &entry) { result.entries.push_back(entry); }); - schema.Scan(context, CatalogType::PRAGMA_FUNCTION_ENTRY, - [&](CatalogEntry &entry) { result.entries.push_back(entry); }); + // database_oid is VARCHAR here and there is no schema_oid, so neither is an identity column + SystemCatalogIdentityColumns columns; + columns.entry_name = "function_name"; + columns.entry_oid = "function_oid"; + return SystemCatalogScanner::CreateBindData(names, return_types, columns); } unique_ptr DuckDBFunctionsInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); - // scan all the schemas for tables and collect them and collect them - auto schemas = Catalog::GetAllSchemas(context); + // collect the functions of the schemas that survive the pushed-down filters; the schemas are enumerated once and + // each is scanned for the three function entry types + auto schemas = SystemCatalogScanner::GetSchemas(context, input, result->stats); + auto filters = SystemCatalogScanner::GetEntryFilters(input); for (auto &schema : schemas) { - ExtractFunctionsFromSchema(context, schema.get(), *result); - }; + for (auto type : {CatalogType::SCALAR_FUNCTION_ENTRY, CatalogType::TABLE_FUNCTION_ENTRY, + CatalogType::PRAGMA_FUNCTION_ENTRY}) { + auto entries = SystemCatalogScanner::GetSchemaEntries(context, schema.get(), type, filters, result->stats); + result->entries.insert(result->entries.end(), entries.begin(), entries.end()); + } + } - std::sort(result->entries.begin(), result->entries.end(), - [&](reference a, reference b) { - return (int32_t)a.get().type < (int32_t)b.get().type; - }); + // stable so that a filtered result is a subsequence of the unfiltered one + std::stable_sort(result->entries.begin(), result->entries.end(), + [&](reference a, reference b) { + return (int32_t)a.get().type < (int32_t)b.get().type; + }); return std::move(result); } @@ -848,8 +851,14 @@ static double DuckDBFunctionsProgress(ClientContext &context, const FunctionData return 100.0 * static_cast(offset) / static_cast(data.entries.size()); } +static void DuckDBFunctionsGetMetrics(TableFunctionGetMetricsInput &input) { + SystemCatalogScanner::ReportMetrics(input, input.global_state->Cast().stats); +} + void DuckDBFunctionsFun::RegisterFunction(BuiltinFunctions &set) { TableFunction functions("duckdb_functions", {}, DuckDBFunctionsFunction, DuckDBFunctionsBind, DuckDBFunctionsInit); + SystemCatalogScanner::RegisterPushdown(functions); + functions.get_metrics = DuckDBFunctionsGetMetrics; functions.table_scan_progress = DuckDBFunctionsProgress; set.AddFunction(functions); } diff --git a/src/duckdb/src/function/table/system/duckdb_indexes.cpp b/src/duckdb/src/function/table/system/duckdb_indexes.cpp index b68505254..bb46cc9f5 100644 --- a/src/duckdb/src/function/table/system/duckdb_indexes.cpp +++ b/src/duckdb/src/function/table/system/duckdb_indexes.cpp @@ -3,6 +3,7 @@ #include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/common/exception.hpp" +#include "duckdb/function/table/system_catalog_scanner.hpp" #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/client_data.hpp" @@ -14,6 +15,7 @@ struct DuckDBIndexesData : public GlobalTableFunctionState { vector> entries; idx_t offset; + SystemCatalogScannerStats stats; }; static unique_ptr DuckDBIndexesBind(ClientContext &context, TableFunctionBindInput &input, @@ -60,18 +62,18 @@ static unique_ptr DuckDBIndexesBind(ClientContext &context, TableF names.emplace_back("sql"); return_types.emplace_back(LogicalType::VARCHAR); - return nullptr; + // table_name and table_oid describe the index's parent table, not the index, so they are not identity columns + SystemCatalogIdentityColumns columns; + columns.entry_name = "index_name"; + columns.entry_oid = "index_oid"; + return SystemCatalogScanner::CreateBindData(names, return_types, columns); } unique_ptr DuckDBIndexesInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); - // scan all the schemas for tables and collect them - auto schemas = Catalog::GetAllSchemas(context); - for (auto &schema : schemas) { - schema.get().Scan(context, CatalogType::INDEX_ENTRY, - [&](CatalogEntry &entry) { result->entries.push_back(entry); }); - }; + // collect the indexes that survive the pushed-down filters + result->entries = SystemCatalogScanner::GetEntries(context, input, CatalogType::INDEX_ENTRY, result->stats); return std::move(result); } @@ -157,8 +159,15 @@ void DuckDBIndexesFunction(ClientContext &context, TableFunctionInput &data_p, D } } +static void DuckDBIndexesGetMetrics(TableFunctionGetMetricsInput &input) { + SystemCatalogScanner::ReportMetrics(input, input.global_state->Cast().stats); +} + void DuckDBIndexesFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("duckdb_indexes", {}, DuckDBIndexesFunction, DuckDBIndexesBind, DuckDBIndexesInit)); + TableFunction indexes("duckdb_indexes", {}, DuckDBIndexesFunction, DuckDBIndexesBind, DuckDBIndexesInit); + SystemCatalogScanner::RegisterPushdown(indexes); + indexes.get_metrics = DuckDBIndexesGetMetrics; + set.AddFunction(indexes); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_schemas.cpp b/src/duckdb/src/function/table/system/duckdb_schemas.cpp index 9dd7fb568..02f8dc980 100644 --- a/src/duckdb/src/function/table/system/duckdb_schemas.cpp +++ b/src/duckdb/src/function/table/system/duckdb_schemas.cpp @@ -3,6 +3,7 @@ #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" #include "duckdb/common/exception.hpp" +#include "duckdb/function/table/system_catalog_scanner.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/client_data.hpp" @@ -14,6 +15,7 @@ struct DuckDBSchemasData : public GlobalTableFunctionState { vector> entries; idx_t offset; + SystemCatalogScannerStats stats; }; static unique_ptr DuckDBSchemasBind(ClientContext &context, TableFunctionBindInput &input, @@ -48,14 +50,17 @@ static unique_ptr DuckDBSchemasBind(ClientContext &context, TableF names.emplace_back("parent_schema_oid"); return_types.emplace_back(LogicalType::BIGINT); - return nullptr; + // the schema's own oid is in the column named oid + SystemCatalogIdentityColumns columns; + columns.schema_oid = "oid"; + return SystemCatalogScanner::CreateBindData(names, return_types, columns); } unique_ptr DuckDBSchemasInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); - // scan all the schemas and collect them - result->entries = Catalog::GetAllSchemas(context); + // collect the schemas that survive the pushed-down filters + result->entries = SystemCatalogScanner::GetSchemas(context, input, result->stats); return std::move(result); } @@ -116,8 +121,15 @@ void DuckDBSchemasFunction(ClientContext &context, TableFunctionInput &data_p, D } } +static void DuckDBSchemasGetMetrics(TableFunctionGetMetricsInput &input) { + SystemCatalogScanner::ReportMetrics(input, input.global_state->Cast().stats); +} + void DuckDBSchemasFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction(TableFunction("duckdb_schemas", {}, DuckDBSchemasFunction, DuckDBSchemasBind, DuckDBSchemasInit)); + TableFunction schemas("duckdb_schemas", {}, DuckDBSchemasFunction, DuckDBSchemasBind, DuckDBSchemasInit); + SystemCatalogScanner::RegisterPushdown(schemas); + schemas.get_metrics = DuckDBSchemasGetMetrics; + set.AddFunction(schemas); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_sequences.cpp b/src/duckdb/src/function/table/system/duckdb_sequences.cpp index af589fc83..2e1cf29f9 100644 --- a/src/duckdb/src/function/table/system/duckdb_sequences.cpp +++ b/src/duckdb/src/function/table/system/duckdb_sequences.cpp @@ -5,6 +5,7 @@ #include "duckdb/catalog/catalog_entry/sequence_catalog_entry.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/numeric_utils.hpp" +#include "duckdb/function/table/system_catalog_scanner.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/client_data.hpp" @@ -14,8 +15,9 @@ struct DuckDBSequencesData : public GlobalTableFunctionState { DuckDBSequencesData() : offset(0) { } - vector> entries; + vector> entries; idx_t offset; + SystemCatalogScannerStats stats; }; static unique_ptr DuckDBSequencesBind(ClientContext &context, TableFunctionBindInput &input, @@ -68,18 +70,17 @@ static unique_ptr DuckDBSequencesBind(ClientContext &context, Tabl names.emplace_back("sql"); return_types.emplace_back(LogicalType::VARCHAR); - return nullptr; + SystemCatalogIdentityColumns columns; + columns.entry_name = "sequence_name"; + columns.entry_oid = "sequence_oid"; + return SystemCatalogScanner::CreateBindData(names, return_types, columns); } unique_ptr DuckDBSequencesInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); - // scan all the schemas for tables and collect themand collect them - auto schemas = Catalog::GetAllSchemas(context); - for (auto &schema : schemas) { - schema.get().Scan(context, CatalogType::SEQUENCE_ENTRY, - [&](CatalogEntry &entry) { result->entries.push_back(entry.Cast()); }); - }; + // collect the sequences that survive the pushed-down filters + result->entries = SystemCatalogScanner::GetEntries(context, input, CatalogType::SEQUENCE_ENTRY, result->stats); return std::move(result); } @@ -127,7 +128,7 @@ void DuckDBSequencesFunction(ClientContext &context, TableFunctionInput &data_p, auto &sql = output.data[15]; while (data.offset < data.entries.size() && count < STANDARD_VECTOR_SIZE) { - auto &seq = data.entries[data.offset++].get(); + auto &seq = data.entries[data.offset++].get().Cast(); auto seq_data = seq.GetData(); database_name.Append(Value(seq.catalog.GetName())); @@ -155,9 +156,15 @@ void DuckDBSequencesFunction(ClientContext &context, TableFunctionInput &data_p, } } +static void DuckDBSequencesGetMetrics(TableFunctionGetMetricsInput &input) { + SystemCatalogScanner::ReportMetrics(input, input.global_state->Cast().stats); +} + void DuckDBSequencesFun::RegisterFunction(BuiltinFunctions &set) { auto function = TableFunction("duckdb_sequences", {}, DuckDBSequencesFunction, DuckDBSequencesBind, DuckDBSequencesInit); + SystemCatalogScanner::RegisterPushdown(function); + function.get_metrics = DuckDBSequencesGetMetrics; set.AddFunction(std::move(function)); } diff --git a/src/duckdb/src/function/table/system/duckdb_settings.cpp b/src/duckdb/src/function/table/system/duckdb_settings.cpp index 65e0a0c8b..d91f2dfdd 100644 --- a/src/duckdb/src/function/table/system/duckdb_settings.cpp +++ b/src/duckdb/src/function/table/system/duckdb_settings.cpp @@ -114,7 +114,7 @@ unique_ptr DuckDBSettingsInit(ClientContext &context, if (lookup_result) { scope = lookup_result.GetScope(); } else { - value.value = option->default_value; + value.value = Value(option->GetDefaultValue(DBConfig::GetConfig(context)).ToString()); } } if (option->scope == SettingScopeTarget::LOCAL_ONLY) { diff --git a/src/duckdb/src/function/table/system/duckdb_tables.cpp b/src/duckdb/src/function/table/system/duckdb_tables.cpp index fcb4c42e6..78d0ea313 100644 --- a/src/duckdb/src/function/table/system/duckdb_tables.cpp +++ b/src/duckdb/src/function/table/system/duckdb_tables.cpp @@ -73,7 +73,10 @@ static unique_ptr DuckDBTablesBind(ClientContext &context, TableFu names.emplace_back("sql"); return_types.emplace_back(LogicalType::VARCHAR); - return SystemCatalogScanner::CreateBindData(names, return_types, "table_name", "table_oid"); + SystemCatalogIdentityColumns columns; + columns.entry_name = "table_name"; + columns.entry_oid = "table_oid"; + return SystemCatalogScanner::CreateBindData(names, return_types, columns); } unique_ptr DuckDBTablesInit(ClientContext &context, TableFunctionInitInput &input) { diff --git a/src/duckdb/src/function/table/system/duckdb_triggers.cpp b/src/duckdb/src/function/table/system/duckdb_triggers.cpp index b4bd09e49..67c08d855 100644 --- a/src/duckdb/src/function/table/system/duckdb_triggers.cpp +++ b/src/duckdb/src/function/table/system/duckdb_triggers.cpp @@ -6,6 +6,7 @@ #include "duckdb/catalog/catalog_entry/trigger_catalog_entry.hpp" #include "duckdb/common/enum_util.hpp" #include "duckdb/common/exception.hpp" +#include "duckdb/function/table/system_catalog_scanner.hpp" namespace duckdb { @@ -15,6 +16,7 @@ struct DuckDBTriggersData : public GlobalTableFunctionState { vector> entries; idx_t offset; + SystemCatalogScannerStats stats; }; static unique_ptr DuckDBTriggersBind(ClientContext &context, TableFunctionBindInput &input, @@ -64,13 +66,15 @@ static unique_ptr DuckDBTriggersBind(ClientContext &context, Table names.emplace_back("sql"); return_types.emplace_back(LogicalType::VARCHAR); - return nullptr; + // triggers are found through their tables, so only the catalog and schema columns are identity columns + return SystemCatalogScanner::CreateBindData(names, return_types); } unique_ptr DuckDBTriggersInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); - auto schemas = Catalog::GetAllSchemas(context); + // scan the tables of the schemas that survive the pushed-down filters + auto schemas = SystemCatalogScanner::GetSchemas(context, input, result->stats); vector> tables; for (auto &schema : schemas) { schema.get().Scan(context, CatalogType::TABLE_ENTRY, [&](CatalogEntry &entry) { @@ -142,9 +146,15 @@ void DuckDBTriggersFunction(ClientContext &context, TableFunctionInput &data_p, } } +static void DuckDBTriggersGetMetrics(TableFunctionGetMetricsInput &input) { + SystemCatalogScanner::ReportMetrics(input, input.global_state->Cast().stats); +} + void DuckDBTriggersFun::RegisterFunction(BuiltinFunctions &set) { - set.AddFunction( - TableFunction("duckdb_triggers", {}, DuckDBTriggersFunction, DuckDBTriggersBind, DuckDBTriggersInit)); + TableFunction triggers("duckdb_triggers", {}, DuckDBTriggersFunction, DuckDBTriggersBind, DuckDBTriggersInit); + SystemCatalogScanner::RegisterPushdown(triggers); + triggers.get_metrics = DuckDBTriggersGetMetrics; + set.AddFunction(triggers); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_views.cpp b/src/duckdb/src/function/table/system/duckdb_views.cpp index 54ef6b49c..df11036e9 100644 --- a/src/duckdb/src/function/table/system/duckdb_views.cpp +++ b/src/duckdb/src/function/table/system/duckdb_views.cpp @@ -61,7 +61,10 @@ static unique_ptr DuckDBViewsBind(ClientContext &context, TableFun names.emplace_back("is_bound"); return_types.emplace_back(LogicalType::BOOLEAN); - return SystemCatalogScanner::CreateBindData(names, return_types, "view_name", "view_oid"); + SystemCatalogIdentityColumns columns; + columns.entry_name = "view_name"; + columns.entry_oid = "view_oid"; + return SystemCatalogScanner::CreateBindData(names, return_types, columns); } unique_ptr DuckDBViewsInit(ClientContext &context, TableFunctionInitInput &input) { diff --git a/src/duckdb/src/function/table/system/logging_utils.cpp b/src/duckdb/src/function/table/system/logging_utils.cpp index 160451619..cf5baf9b4 100644 --- a/src/duckdb/src/function/table/system/logging_utils.cpp +++ b/src/duckdb/src/function/table/system/logging_utils.cpp @@ -1,6 +1,5 @@ #include "duckdb/function/table/system_functions.hpp" -#include "duckdb/catalog/catalog_entry/collate_catalog_entry.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/function/table_function.hpp" #include "duckdb/logging/log_manager.hpp" diff --git a/src/duckdb/src/function/table/system/pragma_collations.cpp b/src/duckdb/src/function/table/system/pragma_collations.cpp index 29c02abfb..ae4af6ea5 100644 --- a/src/duckdb/src/function/table/system/pragma_collations.cpp +++ b/src/duckdb/src/function/table/system/pragma_collations.cpp @@ -1,7 +1,7 @@ #include "duckdb/function/table/system_functions.hpp" #include "duckdb/catalog/catalog.hpp" -#include "duckdb/catalog/catalog_entry/collate_catalog_entry.hpp" +#include "duckdb/planner/collation_binding.hpp" #include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" #include "duckdb/common/exception.hpp" @@ -26,11 +26,7 @@ static unique_ptr PragmaCollateBind(ClientContext &context, TableF unique_ptr PragmaCollateInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); - auto schemas = Catalog::GetAllSchemas(context); - for (auto schema : schemas) { - schema.get().Scan(context, CatalogType::COLLATION_ENTRY, - [&](CatalogEntry &entry) { result->entries.push_back(entry.name.GetIdentifierName()); }); - } + result->entries = CollationFunctions::GetCollations(context); return std::move(result); } diff --git a/src/duckdb/src/function/table/system/pragma_database_size.cpp b/src/duckdb/src/function/table/system/pragma_database_size.cpp index f2efdb8dc..3027743cd 100644 --- a/src/duckdb/src/function/table/system/pragma_database_size.cpp +++ b/src/duckdb/src/function/table/system/pragma_database_size.cpp @@ -6,6 +6,7 @@ #include "duckdb/main/attached_database.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/storage/buffer_manager.hpp" +#include "duckdb/storage/database_size.hpp" #include "duckdb/storage/block_manager.hpp" #include "duckdb/storage/storage_info.hpp" #include "duckdb/storage/storage_manager.hpp" @@ -17,7 +18,8 @@ struct PragmaDatabaseSizeData : public GlobalTableFunctionState { } idx_t index; - vector> databases; + //! Rows are materialized at init so that no database reference outlives it + vector> databases; Value memory_usage; Value memory_limit; }; @@ -56,7 +58,14 @@ static unique_ptr PragmaDatabaseSizeBind(ClientContext &context, T unique_ptr PragmaDatabaseSizeInit(ClientContext &context, TableFunctionInitInput &input) { auto result = make_uniq(); - result->databases = DatabaseManager::Get(context).GetDatabases(context); + for (auto &entry : DatabaseManager::Get(context).GetDatabases(context)) { + auto &db = *entry; + if (!db.IsSystem() && !db.IsTemporary() && db.GetVisibility() != AttachVisibility::HIDDEN) { + result->databases.emplace_back(db.GetName(), db.GetCatalog().GetDatabaseSize(context)); + } + // a concurrent DETACH can have left this as the last reference + AttachedDatabase::InvokeCloseIfLastReference(entry, context); + } auto &buffer_manager = BufferManager::GetBufferManager(context); result->memory_usage = Value(StringUtil::BytesToHumanReadableString(buffer_manager.GetUsedMemory())); auto max_memory = buffer_manager.GetMaxMemory(); @@ -81,12 +90,8 @@ void PragmaDatabaseSizeFunction(ClientContext &context, TableFunctionInput &data auto &memory_limit = output.data[8]; for (; data.index < data.databases.size() && row < STANDARD_VECTOR_SIZE; data.index++) { - auto &db = *data.databases[data.index]; - if (db.IsSystem() || db.IsTemporary() || db.GetVisibility() == AttachVisibility::HIDDEN) { - continue; - } - auto ds = db.GetCatalog().GetDatabaseSize(context); - database_name.Append(Value(db.GetName())); + auto &ds = data.databases[data.index].second; + database_name.Append(Value(data.databases[data.index].first)); database_size.Append(Value(StringUtil::BytesToHumanReadableString(ds.bytes))); block_size.Append(Value::BIGINT(NumericCast(ds.block_size))); total_blocks.Append(Value::BIGINT(NumericCast(ds.total_blocks))); diff --git a/src/duckdb/src/function/table/system/system_catalog_scanner.cpp b/src/duckdb/src/function/table/system/system_catalog_scanner.cpp index f3d7b8b03..c401b3d8b 100644 --- a/src/duckdb/src/function/table/system/system_catalog_scanner.cpp +++ b/src/duckdb/src/function/table/system/system_catalog_scanner.cpp @@ -53,26 +53,30 @@ static bool IsIdentityType(const LogicalType &type, bool is_oid) { return type.id() == (is_oid ? LogicalTypeId::BIGINT : LogicalTypeId::VARCHAR); } +// whether `name` is the identity column called `column`; a null `column` means the function has no such column +static bool MatchesIdentityColumn(const Identifier &name, const LogicalType &type, const char *column, bool is_oid) { + return column && name == column && IsIdentityType(type, is_oid); +} + unique_ptr SystemCatalogScanner::CreateBindData(const vector &names, const vector &return_types, - const char *entry_name_column, - const char *entry_oid_column) { + const SystemCatalogIdentityColumns &columns) { D_ASSERT(names.size() == return_types.size()); auto result = make_uniq(); for (idx_t i = 0; i < names.size(); i++) { auto &name = names[i]; auto &type = return_types[i]; - if (name == "database_name" && IsIdentityType(type, false)) { + if (MatchesIdentityColumn(name, type, columns.database_name, false)) { result->database_name_idx = i; - } else if (name == "database_oid" && IsIdentityType(type, true)) { + } else if (MatchesIdentityColumn(name, type, columns.database_oid, true)) { result->database_oid_idx = i; - } else if (name == "schema_name" && IsIdentityType(type, false)) { + } else if (MatchesIdentityColumn(name, type, columns.schema_name, false)) { result->schema_name_idx = i; - } else if (name == "schema_oid" && IsIdentityType(type, true)) { + } else if (MatchesIdentityColumn(name, type, columns.schema_oid, true)) { result->schema_oid_idx = i; - } else if (entry_name_column && name == entry_name_column && IsIdentityType(type, false)) { + } else if (MatchesIdentityColumn(name, type, columns.entry_name, false)) { result->entry_name_idx = i; - } else if (entry_oid_column && name == entry_oid_column && IsIdentityType(type, true)) { + } else if (MatchesIdentityColumn(name, type, columns.entry_oid, true)) { result->entry_oid_idx = i; } } diff --git a/src/duckdb/src/function/table/system/test_all_types.cpp b/src/duckdb/src/function/table/system/test_all_types.cpp index a7ceecdfc..7b27725d7 100644 --- a/src/duckdb/src/function/table/system/test_all_types.cpp +++ b/src/duckdb/src/function/table/system/test_all_types.cpp @@ -58,16 +58,33 @@ vector TestAllTypesFun::GetTestTypes(const bool use_large_enum, const result.emplace_back(LogicalType::BIGNUM, "bignum"); } - // Time-types. - result.emplace_back(LogicalType::DATE, "date"); + // Time-types, using the smallest/largest finite values. + const auto min_date = Date::FromDate(Date::DATE_MIN_YEAR, Date::DATE_MIN_MONTH, Date::DATE_MIN_DAY); + const auto max_date = Date::FromDate(Date::DATE_MAX_YEAR, Date::DATE_MAX_MONTH, Date::DATE_MAX_DAY); + const auto min_ts = Timestamp::FromDatetime( + Date::FromDate(Timestamp::MIN_YEAR, Timestamp::MIN_MONTH, Timestamp::MIN_DAY), dtime_t(0)); + const auto max_ts = timestamp_t(NumericLimits::Maximum() - 1); + // Clear the fractional day. + const auto min_ns = NumericLimits::Minimum() / Interval::NANOS_PER_DAY * Interval::NANOS_PER_DAY; + const auto max_ns = NumericLimits::Maximum() - 1; + + result.emplace_back(LogicalType::DATE, "date", Value::DATE(min_date), Value::DATE(max_date)); result.emplace_back(LogicalType::TIME, "time"); - result.emplace_back(LogicalType::TIMESTAMP, "timestamp"); - result.emplace_back(LogicalType::TIMESTAMP_S, "timestamp_s"); - result.emplace_back(LogicalType::TIMESTAMP_MS, "timestamp_ms"); - result.emplace_back(LogicalType::TIMESTAMP_NS, "timestamp_ns"); + result.emplace_back(LogicalType::TIMESTAMP, "timestamp", Value::TIMESTAMP(min_ts), Value::TIMESTAMP(max_ts)); + result.emplace_back(LogicalType::TIMESTAMP_S, "timestamp_s", + Value::TIMESTAMPSEC(timestamp_sec_t(min_ts.value / Interval::MICROS_PER_SEC)), + Value::TIMESTAMPSEC(timestamp_sec_t(max_ts.value / Interval::MICROS_PER_SEC))); + result.emplace_back(LogicalType::TIMESTAMP_MS, "timestamp_ms", + Value::TIMESTAMPMS(timestamp_ms_t(min_ts.value / Interval::MICROS_PER_MSEC)), + Value::TIMESTAMPMS(timestamp_ms_t(max_ts.value / Interval::MICROS_PER_MSEC))); + result.emplace_back(LogicalType::TIMESTAMP_NS, "timestamp_ns", Value::TIMESTAMPNS(timestamp_ns_t(min_ns)), + Value::TIMESTAMPNS(timestamp_ns_t(max_ns))); result.emplace_back(LogicalType::TIME_TZ, "time_tz"); - result.emplace_back(LogicalType::TIMESTAMP_TZ, "timestamp_tz"); - result.emplace_back(LogicalType::TIMESTAMP_TZ_NS, "timestamp_tz_ns"); + result.emplace_back(LogicalType::TIMESTAMP_TZ, "timestamp_tz", Value::TIMESTAMPTZ(timestamp_tz_t(min_ts)), + Value::TIMESTAMPTZ(timestamp_tz_t(max_ts))); + result.emplace_back(LogicalType::TIMESTAMP_TZ_NS, "timestamp_tz_ns", + Value::TIMESTAMPTZNS(timestamp_tz_ns_t(min_ns)), + Value::TIMESTAMPTZNS(timestamp_tz_ns_t(max_ns))); // More complex numeric types. result.emplace_back(LogicalType::FLOAT, "float", Value::FLOAT(std::numeric_limits::lowest()), @@ -377,6 +394,12 @@ vector TestAllTypesFun::GetTestTypes(const bool use_large_enum, const auto max_tuple_val = Value::TUPLE({Value::INTEGER(42), Value("🦆🦆🦆🦆🦆🦆")}); result.emplace_back(tuple_type, "tuple", min_tuple_val, max_tuple_val); + // geography - added last so existing column positions are unchanged + // coordinates stay within the canonical GEOGRAPHY ranges + auto min_geography = Value("POINT EMPTY").DefaultCastAs(LogicalType::GEOGRAPHY()); + auto max_geography = Value("LINESTRING (-180 -90, 180 90)").DefaultCastAs(LogicalType::GEOGRAPHY()); + result.emplace_back(LogicalType::GEOGRAPHY(), "geography", min_geography, max_geography); + return result; } diff --git a/src/duckdb/src/function/table/table_scan.cpp b/src/duckdb/src/function/table/table_scan.cpp index a834e7db8..4d5003f0c 100644 --- a/src/duckdb/src/function/table/table_scan.cpp +++ b/src/duckdb/src/function/table/table_scan.cpp @@ -1,4 +1,7 @@ #include "duckdb/function/table/table_scan.hpp" +#include "duckdb/function/table/native_scan_job.hpp" +#include "duckdb/parallel/task_scheduler.hpp" +#include "duckdb/storage/block_allocator.hpp" #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" @@ -57,14 +60,6 @@ struct TableScanJobState { }; using TableScanJob = ScanReadAheadJobWrapper; -//! Create the read-ahead driver, returns null when read-ahead is disabled or prefetching is not beneficial -static unique_ptr CreateTableScanReadAhead(ClientContext &context, DataTable &storage) { - if (!storage.GetTableIOManager().GetBlockManagerForRowData().Prefetch()) { - return nullptr; - } - return ScanReadAhead::Create(context); -} - //! Tracks how many rows of a scan assignment have been consumed, for reporting progress struct ScanAssignmentProgress { //! Rows of the current assignment @@ -103,7 +98,11 @@ struct ScanAssignmentProgress { } }; +enum class TableScanScheduling { UNINITIALIZED, DIRECT, ORDERED, AFFINITY }; + struct TableScanLocalState : public LocalTableFunctionState { + explicit TableScanLocalState(idx_t progress_index_p) : progress_index(progress_index_p) { + } //! The current position in the scan. TableScanState scan_state; //! The DataChunk containing all read columns. @@ -117,6 +116,12 @@ struct TableScanLocalState : public LocalTableFunctionState { ScanAssignmentProgress assignment_progress; idx_t row_groups_scanned = 0; + //! Producer scratch, separate from the assignment currently being decoded. + unique_ptr prepare_state; + vector> reusable_jobs; + + //! Slot in the global scan state's progress counters + const idx_t progress_index; }; struct IndexScanLocalState : public LocalTableFunctionState { @@ -348,7 +353,11 @@ class DuckTableScanState : public TableScanGlobalState { DuckTableScanState(ClientContext &context, const FunctionData *bind_data_p) : TableScanGlobalState(context, bind_data_p), bind_data(bind_data_p->Cast()), duck_table(bind_data.table.Cast()), tx(DuckTransaction::Get(context, duck_table.catalog)), - storage(duck_table.GetStorage()), total_rows(storage.GetTotalRows()) { + storage(duck_table.GetStorage()), total_rows(storage.GetTotalRows()), + progress(MaxValue(1, context.db->NumberOfThreads())) { + for (auto &counter : progress) { + counter.store(0, std::memory_order_relaxed); + } } public: @@ -365,13 +374,44 @@ class DuckTableScanState : public TableScanGlobalState { vector storage_ids; optional_ptr filters; optional_ptr sample_options; - //! Guards assignment claims, keeping job batch indexes dense in claim order + //! Guards scheduling setup and ordered batch index assignment mutex read_ahead_lock; //! Batch index assigned to the next produced job idx_t next_job_index = 0; ScanStatePool state_pool; - //! Rows of claimed assignments that have been consumed by a scan - atomic scanned_rows {0}; + //! Preallocated counters spread progress updates without registering local states + vector> progress; + TableScanScheduling scheduling = TableScanScheduling::UNINITIALIZED; + +private: + void InitializeScheduling(ExecutionContext &context, TableFunctionInitInput &input) { + lock_guard guard(read_ahead_lock); + if (scheduling != TableScanScheduling::UNINITIALIZED) { + return; + } + auto &blocks = storage.GetTableIOManager().GetBlockManagerForRowData(); + idx_t affinity_shards = 0; + if (input.execution_order == PipelineExecutionOrder::UNORDERED) { + const bool supported_scan = input.max_threads > 1 && !blocks.InMemory() && !bind_data.is_create_index && + !bind_data.order_options && !sample_options; + if (supported_scan && + CollectionScanState::SupportsAssignmentBlockDiscovery(storage_ids, storage.GetTypes())) { + const auto shard_count = BlockAllocator::Get(storage.GetAttached()).GetPoolShardCount(); + if (shard_count > 1 || ClientConfig::GetConfig(context.client).verify_parallelism) { + affinity_shards = shard_count; + } + } + } + const bool repeatable_percentage_sample = + sample_options && sample_options->repeatable && sample_options->is_percentage; + const bool prefetch = !bind_data.is_create_index && !repeatable_percentage_sample && blocks.Prefetch(); + const auto policy = affinity_shards ? ScanReadAheadPolicy::AFFINITY : ScanReadAheadPolicy::ORDERED; + read_ahead = ScanReadAhead::Create(context.client, policy, prefetch, MaxValue(affinity_shards, 1), + input.max_threads); + scheduling = affinity_shards ? TableScanScheduling::AFFINITY + : read_ahead ? TableScanScheduling::ORDERED + : TableScanScheduling::DIRECT; + } public: //! Retains the scan initialization info shared by all scan states of this scan @@ -397,10 +437,12 @@ class DuckTableScanState : public TableScanGlobalState { unique_ptr InitLocalState(ExecutionContext &context, TableFunctionInitInput &input) override { - auto l_state = make_uniq(); + const auto counter_index = TaskScheduler::GetEstimatedCPUId() % progress.size(); + auto l_state = make_uniq(counter_index); InitializeScanState(context.client, l_state->scan_state); - if (!read_ahead) { + InitializeScheduling(context, input); + if (scheduling == TableScanScheduling::DIRECT) { ClaimAssignment(context.client, *l_state); } if (input.CanRemoveFilterColumns()) { @@ -409,9 +451,60 @@ class DuckTableScanState : public TableScanGlobalState { return std::move(l_state); } + unique_ptr ProduceAffinityJob(ClientContext &context, TableScanLocalState &l_state, + vector> &io_tasks) { + context.InterruptCheck(); + if (!l_state.prepare_state) { + l_state.prepare_state = make_uniq(); + InitializeScanState(context, *l_state.prepare_state); + } + unique_ptr job; + if (!l_state.reusable_jobs.empty()) { + job = std::move(l_state.reusable_jobs.back()); + l_state.reusable_jobs.pop_back(); + } else { + job = make_uniq(BlockAllocator::Get(storage.GetAttached())); + } + auto &prepare = *l_state.prepare_state; + if (!storage.NextParallelScanAssignment(context, state, prepare, job->assignment)) { + return nullptr; + } + if (job->assignment.source == TableScanSource::PERSISTENT) { + prepare.table_state.PrepareAssignmentBlocks(job->blocks, io_tasks, read_ahead->PrefetchEnabled()); + } + prepare.ReleasePins(); + return std::move(job); + } + + ScanReadAheadAcquire ClaimAffinityAssignment(ClientContext &context, TableFunctionInput &input, + TableScanLocalState &l_state) { + AddProgress(l_state, l_state.assignment_progress.Finish()); + unique_ptr claimed; + const auto shard = BlockAllocator::Get(storage.GetAttached()).GetLocalPoolShard(); + auto produce = [&](vector> &tasks) { + return ProduceAffinityJob(context, l_state, tasks); + }; + const auto result = read_ahead->AcquireReadyJob(context, input, std::ref(produce), claimed, shard); + if (result != ScanReadAheadAcquire::ACQUIRED) { + D_ASSERT(!claimed); + return result; + } + auto job = unique_ptr_cast(std::move(claimed)); + l_state.assignment_progress.Start(job->assignment.row_group.RowCount()); + if (l_state.scan_state.StartAssignment(job->assignment, read_ahead->PrefetchEnabled())) { + l_state.row_groups_scanned++; + } + job->assignment = TableScanAssignment(); + static constexpr idx_t MAX_REUSABLE_JOBS = 8; + if (l_state.reusable_jobs.size() < MAX_REUSABLE_JOBS) { + l_state.reusable_jobs.push_back(std::move(job)); + } + return ScanReadAheadAcquire::ACQUIRED; + } + //! Claims the next assignment into the thread's own scan state, returns false when none are left bool ClaimAssignment(ClientContext &context, TableScanLocalState &l_state) { - scanned_rows.fetch_add(l_state.assignment_progress.Finish(), std::memory_order_relaxed); + AddProgress(l_state, l_state.assignment_progress.Finish()); auto rows = storage.NextParallelScan(context, state, l_state.scan_state); if (!rows.IsValid()) { return false; @@ -421,9 +514,15 @@ class DuckTableScanState : public TableScanGlobalState { return true; } + void AddProgress(const TableScanLocalState &l_state, idx_t rows) { + if (rows) { + progress[l_state.progress_index].fetch_add(rows, std::memory_order_relaxed); + } + } + //! Counts the rows of the current assignment that were consumed by the scan void UpdateScanProgress(TableScanLocalState &l_state, const TableScanState &scan_state) { - scanned_rows.fetch_add(l_state.assignment_progress.Update(scan_state), std::memory_order_relaxed); + AddProgress(l_state, l_state.assignment_progress.Update(scan_state)); } //! How TableScanFunc's loop proceeds after a persistent scan iteration @@ -463,7 +562,7 @@ class DuckTableScanState : public TableScanGlobalState { return PersistentScanResult::YIELD; } // the prepared vector was filtered out entirely, go the next vector - context.InterruptCheck(); + context.FastInterruptCheck(); return PersistentScanResult::NEXT_VECTOR; } @@ -554,7 +653,7 @@ class DuckTableScanState : public TableScanGlobalState { return true; } // the job is exhausted, fold its scan counters into this thread and recycle its state - scanned_rows.fetch_add(l_state.assignment_progress.Finish(), std::memory_order_relaxed); + AddProgress(l_state, l_state.assignment_progress.Finish()); l_state.job_rows_scanned += job_scan.RowsScanned(); job_scan.table_state.rows_scanned = 0; job_scan.local_state.rows_scanned = 0; @@ -570,7 +669,6 @@ class DuckTableScanState : public TableScanGlobalState { void TableScanFunc(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) override { auto &l_state = data_p.local_state->Cast(); - l_state.scan_state.options.force_fetch_row = Settings::Get(context); #ifdef DUCKDB_DEBUG_ASYNC_SINK_SOURCE { @@ -585,7 +683,7 @@ class DuckTableScanState : public TableScanGlobalState { if (bind_data.is_create_index) { storage.CreateIndexScan(l_state.scan_state, output); UpdateScanProgress(l_state, l_state.scan_state); - } else if (read_ahead) { + } else if (scheduling == TableScanScheduling::ORDERED) { if (!ScanWithReadAhead(context, data_p, l_state, output) && data_p.results_execution_mode == AsyncResultsExecutionMode::TASK_EXECUTOR) { // every assignment went to a read-ahead job, the thread's own scan state never claims one @@ -608,7 +706,16 @@ class DuckTableScanState : public TableScanGlobalState { return; } - const bool claimed = ClaimAssignment(context, l_state); + bool claimed; + if (scheduling == TableScanScheduling::AFFINITY) { + const auto acquired = ClaimAffinityAssignment(context, data_p, l_state); + if (acquired == ScanReadAheadAcquire::PARKED) { + return; + } + claimed = acquired == ScanReadAheadAcquire::ACQUIRED; + } else { + claimed = ClaimAssignment(context, l_state); + } if (data_p.results_execution_mode == AsyncResultsExecutionMode::TASK_EXECUTOR) { // We can avoid looping, and just return as appropriate data_p.async_result = claimed ? AsyncResultType::HAVE_MORE_OUTPUT : AsyncResultType::FINISHED; @@ -619,7 +726,7 @@ class DuckTableScanState : public TableScanGlobalState { } // Before looping back, check if we are interrupted - context.InterruptCheck(); + context.FastInterruptCheck(); } while (true); } @@ -630,7 +737,10 @@ class DuckTableScanState : public TableScanGlobalState { } // rows count once they are consumed by a scan, or when their assignment is skipped entirely - idx_t done_rows = scanned_rows.load(); + idx_t done_rows = 0; + for (auto &counter : progress) { + done_rows += counter.load(std::memory_order_relaxed); + } done_rows += state.scan_state.skipped_rows.load(); done_rows += state.local_state.skipped_rows.load(); auto percentage = 100 * (static_cast(done_rows) / static_cast(total_rows)); @@ -645,6 +755,7 @@ class DuckTableScanState : public TableScanGlobalState { OperatorPartitionData TableScanGetPartitionData(ClientContext &context, TableFunctionGetPartitionInput &input) override { auto &l_state = input.local_state->Cast(); + D_ASSERT(scheduling != TableScanScheduling::AFFINITY); // with read-ahead the assignment being decoded lives in the claimed job's scan state auto &scan_state = l_state.job ? *l_state.job->scan_state : l_state.scan_state; if (scan_state.table_state.GetRowGroup()) { @@ -698,11 +809,6 @@ unique_ptr DuckTableScanInitGlobal(ClientContext &cont } storage.InitializeParallelScan(context, g_state->state, input.column_indexes); g_state->InitializeScanInfo(input); - const bool repeatable_percentage_sample = - input.sample_options && input.sample_options->repeatable && input.sample_options->is_percentage; - if (!bind_data.is_create_index && !repeatable_percentage_sample) { - g_state->read_ahead = CreateTableScanReadAhead(context, storage); - } if (!input.CanRemoveFilterColumns()) { return std::move(g_state); } @@ -1137,7 +1243,7 @@ InsertionOrderPreservingMap TableScanToString(TableFunctionToStringInput return result; } -static void TableScanSerialize(Serializer &serializer, const optional_ptr bind_data_p, +static void TableScanSerialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundTableFunction &function) { auto &bind_data = bind_data_p->Cast(); // the catalog/schema/name are only the innermost qualification - "qualified_name" carries the full (possibly @@ -1194,19 +1300,19 @@ virtual_column_map_t TableScanGetVirtualColumns(ClientContext &context, optional return bind_data.table.GetVirtualColumns(); } -vector TableScanGetRowIdColumns(ClientContext &context, optional_ptr bind_data) { +vector TableScanGetRowIdColumns(ClientContext &context, optional_ptr bind_data) { vector result; result.emplace_back(COLUMN_IDENTIFIER_ROW_ID); return result; } -void SetScanOrder(unique_ptr order_options, optional_ptr bind_data_p) { - auto &bind_data = bind_data_p->Cast(); +void SetScanOrder(unique_ptr order_options, cow_ptr &bind_data_p) { + auto &bind_data = bind_data_p.write().Cast(); bind_data.order_options = std::move(order_options); } -void SetPartitionsToScan(vector partition_indices, optional_ptr bind_data_p) { - auto &bind_data = bind_data_p->Cast(); +void SetPartitionsToScan(vector partition_indices, cow_ptr &bind_data_p) { + auto &bind_data = bind_data_p.write().Cast(); bind_data.partitions_to_scan = make_uniq>(partition_indices.begin(), partition_indices.end()); } diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index c5712684f..9bfdb51f1 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-alpha55959" +#define DUCKDB_PATCH_VERSION "0-alpha56986" #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-alpha55959" +#define DUCKDB_VERSION "v2.1.0-alpha56986" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "a2deaf15a4" +#define DUCKDB_SOURCE_ID "87d96b7773" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/function/variant/variant_shredding.cpp b/src/duckdb/src/function/variant/variant_shredding.cpp index a71cf3b73..49c0eff7f 100644 --- a/src/duckdb/src/function/variant/variant_shredding.cpp +++ b/src/duckdb/src/function/variant/variant_shredding.cpp @@ -62,6 +62,7 @@ static void WriteShreddedWideDecimal(UnifiedVariantVectorData &variant, Vector & static bool IsVariantStringType(VariantLogicalType type_id) { switch (type_id) { case VariantLogicalType::GEOMETRY: + case VariantLogicalType::GEOGRAPHY: case VariantLogicalType::BITSTRING: case VariantLogicalType::BLOB: case VariantLogicalType::VARCHAR: @@ -168,6 +169,7 @@ void VariantShredding::WriteTypedPrimitiveValues(UnifiedVariantVectorData &varia case LogicalTypeId::BLOB: case LogicalTypeId::BIGNUM: case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: case LogicalTypeId::BIT: case LogicalTypeId::VARCHAR: { WriteShreddedString(variant, result, sel, value_index_sel, result_sel, count); diff --git a/src/duckdb/src/function/window/match_recognize_matcher.cpp b/src/duckdb/src/function/window/match_recognize_matcher.cpp index 82019d989..607bfa5c1 100644 --- a/src/duckdb/src/function/window/match_recognize_matcher.cpp +++ b/src/duckdb/src/function/window/match_recognize_matcher.cpp @@ -203,7 +203,7 @@ bool PatternMatcher::Match(idx_t start, idx_t partition_start, idx_t input_size) // a walk can be long, and a pattern that has to try again for every row longer still if (++steps >= INTERRUPT_INTERVAL) { steps = 0; - context.InterruptCheck(); + context.FastInterruptCheck(); } if (state_limit && ++states > state_limit) { throw InvalidInputException( diff --git a/src/duckdb/src/function/window/window_aggregate_function.cpp b/src/duckdb/src/function/window/window_aggregate_function.cpp index 9fa174cbc..a83ec3715 100644 --- a/src/duckdb/src/function/window/window_aggregate_function.cpp +++ b/src/duckdb/src/function/window/window_aggregate_function.cpp @@ -61,7 +61,7 @@ WindowAggregateExecutor::WindowAggregateExecutor(BoundWindowExpression &wexpr, C if (!WindowNaiveAggregator::CanAggregate(wexpr)) { throw InvalidInputException("Cannot use non-aggregate window function with naive window executor!"); } - aggregator = make_uniq(*this, shared); + aggregator = make_uniq(*this, shared, client); } else if (WindowDistinctAggregator::CanAggregate(wexpr)) { // build a merge sort tree // see https://dl.acm.org/doi/pdf/10.1145/3514221.3526184 @@ -76,7 +76,7 @@ WindowAggregateExecutor::WindowAggregateExecutor(BoundWindowExpression &wexpr, C aggregator = make_uniq(wexpr, shared); } else if (WindowNaiveAggregator::CanAggregate(wexpr)) { // No accelerator can handle this combination, so fall back to naïve. - aggregator = make_uniq(*this, shared); + aggregator = make_uniq(*this, shared, client); } else { // This shouldn't happen, if we get here, the binder messed up // Non-aggregate window functions that can't be handled by the WindowCustomAggregator due to e.g. a ORDER BY diff --git a/src/duckdb/src/function/window/window_aggregate_states.cpp b/src/duckdb/src/function/window/window_aggregate_states.cpp index a11fbfe1c..c0af12c2c 100644 --- a/src/duckdb/src/function/window/window_aggregate_states.cpp +++ b/src/duckdb/src/function/window/window_aggregate_states.cpp @@ -30,7 +30,7 @@ void WindowAggregateStates::Initialize(idx_t count_p) { } void WindowAggregateStates::Combine(WindowAggregateStates &target) { - AggregateInputData aggr_input_data(aggr, allocator, AggregateCombineType::ALLOW_DESTRUCTIVE); + AggregateInputData aggr_input_data(aggr, target.allocator, AggregateCombineType::ALLOW_DESTRUCTIVE); aggr.function.GetStateCombineCallback()(*statef, *target.statef, aggr_input_data, GetCount()); } diff --git a/src/duckdb/src/function/window/window_collection.cpp b/src/duckdb/src/function/window/window_collection.cpp index 5a1b0875f..b93b33e1b 100644 --- a/src/duckdb/src/function/window/window_collection.cpp +++ b/src/duckdb/src/function/window/window_collection.cpp @@ -148,10 +148,19 @@ WindowCursor::WindowCursor(const WindowCollection &paged, column_t col_idx) } LogicalType WindowCollectionChunkScanner::PrefixStructType(column_t end, column_t begin) { + vector types; + for (column_t c = 0; c < end; ++c) { + types.push_back(chunk.data[c].GetType()); + } + return PrefixStructType(types, end, begin); +} + +LogicalType WindowCollectionChunkScanner::PrefixStructType(const vector &types, column_t end, + column_t begin) { child_list_t partition_children; for (auto c = begin; c < end; ++c) { auto name = std::to_string(c); - auto type = chunk.data[c].GetType(); + auto type = types[c]; std::pair child {Identifier(name), type}; partition_children.emplace_back(child); } diff --git a/src/duckdb/src/function/window/window_distinct_aggregator.cpp b/src/duckdb/src/function/window/window_distinct_aggregator.cpp index 816562ede..c33f39197 100644 --- a/src/duckdb/src/function/window/window_distinct_aggregator.cpp +++ b/src/duckdb/src/function/window/window_distinct_aggregator.cpp @@ -1,3 +1,4 @@ +#include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/function/window/window_distinct_aggregator.hpp" #include "duckdb/common/sorting/sort.hpp" @@ -97,6 +98,8 @@ class WindowDistinctAggregatorGlobalState : public WindowAggregatorGlobalState { //! Sorting operations vector sort_cols; + //! DISTINCT FROM comparison of the aggregate arguments + unique_ptr key_distinct_from; unique_ptr sort; unique_ptr global_sink; //! Local sort sets @@ -136,6 +139,10 @@ WindowDistinctAggregatorGlobalState::WindowDistinctAggregatorGlobalState(ClientC sort_cols.emplace_back(sort_cols.size()); } + auto key_type = WindowCollectionChunkScanner::PrefixStructType(sort_types, aggregator.arg_types.size()); + key_distinct_from = BoundComparisonExpression::CreateOnColumns(client, ExpressionType::COMPARE_DISTINCT_FROM, + key_type, 0, key_type, 1); + sort = make_uniq(client, orders, sort_types, sort_cols); global_sink = sort->GetGlobalSinkState(client); @@ -190,7 +197,7 @@ class WindowDistinctAggregatorLocalState : public WindowAggregatorLocalState { void Sink(ExecutionContext &context, DataChunk &sink_chunk, DataChunk &coll_chunk, idx_t input_idx, optional_ptr filter_sel, idx_t filtered, InterruptState &interrupt); void Finalize(ExecutionContext &context, WindowAggregatorGlobalState &gastate, CollectionPtr collection) override; - void Sorted(); + void Sorted(Context &context); void ExecuteTask(ExecutionContext &context, WindowDistinctAggregatorGlobalState &gdstate); void Evaluate(ExecutionContext &context, const WindowDistinctAggregatorGlobalState &gdstate, const DataChunk &bounds, Vector &result, idx_t count, idx_t row_idx); @@ -319,7 +326,7 @@ void WindowDistinctAggregatorLocalState::ExecuteTask(ExecutionContext &context, break; } case WindowDistinctSortStage::SORTED: - Sorted(); + Sorted(context.client.GetContext()); break; default: break; @@ -398,7 +405,7 @@ void WindowDistinctAggregator::Finalize(ExecutionContext &context, CollectionPtr while (gdsink.stage.load() != WindowDistinctSortStage::FINISHED) { // A failed task never completes its stage, so the waiting threads // leave through the interrupt that the executor raises for the failure - context.client.InterruptCheck(); + context.client.FastInterruptCheck(); if (gdsink.TryPrepareNextStage(ldstate)) { ldstate.ExecuteTask(context, gdsink); } else { @@ -414,7 +421,7 @@ void WindowDistinctAggregator::Finalize(ExecutionContext &context, CollectionPtr ++gdsink.finalized; } -void WindowDistinctAggregatorLocalState::Sorted() { +void WindowDistinctAggregatorLocalState::Sorted(Context &context) { using ZippedTuple = WindowDistinctAggregatorGlobalState::ZippedTuple; auto &collection = *gdstate.sorted; auto &prev_idcs = gdstate.zipped_tree.LowestLevel(); @@ -449,7 +456,7 @@ void WindowDistinctAggregatorLocalState::Sorted() { } // 8: for i ← 1 to in.size do - WindowDeltaScanner(collection, block_begin, block_end, scan_cols, key_count, + WindowDeltaScanner(context, *gdstate.key_distinct_from, collection, block_begin, block_end, scan_cols, key_count, [&](const idx_t row_idx, DataChunk &prev, DataChunk &curr, const idx_t ndistinct, SelectionVector &distinct, const SelectionVector &matching) { const auto count = MinValue(prev.size(), curr.size()); @@ -531,7 +538,7 @@ void WindowDistinctSortTree::Build(ClientContext &context, WindowDistinctAggrega while (build_level.load() < tree.size()) { // A failed run never completes its level, so the waiting threads // leave through the interrupt that the executor raises for the failure - context.InterruptCheck(); + context.FastInterruptCheck(); idx_t level_idx; idx_t run_idx; if (TryNextRun(level_idx, run_idx)) { @@ -651,7 +658,7 @@ void WindowDistinctAggregatorLocalState::FlushStates() { } const auto &aggr = gdstate.aggr; - AggregateInputData aggr_input_data(aggr, allocator); + AggregateInputData aggr_input_data(aggr, statef.allocator); statel.Verify(); aggr.function.GetStateCombineCallback()(statel, statep, aggr_input_data, flush_count); @@ -668,6 +675,8 @@ void WindowDistinctAggregatorLocalState::Evaluate(ExecutionContext &context, const auto &levels_flat_native = gdstate.levels_flat_native; const auto exclude_mode = gdstate.aggregator.exclude_mode; + // Reclaim the result states of the previous batch, whose results have been consumed + statef.allocator.Reset(); // Build the finalise vector that just points to the result states statef.Initialize(count); diff --git a/src/duckdb/src/function/window/window_index_tree.cpp b/src/duckdb/src/function/window/window_index_tree.cpp index c12f4a361..78967c608 100644 --- a/src/duckdb/src/function/window/window_index_tree.cpp +++ b/src/duckdb/src/function/window/window_index_tree.cpp @@ -23,7 +23,7 @@ WindowIndexTreeLocalState::WindowIndexTreeLocalState(ExecutionContext &context, : WindowMergeSortTreeLocalState(context, index_tree), index_tree(index_tree) { } -void WindowIndexTreeLocalState::BuildLeaves() { +void WindowIndexTreeLocalState::BuildLeaves(Context &) { auto &collection = *window_tree.sorted; if (!collection.Count()) { return; diff --git a/src/duckdb/src/function/window/window_match_recognize.cpp b/src/duckdb/src/function/window/window_match_recognize.cpp index 0fe4ccfa2..e4dae28b7 100644 --- a/src/duckdb/src/function/window/window_match_recognize.cpp +++ b/src/duckdb/src/function/window/window_match_recognize.cpp @@ -186,7 +186,7 @@ unique_ptr MatchRecognizePattern::Deserialize(Deserialize return result; } -void WindowMatchRecognizeExecutor::Serialize(Serializer &serializer, const optional_ptr bind_data, +void WindowMatchRecognizeExecutor::Serialize(Serializer &serializer, const optional_ptr bind_data, const BoundWindowFunction &function) { auto &config = bind_data->Cast(); serializer.WriteObject(100, "pattern", [&](Serializer &child) { config.pattern->Serialize(child); }); @@ -1077,7 +1077,7 @@ static void ScanPartitions(ExecutionContext &context, WindowMatchRecognizeGlobal idx_t match_number = 0; auto row = partition_start; while (row <= partition_end) { - context.client.InterruptCheck(); + context.client.FastInterruptCheck(); row_conditions.BeginMatch(row, match_number + 1); if (!matcher.Match(row, partition_start, partition_end + 1)) { row++; diff --git a/src/duckdb/src/function/window/window_merge_sort_tree.cpp b/src/duckdb/src/function/window/window_merge_sort_tree.cpp index 264e214e1..4f6bea47d 100644 --- a/src/duckdb/src/function/window/window_merge_sort_tree.cpp +++ b/src/duckdb/src/function/window/window_merge_sort_tree.cpp @@ -1,3 +1,5 @@ +#include "duckdb/function/window/window_collection.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/function/window/window_merge_sort_tree.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" @@ -46,6 +48,14 @@ WindowMergeSortTree::WindowMergeSortTree(ClientContext &client, const vector key_types; + for (auto key_col : key_cols) { + key_types.push_back(scan_types[key_col]); + } + auto key_type = WindowCollectionChunkScanner::PrefixStructType(key_types, key_types.size()); + key_distinct_from = BoundComparisonExpression::CreateOnColumns(client, ExpressionType::COMPARE_DISTINCT_FROM, + key_type, 0, key_type, 1); + sort = make_uniq(client, orders, scan_types, scan_cols); global_sink = sort->GetGlobalSinkState(client); @@ -112,7 +122,7 @@ void WindowMergeSortTreeLocalState::ExecuteSortTask(ExecutionContext &context, I break; } case WindowMergeSortStage::SORTED: - BuildLeaves(); + BuildLeaves(context.client.GetContext()); break; case WindowMergeSortStage::FINISH: window_tree.Finished(); @@ -222,7 +232,7 @@ void WindowMergeSortTreeLocalState::Finalize(ExecutionContext &context, Interrup while (window_tree.build_stage.load() != WindowMergeSortStage::FINISHED) { // A failed task never completes its stage, so the waiting threads // leave through the interrupt that the executor raises for the failure - context.client.InterruptCheck(); + context.client.FastInterruptCheck(); if (window_tree.TryPrepareSortStage(*this)) { ExecuteSortTask(context, interrupt); } else { diff --git a/src/duckdb/src/function/window/window_naive_aggregator.cpp b/src/duckdb/src/function/window/window_naive_aggregator.cpp index ef1745156..f4da1d0d2 100644 --- a/src/duckdb/src/function/window/window_naive_aggregator.cpp +++ b/src/duckdb/src/function/window/window_naive_aggregator.cpp @@ -1,4 +1,6 @@ #include "duckdb/function/window/window_naive_aggregator.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/common/sorting/sort.hpp" #include "duckdb/function/window/window_collection.hpp" #include "duckdb/function/window/window_shared_expressions.hpp" @@ -6,17 +8,29 @@ #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/function/window/window_aggregate_function.hpp" #include "duckdb/common/enums/window_aggregation_mode.hpp" +#include "duckdb/main/client_context.hpp" namespace duckdb { //===--------------------------------------------------------------------===// // WindowNaiveAggregator //===--------------------------------------------------------------------===// -WindowNaiveAggregator::WindowNaiveAggregator(const WindowAggregateExecutor &executor, WindowSharedExpressions &shared) +WindowNaiveAggregator::WindowNaiveAggregator(const WindowAggregateExecutor &executor, WindowSharedExpressions &shared, + ClientContext &client) : WindowAggregator(executor.wexpr, shared), executor(executor) { for (const auto &order : wexpr.ArgOrders()) { arg_order_idx.emplace_back(shared.RegisterCollection(order.expression, false)); } + if (!arg_types.empty()) { + vector> arg_equals; + for (idx_t arg_idx = 0; arg_idx < arg_types.size(); arg_idx++) { + auto &arg_type = arg_types[arg_idx]; + arg_equals.push_back( + BoundComparisonExpression::CreateOnColumns(client, ExpressionType::COMPARE_NOT_DISTINCT_FROM, arg_type, + arg_idx, arg_type, arg_types.size() + arg_idx)); + } + args_equal = BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_AND, std::move(arg_equals)); + } } WindowNaiveAggregator::~WindowNaiveAggregator() { @@ -87,6 +101,9 @@ class WindowNaiveLocalState : public WindowAggregatorLocalState { Vector hashes; //! The state used for comparing the collection across chunk boundaries unique_ptr comparer; + //! Whether two rows have the same arguments, over [left arguments..., right arguments...] + unique_ptr args_equal; + DataChunk args_compare; //! The state used for scanning ORDER BY values from the collection unique_ptr sort; @@ -136,6 +153,12 @@ void WindowNaiveLocalState::Finalize(ExecutionContext &context, WindowAggregator // Set up the comparison scanner just in case if (!comparer) { comparer = make_uniq(*collection, aggregator.child_idx); + if (aggregator.args_equal) { + args_equal = make_uniq(context.client.GetContext(), *aggregator.args_equal); + auto compare_types = aggregator.arg_types; + compare_types.insert(compare_types.end(), aggregator.arg_types.begin(), aggregator.arg_types.end()); + args_compare.InitializeEmpty(compare_types); + } } // Set up the argument ORDER BY scanner if needed @@ -197,6 +220,9 @@ size_t WindowNaiveLocalState::Hash(idx_t rid) { } bool WindowNaiveLocalState::KeyEqual(const idx_t &lidx, const idx_t &ridx) { + if (!args_equal) { + return true; + } // One of the indices will be scanned, so make it the left one auto lhs = lidx; auto rhs = ridx; @@ -219,18 +245,16 @@ bool WindowNaiveLocalState::KeyEqual(const idx_t &lidx, const idx_t &ridx) { auto r = rreader->RowOffset(rhs); SelectionVector rsel(&r, 1); - sel_t f = 0; - SelectionVector fsel(&f, 1); + sel_t t = 0; + SelectionVector tsel(&t, 1); - for (column_t c = 0; c < scanned.ColumnCount(); ++c) { - Vector left(scanned.data[c], lsel, 1); - Vector right(rscanned->data[c], rsel, 1); - if (!VectorOperations::NotDistinctFrom(left, right, nullptr, 1, nullptr, &fsel)) { - return false; - } + const auto column_count = scanned.ColumnCount(); + for (column_t c = 0; c < column_count; ++c) { + args_compare.data[c].Slice(scanned.data[c], lsel, 1); + args_compare.data[column_count + c].Slice(rscanned->data[c], rsel, 1); } - - return true; + args_compare.CheckCardinality(1); + return args_equal->SelectExpression(args_compare, tsel) == 1; } void WindowNaiveLocalState::Evaluate(ExecutionContext &context, const WindowAggregatorGlobalState &gsink, @@ -243,6 +267,10 @@ void WindowNaiveLocalState::Evaluate(ExecutionContext &context, const WindowAggr auto fdata = FlatVector::GetDataMutable(statef); auto pdata = FlatVector::GetDataMutable(statep); + // Reclaim the result states of the previous batch, whose results have been consumed + D_ASSERT(live_count == 0); + allocator.Reset(); + HashRow hash_row(*this); EqualRow equal_row(*this); RowSet row_set(STANDARD_VECTOR_SIZE, hash_row, equal_row); diff --git a/src/duckdb/src/function/window/window_segment_tree.cpp b/src/duckdb/src/function/window/window_segment_tree.cpp index b5514b71a..e6b4eb98a 100644 --- a/src/duckdb/src/function/window/window_segment_tree.cpp +++ b/src/duckdb/src/function/window/window_segment_tree.cpp @@ -149,12 +149,15 @@ class WindowSegmentTreePart { class WindowSegmentTreeLocalState : public WindowAggregatorLocalState { public: - explicit WindowSegmentTreeLocalState(ExecutionContext &context) : WindowAggregatorLocalState(context) { + explicit WindowSegmentTreeLocalState(ExecutionContext &context) + : WindowAggregatorLocalState(context), result_arena(BufferAllocator::Get(context.client)) { } void Finalize(ExecutionContext &context, WindowAggregatorGlobalState &gastate, CollectionPtr collection) override; void Evaluate(ExecutionContext &context, const WindowSegmentTreeGlobalState &gsink, const DataChunk &bounds, Vector &result, idx_t count, idx_t row_idx); + //! The arena of the result parts, reset per batch + ArenaAllocator result_arena; //! The left (default) segment tree part unique_ptr part; //! The right segment tree part (for EXCLUDE) @@ -496,8 +499,10 @@ void WindowSegmentTreeLocalState::Evaluate(ExecutionContext &context, const Wind auto peer_end = FlatVector::GetData(bounds.data[PEER_END]); if (!part) { - part = make_uniq(allocator, gtstate.aggr, cursor->Copy(), gtstate.filter_mask); + part = make_uniq(result_arena, gtstate.aggr, cursor->Copy(), gtstate.filter_mask); } + // Reclaim the result states of the previous batch, whose results have been consumed + result_arena.Reset(); if (gtstate.aggregator.exclude_mode != WindowExcludeMode::NO_OTHER) { // If we exclude the current row, then both left and right need to contain it. diff --git a/src/duckdb/src/function/window/window_token_tree.cpp b/src/duckdb/src/function/window/window_token_tree.cpp index 81dfe8b1e..31cd1f157 100644 --- a/src/duckdb/src/function/window/window_token_tree.cpp +++ b/src/duckdb/src/function/window/window_token_tree.cpp @@ -9,12 +9,12 @@ class WindowTokenTreeLocalState : public WindowMergeSortTreeLocalState { : WindowMergeSortTreeLocalState(context, token_tree), token_tree(token_tree) { } //! Process sorted leaf data - void BuildLeaves() override; + void BuildLeaves(Context &context) override; WindowTokenTree &token_tree; }; -void WindowTokenTreeLocalState::BuildLeaves() { +void WindowTokenTreeLocalState::BuildLeaves(Context &context) { // Find our chunk range auto &collection = *token_tree.sorted; const auto block_begin = (build_task * collection.ChunkCount()) / token_tree.total_tasks; @@ -28,7 +28,7 @@ void WindowTokenTreeLocalState::BuildLeaves() { const auto &scan_cols = token_tree.key_cols; const auto key_count = scan_cols.size(); - WindowDeltaScanner(collection, block_begin, block_end, scan_cols, key_count, + WindowDeltaScanner(context, *token_tree.key_distinct_from, collection, block_begin, block_end, scan_cols, key_count, [&](const idx_t row_idx, DataChunk &prev, DataChunk &curr, const idx_t ndistinct, SelectionVector &distinct, const SelectionVector &matching) { // Same as previous - token delta is 0 diff --git a/src/duckdb/src/include/duckdb.h b/src/duckdb/src/include/duckdb.h index 9dd471822..9e3160e57 100644 --- a/src/duckdb/src/include/duckdb.h +++ b/src/duckdb/src/include/duckdb.h @@ -285,6 +285,9 @@ typedef enum DUCKDB_TYPE { //! duckdb_timestamp (nanoseconds) DUCKDB_TYPE_TIMESTAMP_TZ_NS = 42, + + //! GEOGRAPHY type, WKB blob with spherical edges + DUCKDB_TYPE_GEOGRAPHY = 43, } DUCKDB_TYPE; /*! @@ -5591,13 +5594,13 @@ DUCKDB_C_API duckdb_state duckdb_register_logical_type(duckdb_connection con, du #if DUCKDB_API_VERSION_AT_LEAST(1, 5, 6) /*! - * Gets the CRS (Coordinate Reference System) of a GEOMETRY type. Result must be freed with `duckdb_free`. + * Gets the CRS (Coordinate Reference System) of a GEOMETRY or GEOGRAPHY type. Result must be freed with `duckdb_free`. * * history: * - unstable: v1.5.2 * - stable: v1.5.6 * - * @param type The GEOMETRY type. + * @param type The GEOMETRY or GEOGRAPHY type. * @return char* */ DUCKDB_C_API char *duckdb_geometry_type_get_crs(duckdb_logical_type type); diff --git a/src/duckdb/src/include/duckdb/catalog/catalog.hpp b/src/duckdb/src/include/duckdb/catalog/catalog.hpp index ba4285888..c5b489c0c 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog.hpp @@ -40,7 +40,6 @@ struct CreatePragmaFunctionInfo; struct CreateFunctionInfo; struct CreateViewInfo; struct CreateSequenceInfo; -struct CreateCollationInfo; struct CreateCoordinateSystemInfo; struct CreateIndexInfo; struct CreateTypeInfo; @@ -55,7 +54,6 @@ class QueryContext; class Transaction; class AggregateFunctionCatalogEntry; -class CollateCatalogEntry; class SchemaCatalogEntry; class TableCatalogEntry; class ViewCatalogEntry; @@ -195,9 +193,6 @@ class Catalog { //! Creates a Enum in the catalog. DUCKDB_API optional_ptr CreateType(CatalogTransaction transaction, CreateTypeInfo &info); DUCKDB_API optional_ptr CreateType(ClientContext &context, CreateTypeInfo &info); - //! Creates a collation in the catalog - DUCKDB_API optional_ptr CreateCollation(CatalogTransaction transaction, CreateCollationInfo &info); - DUCKDB_API optional_ptr CreateCollation(ClientContext &context, CreateCollationInfo &info); //! Creates a coordinate system in the catalog DUCKDB_API optional_ptr CreateCoordinateSystem(CatalogTransaction transaction, CreateCoordinateSystemInfo &info); @@ -231,9 +226,6 @@ class Catalog { //! Creates a enum in the catalog. DUCKDB_API optional_ptr CreateType(CatalogTransaction transaction, SchemaCatalogEntry &schema, CreateTypeInfo &info); - //! Creates a collation in the catalog - DUCKDB_API static optional_ptr CreateCollation(CatalogTransaction transaction, - SchemaCatalogEntry &schema, CreateCollationInfo &info); //! Creates a coordinate system in the catalog DUCKDB_API static optional_ptr CreateCoordinateSystem(CatalogTransaction transaction, SchemaCatalogEntry &schema, @@ -251,7 +243,10 @@ class Catalog { virtual bool SupportsNestedSchemas() const { return false; } - //! Reject unsupported nested paths before invoking extension catalog methods. + //! Whether the schema path of name is not nested, or nested and supported by this catalog. Lookups of an + //! unsupported path find nothing, without passing the path to the catalog's LookupSchema. + DUCKDB_API bool SupportsSchemaPath(const QualifiedName &name, CatalogType type) const; + //! Reject unsupported nested paths when creating a schema. DUCKDB_API void CheckNestedSchemaSupport(const QualifiedName &name, CatalogType type) const; //! Resolve a string schema argument, preferring an existing nested entry over a literal dotted schema. DUCKDB_API QualifiedName ResolveEntryName(ClientContext &context, const string &schema_arg, @@ -305,9 +300,11 @@ class Catalog { OnEntryNotFound if_not_found); //! Scans all the schemas in the system one-by-one, invoking the callback for each entry DUCKDB_API virtual void ScanSchemas(ClientContext &context, std::function callback) = 0; - //! The schemas a system catalog scan (duckdb_tables, duckdb_views) visits in this catalog, given the filters - //! pushed down on the schema identity columns. Lists every schema and keeps those the filters accept. A catalog - //! may override this to avoid the listing; it must return every schema the filters accept and may return more. + //! The schemas a system catalog scan (such as duckdb_tables) visits in this catalog, given the filters pushed down + //! on the schema identity columns. Lists every schema and keeps those the filters accept. A catalog may override + //! this to avoid the listing; it must return every schema the filters accept and may return more. A schema_name + //! filter is evaluated on the schema's own name, so with nested schemas it accepts every schema with that leaf + //! name at any depth. DUCKDB_API virtual vector> GetSchemasForScan(ClientContext &context, const SchemaScanFilters &filters); diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/collate_catalog_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/collate_catalog_entry.hpp deleted file mode 100644 index e5bc8dd6d..000000000 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/collate_catalog_entry.hpp +++ /dev/null @@ -1,39 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/catalog/catalog_entry/collate_catalog_entry.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/catalog/standard_entry.hpp" -#include "duckdb/function/function.hpp" -#include "duckdb/parser/parsed_data/create_collation_info.hpp" - -namespace duckdb { - -//! A collation catalog entry -class CollateCatalogEntry : public StandardEntry { -public: - static constexpr const CatalogType Type = CatalogType::COLLATION_ENTRY; - static constexpr const char *Name = "collation"; - -public: - CollateCatalogEntry(Catalog &catalog, SchemaCatalogEntry &schema, CreateCollationInfo &info) - : StandardEntry(CatalogType::COLLATION_ENTRY, schema, catalog, info.GetCollationName()), - function(info.function), combinable(info.combinable), - not_required_for_equality(info.not_required_for_equality) { - } - - //! The collation function to push in case collation is required - ScalarFunction function; - //! Whether or not the collation can be combined with other collations. - bool combinable; - //! Whether or not the collation is required for equality comparisons or not. For many collations a binary - //! comparison for equality comparisons is correct, allowing us to skip the collation in these cases which greatly - //! speeds up processing. - bool not_required_for_equality; -}; -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_schema_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_schema_entry.hpp index a0a151a53..d2540a3d4 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_schema_entry.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry/duck_schema_entry.hpp @@ -35,8 +35,6 @@ class DuckSchemaEntry : public SchemaCatalogEntry { CatalogSet functions; //! The catalog set holding the sequences CatalogSet sequences; - //! The catalog set holding the collations - CatalogSet collations; //! The catalog set holding the types CatalogSet types; //! The catalog set holding the coordinate systems @@ -60,7 +58,6 @@ class DuckSchemaEntry : public SchemaCatalogEntry { CreateCopyFunctionInfo &info) override; optional_ptr CreatePragmaFunction(CatalogTransaction transaction, CreatePragmaFunctionInfo &info) override; - optional_ptr CreateCollation(CatalogTransaction transaction, CreateCollationInfo &info) override; optional_ptr CreateCoordinateSystem(CatalogTransaction transaction, CreateCoordinateSystemInfo &info) override; optional_ptr CreateType(CatalogTransaction transaction, CreateTypeInfo &info) override; diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/list.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/list.hpp index 1be747588..f1ea7d6bf 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/list.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry/list.hpp @@ -1,5 +1,4 @@ #include "duckdb/catalog/catalog_entry/aggregate_function_catalog_entry.hpp" -#include "duckdb/catalog/catalog_entry/collate_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/copy_function_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/index_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/scalar_macro_catalog_entry.hpp" diff --git a/src/duckdb/src/include/duckdb/catalog/catalog_entry/schema_catalog_entry.hpp b/src/duckdb/src/include/duckdb/catalog/catalog_entry/schema_catalog_entry.hpp index 1a85520f5..aa460bc58 100644 --- a/src/duckdb/src/include/duckdb/catalog/catalog_entry/schema_catalog_entry.hpp +++ b/src/duckdb/src/include/duckdb/catalog/catalog_entry/schema_catalog_entry.hpp @@ -25,7 +25,6 @@ enum class OnCreateConflict : uint8_t; struct AlterTableInfo; struct CreateIndexInfo; struct CreateFunctionInfo; -struct CreateCollationInfo; struct CreateCoordinateSystemInfo; struct CreateViewInfo; struct BoundCreateTableInfo; @@ -117,10 +116,6 @@ class SchemaCatalogEntry : public InCatalogEntry { CreatePragmaFunctionInfo &info) { throw NotImplementedException("Pragma functions are not supported in schema %s", name); } - //! Create a collation within the given schema - virtual optional_ptr CreateCollation(CatalogTransaction transaction, CreateCollationInfo &info) { - throw NotImplementedException("Collations are not supported in schema %s", name); - } //! Create a coordinate system within the given schema virtual optional_ptr CreateCoordinateSystem(CatalogTransaction transaction, CreateCoordinateSystemInfo &info) { diff --git a/src/duckdb/src/include/duckdb/common/allocator.hpp b/src/duckdb/src/include/duckdb/common/allocator.hpp index c94fbe5ed..2089c657b 100644 --- a/src/duckdb/src/include/duckdb/common/allocator.hpp +++ b/src/duckdb/src/include/duckdb/common/allocator.hpp @@ -162,7 +162,7 @@ void DeleteArray(T *ptr, idx_t size) { } template -T *AllocateObject(ARGS &&... args) { +T *AllocateObject(ARGS &&...args) { auto data = Allocator::DefaultAllocator().AllocateData(sizeof(T)); return new (data) T(std::forward(args)...); } @@ -197,17 +197,22 @@ class HugeAllocation { idx_t GetSize() const { return allocated_size; } + //! Approximate fallback-backing ownership supplied by BlockAllocator; unknown after untracked reuse. + optional_idx GetAllocationShard() const { + return allocation_shard; + } bool IsSet() const { return pointer; } DUCKDB_API void Reset(); private: - HugeAllocation(BufferAllocator &allocator, data_ptr_t pointer, idx_t allocated_size); + HugeAllocation(BufferAllocator &allocator, data_ptr_t pointer, idx_t allocated_size, optional_idx allocation_shard); optional_ptr allocator; data_ptr_t pointer; idx_t allocated_size; + optional_idx allocation_shard; }; //! The BufferAllocator is a wrapper around the global allocator class that sends any allocations made through the @@ -230,7 +235,7 @@ class BufferAllocator : public Allocator { private: explicit BufferAllocator(StandardBufferManager &manager); - void FreeHuge(data_ptr_t pointer, idx_t size); + void FreeHuge(data_ptr_t pointer, idx_t size, optional_idx allocation_shard); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/arena_containers/arena_sql_value_map.hpp b/src/duckdb/src/include/duckdb/common/arena_containers/arena_sql_value_map.hpp new file mode 100644 index 000000000..ef04136a0 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/arena_containers/arena_sql_value_map.hpp @@ -0,0 +1,24 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/arena_containers/arena_sql_value_map.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/arena_stl_allocator.hpp" +#include "duckdb/common/types/sql_value_map.hpp" + +namespace duckdb { + +template +using arena_sql_value_map_t = unordered_map, SQLValueEquality, + arena_stl_allocator>>; + +template +using arena_sql_value_ordered_map_t = + map, arena_stl_allocator>>; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/arena_linked_list.hpp b/src/duckdb/src/include/duckdb/common/arena_linked_list.hpp index 0c98fe29b..fdc91b3a0 100644 --- a/src/duckdb/src/include/duckdb/common/arena_linked_list.hpp +++ b/src/duckdb/src/include/duckdb/common/arena_linked_list.hpp @@ -50,7 +50,7 @@ class ArenaLinkedList { } template - void emplace_back(ARGS &&... args) { + void emplace_back(ARGS &&...args) { auto node = arena.Make(std::forward(args)...); auto ptr = head ? &tail->next : &head; *ptr = node; diff --git a/src/duckdb/src/include/duckdb/common/bignum.hpp b/src/duckdb/src/include/duckdb/common/bignum.hpp index 62be0f8f8..b4a1f048f 100644 --- a/src/duckdb/src/include/duckdb/common/bignum.hpp +++ b/src/duckdb/src/include/duckdb/common/bignum.hpp @@ -22,6 +22,7 @@ class StringHeap; class ArenaAllocator; class ClientContext; class Context; +struct hugeint_t; struct bignum_t { string_t data; @@ -112,6 +113,8 @@ struct BignumIntermediate { //! Multiplies two BignumIntermediates and returns a string_t result, equivalent of a * static string_t Multiply(StringHeap &heap, BignumArithmeticState &state, const BignumIntermediate &lhs, const BignumIntermediate &rhs); + //! The exact product of two integers, including products wider than a HUGEINT + static string_t Multiply(StringHeap &heap, hugeint_t lhs, hugeint_t rhs); //! Multiplies two magnitudes given as little-endian bignum_digit_t digits, result = lhs * rhs without leading zeros DUCKDB_API static void MultiplyMagnitudes(BignumArithmeticState &state, const unsafe_vector &lhs, const unsafe_vector &rhs, diff --git a/src/duckdb/src/include/duckdb/common/bitpacking.hpp b/src/duckdb/src/include/duckdb/common/bitpacking.hpp index c4f10e071..2dbc25338 100644 --- a/src/duckdb/src/include/duckdb/common/bitpacking.hpp +++ b/src/duckdb/src/include/duckdb/common/bitpacking.hpp @@ -78,6 +78,18 @@ class BitpackingPrimitives { return UnPackGroup(dst, src, width, skip_sign_extension); } + // Unpack unsigned 32/64-bit residuals and add the frame. + template ::type> + inline static void UnPackBufferWithFrame(data_ptr_t dst, const_data_ptr_t src, idx_t count, + bitpacking_width_t width, T frame) { + static_assert(sizeof(T) == sizeof(uint32_t) || sizeof(T) == sizeof(uint64_t), + "Fused frame unpacking requires 32/64-bit values"); + D_ASSERT(count % BITPACKING_ALGORITHM_GROUP_SIZE == 0); + duckdb_fastpforlib::fastunpack_with_frame(reinterpret_cast(src), reinterpret_cast(dst), + width, static_cast(frame), + count / BITPACKING_ALGORITHM_GROUP_SIZE); + } + // Calculates the minimum required number of bits per value that can store all values template ::IsSigned()> inline static bitpacking_width_t MinimumBitWidth(T value) { diff --git a/src/duckdb/src/include/duckdb/common/buffer_ptr.hpp b/src/duckdb/src/include/duckdb/common/buffer_ptr.hpp new file mode 100644 index 000000000..a72365a99 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/buffer_ptr.hpp @@ -0,0 +1,271 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/buffer_ptr.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/memory_safety.hpp" + +#include +#include +#include +#include +#include + +namespace duckdb { + +template +class buffer_ptr; +template +class enable_buffer_from_this; +template +buffer_ptr make_buffer(ARGS &&...args); + +namespace buffer_ptr_detail { + +struct ControlBlock { + explicit ControlBlock(void (*destroy_p)(ControlBlock *)) noexcept : destroy(destroy_p) { + } + + void AddReference() noexcept { + auto previous = references.fetch_add(1, std::memory_order_relaxed); + // Leave ample headroom for concurrent increments before terminating. + if (previous == 0 || previous >= (std::numeric_limits::max)() / 2) { + std::terminate(); + } + } + + void Release() noexcept { + // Acquiring an owner requires an existing strong owner. With no weak owners, + // a sole owner cannot race with an increment and needs no atomic decrement. + if (references.load(std::memory_order_acquire) == 1) { + // buffer_from_this must also reject acquisition during destruction. + references.store(0, std::memory_order_relaxed); + destroy(this); + return; + } + if (references.fetch_sub(1, std::memory_order_release) == 1) { + // Synchronize with the release sequence before destroying the payload. + (void)references.load(std::memory_order_acquire); + destroy(this); + } + } + + std::atomic references {1}; + void (*destroy)(ControlBlock *); +}; + +template +struct Allocation : ControlBlock { + template + explicit Allocation(ARGS &&...args) : ControlBlock(Destroy), value(std::forward(args)...) { + } + + static void Destroy(ControlBlock *block) { + delete static_cast(block); + } + + T value; +}; + +} // namespace buffer_ptr_detail + +//! Strong-only, atomic shared ownership for buffers. Independent handles can be +//! used concurrently; modifying the same handle requires external synchronization. +//! Create owners with make_buffer. Aliases retain an owner but may point elsewhere. +template +class buffer_ptr { // NOLINT: mimic std casing +public: + using element_type = T; +#if defined(_LIBCPP_VERSION) + using __trivially_relocatable = buffer_ptr; // NOLINT: libc++ extension point +#endif + + buffer_ptr() noexcept = default; + buffer_ptr(std::nullptr_t) noexcept { // NOLINT: allow implicit nullptr + } + buffer_ptr(const buffer_ptr &other) noexcept : buffer_ptr(other, other.ptr) { + } + template ::value, int>::type = 0> + buffer_ptr(const buffer_ptr &other) noexcept // NOLINT: allow implicit conversion + : buffer_ptr(other, other.ptr) { + } + buffer_ptr(buffer_ptr &&other) noexcept : buffer_ptr(std::move(other), other.ptr) { + } + template ::value, int>::type = 0> + buffer_ptr(buffer_ptr &&other) noexcept // NOLINT: allow implicit conversion + : buffer_ptr(std::move(other), other.ptr) { + } + template + buffer_ptr(const buffer_ptr &owner, T *ptr_p) noexcept : ptr(ptr_p), control(owner.control) { + if (control) { + control->AddReference(); + } + } + template + buffer_ptr(buffer_ptr &&owner, T *ptr_p) noexcept : ptr(ptr_p), control(owner.control) { + owner.ptr = nullptr; + owner.control = nullptr; + } + ~buffer_ptr() { + if (control) { + control->Release(); + } + } + + buffer_ptr &operator=(const buffer_ptr &other) noexcept { + return Assign(other); + } + template ::value, int>::type = 0> + buffer_ptr &operator=(const buffer_ptr &other) noexcept { + return Assign(other); + } + buffer_ptr &operator=(buffer_ptr &&other) noexcept { + buffer_ptr(std::move(other)).swap(*this); + return *this; + } + template ::value, int>::type = 0> + buffer_ptr &operator=(buffer_ptr &&other) noexcept { + buffer_ptr(std::move(other)).swap(*this); + return *this; + } + + void reset() noexcept { // NOLINT: mimic std casing + buffer_ptr().swap(*this); + } + void swap(buffer_ptr &other) noexcept { // NOLINT: mimic std casing + std::swap(ptr, other.ptr); + std::swap(control, other.control); + } + T *get() const noexcept { // NOLINT: mimic std casing + return ptr; + } + uint64_t use_count() const noexcept { // NOLINT: mimic std casing + return control ? control->references.load(std::memory_order_relaxed) : 0; + } + explicit operator bool() const noexcept { + return ptr != nullptr; + } + typename std::add_lvalue_reference::type operator*() const { + AssertNotNull(); + return *ptr; + } + T *operator->() const { + AssertNotNull(); + return ptr; + } + +private: + template + friend class buffer_ptr; + template + friend class enable_buffer_from_this; + template + friend buffer_ptr make_buffer(ARGS &&...args); + + buffer_ptr(T *ptr_p, buffer_ptr_detail::ControlBlock *control_p) noexcept : ptr(ptr_p), control(control_p) { + } + template + buffer_ptr &Assign(const buffer_ptr &other) noexcept { + if (control == other.control) { + // Two aliases of the same owner can have different stored pointers. + ptr = other.ptr; + } else { + // Acquire first: other can be a member of the object being released. + buffer_ptr(other).swap(*this); + } + return *this; + } + void AssertNotNull() const { +#if !defined(DUCKDB_DEBUG_NO_SAFETY) && !defined(DUCKDB_CLANG_TIDY) + if (!ptr) { + ThrowNullSharedPtrDereference(); + } +#endif + } + template + void EnableOwner(const enable_buffer_from_this *object) noexcept { + object->control = control; + } + void EnableOwner(...) noexcept { + } + + T *ptr = nullptr; + buffer_ptr_detail::ControlBlock *control = nullptr; +}; + +template +bool operator==(const buffer_ptr &left, const buffer_ptr &right) noexcept { + return left.get() == right.get(); +} +template +bool operator!=(const buffer_ptr &left, const buffer_ptr &right) noexcept { + return !(left == right); +} +template +bool operator==(const buffer_ptr &ptr, std::nullptr_t) noexcept { + return !ptr; +} +template +bool operator==(std::nullptr_t, const buffer_ptr &ptr) noexcept { + return !ptr; +} +template +bool operator!=(const buffer_ptr &ptr, std::nullptr_t) noexcept { + return bool(ptr); +} +template +bool operator!=(std::nullptr_t, const buffer_ptr &ptr) noexcept { + return bool(ptr); +} + +//! Acquire another strong owner while an existing owner keeps this object alive. +//! This is not a weak reference: it cannot be used concurrently with final release. +template +class enable_buffer_from_this { // NOLINT: mimic std casing +public: + buffer_ptr buffer_from_this() { // NOLINT: mimic std casing + AddReference(); + return buffer_ptr(static_cast(this), control); + } + buffer_ptr buffer_from_this() const { // NOLINT: mimic std casing + AddReference(); + return buffer_ptr(static_cast(this), control); + } + +protected: + enable_buffer_from_this() noexcept = default; + enable_buffer_from_this(const enable_buffer_from_this &) noexcept { + } + enable_buffer_from_this &operator=(const enable_buffer_from_this &) noexcept { + // Assignment changes the payload, not its owner. + return *this; + } + ~enable_buffer_from_this() = default; + +private: + template + friend class buffer_ptr; + + void AddReference() const { + if (!control || control->references.load(std::memory_order_relaxed) == 0) { + throw std::bad_weak_ptr(); + } + control->AddReference(); + } + mutable buffer_ptr_detail::ControlBlock *control = nullptr; +}; + +template +buffer_ptr make_buffer(ARGS &&...args) { // NOLINT: mimic std casing + auto allocation = new buffer_ptr_detail::Allocation(std::forward(args)...); + buffer_ptr result(&allocation->value, allocation); + result.EnableOwner(&allocation->value); + return result; +} + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/cow_ptr.hpp b/src/duckdb/src/include/duckdb/common/cow_ptr.hpp new file mode 100644 index 000000000..d21507b3b --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/cow_ptr.hpp @@ -0,0 +1,128 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/cow_ptr.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/exception.hpp" +#include "duckdb/common/helper.hpp" +#include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/shared_ptr.hpp" +#include "duckdb/common/unique_ptr.hpp" + +namespace duckdb { + +//! A copy-on-write pointer: copies of a cow_ptr share the object, reads are const and writes go through write(). +//! T must provide a Copy() method that returns a unique_ptr to (a base class of) T. +template +class cow_ptr { // NOLINT: mimic std casing +public: + cow_ptr() noexcept { + } + cow_ptr(std::nullptr_t) noexcept { // NOLINT: allow implicit creation from nullptr + } + //! Takes sole ownership of the object, so no mutable alias exists outside of the cow_ptr + template ::value, int>::type = 0> + cow_ptr(unique_ptr &&other) // NOLINT: allow implicit creation from unique pointer + : ptr(std::move(other)) { + } + + //! Constructs the object in place - U is the (derived) type to construct + template + static cow_ptr make(ARGS &&...args) { // NOLINT: mimic std casing + cow_ptr result; + result.ptr = make_shared_ptr(std::forward(args)...); + return result; + } + + //! Adopts the object owned by a unique_ptr + template + static cow_ptr from_unique(unique_ptr &&other) { // NOLINT: mimic std casing + return cow_ptr(std::move(other)); + } + //! Shares the object of a shared_ptr - the object is copied on write for as long as the shared_ptr holds on to it + template + static cow_ptr from_shared(shared_ptr other) { // NOLINT: mimic std casing + cow_ptr result; + result.ptr = std::move(other); + return result; + } + + // copying shares the underlying object + cow_ptr(const cow_ptr &other) = default; + cow_ptr &operator=(const cow_ptr &other) = default; + cow_ptr(cow_ptr &&other) noexcept = default; + cow_ptr &operator=(cow_ptr &&other) noexcept = default; + +public: + const T *operator->() const { + return ptr.operator->(); + } + const T &operator*() const { + return *ptr; + } + //! Read access never copies + const T &read() const { // NOLINT: mimic std casing + return *ptr; + } + const T *get() const { // NOLINT: mimic std casing + return ptr.get(); + } + operator optional_ptr() const { // NOLINT: allow implicit conversion to a read-only optional_ptr + return optional_ptr(ptr.get()); + } + explicit operator bool() const { + return ptr.operator bool(); + } + bool operator==(std::nullptr_t) const { + return !ptr; + } + bool operator!=(std::nullptr_t) const { + return ptr.operator bool(); + } + void reset() { // NOLINT: mimic std casing + ptr.reset(); + } + + //! Write access: returns a mutable reference to the object, copying it first if it is shared with another cow_ptr. + //! Requires exclusive access to this cow_ptr: no other thread may use it or hold a reference obtained from it. + T &write() { // NOLINT: mimic std casing + if (!ptr) { + throw InternalException("Attempting to write to a cow_ptr that is not set"); + } + detach(); + return *ptr; + } + //! Mutable counterpart of get(): same as write(), but returns a pointer that is null if the cow_ptr is not set + T *get_mut() { // NOLINT: mimic std casing + detach(); + return ptr.get(); + } + + //! Whether both pointers refer to the same object + bool shares_with(const cow_ptr &other) const { // NOLINT: mimic std casing + return ptr == other.ptr; + } + +private: + //! Stop sharing the object with other cow_ptrs by replacing it with a copy + void detach() { // NOLINT: mimic std casing + if (ptr && ptr.use_count() > 1) { + ptr = FromCopy(ptr->Copy()); + } + } + template + static shared_ptr FromCopy(unique_ptr copy) { + return shared_ptr(unique_ptr_cast(std::move(copy))); + } + +private: + shared_ptr ptr; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/csv_writer.hpp b/src/duckdb/src/include/duckdb/common/csv_writer.hpp index bebf73193..de04d050a 100644 --- a/src/duckdb/src/include/duckdb/common/csv_writer.hpp +++ b/src/duckdb/src/include/duckdb/common/csv_writer.hpp @@ -63,10 +63,10 @@ class CSVWriter { //! Create a CSVWriter that writes to a (non-owned) WriteStream CSVWriter(WriteStream &stream, vector name_list, bool shared = true); //! Create a CSVWriter with the full set of options that writes to a (non-owned) AsyncFileWriter - CSVWriter(CSVReaderOptions &options, AsyncFileWriter &file_writer, bool shared = true); + CSVWriter(const CSVReaderOptions &options, AsyncFileWriter &file_writer, bool shared = true); //! Create a CSVWriter that writes to a file - CSVWriter(CSVReaderOptions &options, FileSystem &fs, const string &file_path, FileCompressionType compression, + CSVWriter(const CSVReaderOptions &options, FileSystem &fs, const string &file_path, FileCompressionType compression, QueryContext context = QueryContext(), bool shared = true); ~CSVWriter(); diff --git a/src/duckdb/src/include/duckdb/common/enum_util.hpp b/src/duckdb/src/include/duckdb/common/enum_util.hpp index 3a7a56f5c..64e90067f 100644 --- a/src/duckdb/src/include/duckdb/common/enum_util.hpp +++ b/src/duckdb/src/include/duckdb/common/enum_util.hpp @@ -46,6 +46,8 @@ enum class AccessMode : uint8_t; enum class AdaptiveFilterSource : uint8_t; +enum class AggregateCombineSourceRetention : uint8_t; + enum class AggregateCombineType : uint8_t; enum class AggregateDistinctDependent : uint8_t; @@ -220,6 +222,8 @@ enum class DistinctCountSource : uint8_t; enum class DistinctType : uint8_t; +enum class DistinctnessPropagation : uint8_t; + enum class ErrorType : uint16_t; enum class ExceptionFormatValueType : uint8_t; @@ -294,6 +298,8 @@ enum class FunctionStability : uint8_t; enum class GateStatus : uint8_t; +enum class GeometryModel : uint8_t; + enum class GeometryStorageType : uint8_t; enum class GeometryType : uint8_t; @@ -334,6 +340,8 @@ enum class JoinOrderOperatorType : uint8_t; enum class JoinRefType : uint8_t; +enum class JoinSimplificationPhase : uint8_t; + enum class JoinType : uint8_t; enum class KeywordCase : uint8_t; @@ -474,6 +482,8 @@ enum class PipelineBroadcastExchangeOrderMode : uint8_t; enum class PipelineBroadcastExchangeScanMode : uint8_t; +enum class PipelineExecutionOrder : uint8_t; + enum class PipelineInputMode : uint8_t; enum class PipelineScheduleGraph : uint8_t; @@ -526,8 +536,6 @@ enum class RecursiveProbeSidePreference : uint8_t; enum class RegexMatchOperatorSemantics : uint8_t; -enum class RelationType : uint8_t; - enum class RemoteCapability : uint8_t; enum class RemoveUnusedColumnsMode : uint8_t; @@ -554,6 +562,8 @@ enum class SamplingState : uint8_t; enum class ScanReadAheadAcquire : uint8_t; +enum class ScanReadAheadPolicy : uint8_t; + enum class ScanType : uint8_t; enum class SecretDisplayType : uint8_t; @@ -598,6 +608,8 @@ enum class SourceBatchIndexState : uint8_t; enum class SourceResultType : uint8_t; +enum class StandardByteClass : uint8_t; + enum class StarExpressionType : uint8_t; enum class StateMemoryOwnership : uint8_t; @@ -730,6 +742,9 @@ const char* EnumUtil::ToChars(AccessMode value); template<> const char* EnumUtil::ToChars(AdaptiveFilterSource value); +template<> +const char* EnumUtil::ToChars(AggregateCombineSourceRetention value); + template<> const char* EnumUtil::ToChars(AggregateCombineType value); @@ -991,6 +1006,9 @@ const char* EnumUtil::ToChars(DistinctCountSource value); template<> const char* EnumUtil::ToChars(DistinctType value); +template<> +const char* EnumUtil::ToChars(DistinctnessPropagation value); + template<> const char* EnumUtil::ToChars(ErrorType value); @@ -1102,6 +1120,9 @@ const char* EnumUtil::ToChars(FunctionStability value); template<> const char* EnumUtil::ToChars(GateStatus value); +template<> +const char* EnumUtil::ToChars(GeometryModel value); + template<> const char* EnumUtil::ToChars(GeometryStorageType value); @@ -1162,6 +1183,9 @@ const char* EnumUtil::ToChars(JoinOrderOperatorType value template<> const char* EnumUtil::ToChars(JoinRefType value); +template<> +const char* EnumUtil::ToChars(JoinSimplificationPhase value); + template<> const char* EnumUtil::ToChars(JoinType value); @@ -1372,6 +1396,9 @@ const char* EnumUtil::ToChars(PipelineBroadc template<> const char* EnumUtil::ToChars(PipelineBroadcastExchangeScanMode value); +template<> +const char* EnumUtil::ToChars(PipelineExecutionOrder value); + template<> const char* EnumUtil::ToChars(PipelineInputMode value); @@ -1450,9 +1477,6 @@ const char* EnumUtil::ToChars(RecursiveProbeSidePr template<> const char* EnumUtil::ToChars(RegexMatchOperatorSemantics value); -template<> -const char* EnumUtil::ToChars(RelationType value); - template<> const char* EnumUtil::ToChars(RemoteCapability value); @@ -1492,6 +1516,9 @@ const char* EnumUtil::ToChars(SamplingState value); template<> const char* EnumUtil::ToChars(ScanReadAheadAcquire value); +template<> +const char* EnumUtil::ToChars(ScanReadAheadPolicy value); + template<> const char* EnumUtil::ToChars(ScanType value); @@ -1558,6 +1585,9 @@ const char* EnumUtil::ToChars(SourceBatchIndexState value template<> const char* EnumUtil::ToChars(SourceResultType value); +template<> +const char* EnumUtil::ToChars(StandardByteClass value); + template<> const char* EnumUtil::ToChars(StarExpressionType value); @@ -1745,6 +1775,9 @@ AccessMode EnumUtil::FromString(const char *value); template<> AdaptiveFilterSource EnumUtil::FromString(const char *value); +template<> +AggregateCombineSourceRetention EnumUtil::FromString(const char *value); + template<> AggregateCombineType EnumUtil::FromString(const char *value); @@ -2006,6 +2039,9 @@ DistinctCountSource EnumUtil::FromString(const char *value) template<> DistinctType EnumUtil::FromString(const char *value); +template<> +DistinctnessPropagation EnumUtil::FromString(const char *value); + template<> ErrorType EnumUtil::FromString(const char *value); @@ -2117,6 +2153,9 @@ FunctionStability EnumUtil::FromString(const char *value); template<> GateStatus EnumUtil::FromString(const char *value); +template<> +GeometryModel EnumUtil::FromString(const char *value); + template<> GeometryStorageType EnumUtil::FromString(const char *value); @@ -2177,6 +2216,9 @@ JoinOrderOperatorType EnumUtil::FromString(const char *va template<> JoinRefType EnumUtil::FromString(const char *value); +template<> +JoinSimplificationPhase EnumUtil::FromString(const char *value); + template<> JoinType EnumUtil::FromString(const char *value); @@ -2387,6 +2429,9 @@ PipelineBroadcastExchangeOrderMode EnumUtil::FromString PipelineBroadcastExchangeScanMode EnumUtil::FromString(const char *value); +template<> +PipelineExecutionOrder EnumUtil::FromString(const char *value); + template<> PipelineInputMode EnumUtil::FromString(const char *value); @@ -2465,9 +2510,6 @@ RecursiveProbeSidePreference EnumUtil::FromString( template<> RegexMatchOperatorSemantics EnumUtil::FromString(const char *value); -template<> -RelationType EnumUtil::FromString(const char *value); - template<> RemoteCapability EnumUtil::FromString(const char *value); @@ -2507,6 +2549,9 @@ SamplingState EnumUtil::FromString(const char *value); template<> ScanReadAheadAcquire EnumUtil::FromString(const char *value); +template<> +ScanReadAheadPolicy EnumUtil::FromString(const char *value); + template<> ScanType EnumUtil::FromString(const char *value); @@ -2573,6 +2618,9 @@ SourceBatchIndexState EnumUtil::FromString(const char *va template<> SourceResultType EnumUtil::FromString(const char *value); +template<> +StandardByteClass EnumUtil::FromString(const char *value); + template<> StarExpressionType EnumUtil::FromString(const char *value); diff --git a/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp b/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp index 810a9c374..36dd1e417 100644 --- a/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp @@ -66,7 +66,13 @@ enum class OptimizerType : uint32_t { WINDOW_JOIN_PUSHDOWN = 49, SELF_JOIN_AGGREGATE = 50, SCALAR_AGGREGATE_MERGE = 51, - DUPLICATE_ELIMINATED_DOMAIN = 52 + DUPLICATE_ELIMINATED_DOMAIN = 52, + REDUNDANT_DISTINCT = 53, + CASE_TO_FILTER_AGGREGATE = 54, + WINDOW_FUSION = 55, + SET_OPERATION_AGGREGATE = 56, + JOIN_TO_SEMI_JOIN = 57, + MARK_JOIN_SIMPLIFIER = 58 }; string OptimizerTypeToString(OptimizerType type); diff --git a/src/duckdb/src/include/duckdb/common/enums/pipeline_execution_order.hpp b/src/duckdb/src/include/duckdb/common/enums/pipeline_execution_order.hpp new file mode 100644 index 000000000..012be8a55 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/enums/pipeline_execution_order.hpp @@ -0,0 +1,17 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/enums/pipeline_execution_order.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/constants.hpp" + +namespace duckdb { + +enum class PipelineExecutionOrder : uint8_t { PARTITIONED, ORDERED, UNORDERED }; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/enums/relation_type.hpp b/src/duckdb/src/include/duckdb/common/enums/relation_type.hpp deleted file mode 100644 index bca6af491..000000000 --- a/src/duckdb/src/include/duckdb/common/enums/relation_type.hpp +++ /dev/null @@ -1,52 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/common/enums/relation_type.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/constants.hpp" - -namespace duckdb { - -//===--------------------------------------------------------------------===// -// Catalog Types -//===--------------------------------------------------------------------===// -enum class RelationType : uint8_t { - INVALID_RELATION, - TABLE_RELATION, - PROJECTION_RELATION, - FILTER_RELATION, - EXPLAIN_RELATION, - CROSS_PRODUCT_RELATION, - JOIN_RELATION, - AGGREGATE_RELATION, - SET_OPERATION_RELATION, - DISTINCT_RELATION, - LIMIT_RELATION, - ORDER_RELATION, - CREATE_VIEW_RELATION, - CREATE_TABLE_RELATION, - INSERT_RELATION, - VALUE_LIST_RELATION, - MATERIALIZED_RELATION, - DELETE_RELATION, - UPDATE_RELATION, - WRITE_CSV_RELATION, - WRITE_PARQUET_RELATION, - READ_CSV_RELATION, - SUBQUERY_RELATION, - TABLE_FUNCTION_RELATION, - VIEW_RELATION, - QUERY_RELATION, - DELIM_JOIN_RELATION, - DELIM_GET_RELATION, - EXTENSION_RELATION = 255 -}; - -string RelationTypeToString(RelationType type); - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/enums/statement_type.hpp b/src/duckdb/src/include/duckdb/common/enums/statement_type.hpp index d458a00c6..f7d9f9459 100644 --- a/src/duckdb/src/include/duckdb/common/enums/statement_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/statement_type.hpp @@ -42,7 +42,7 @@ enum class StatementType : uint8_t { CALL_STATEMENT, // CALL statement type SET_STATEMENT, // SET statement type LOAD_STATEMENT, // LOAD statement type - RELATION_STATEMENT, + RELATION_STATEMENT, // nothing produces it, but the C API publishes its value EXTENSION_STATEMENT, LOGICAL_PLAN_STATEMENT, ATTACH_STATEMENT, diff --git a/src/duckdb/src/include/duckdb/common/enums/tableref_type.hpp b/src/duckdb/src/include/duckdb/common/enums/tableref_type.hpp index d00fc7fa0..6477d7028 100644 --- a/src/duckdb/src/include/duckdb/common/enums/tableref_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/tableref_type.hpp @@ -27,7 +27,7 @@ enum class TableReferenceType : uint8_t { PIVOT = 9, // pivot statement SHOW_REF = 10, // SHOW statement COLUMN_DATA = 11, // column data collection - DELIM_GET = 12, // Delim get ref + DELIM_GET = 12, // no table reference has this type BOUND_TABLE_REF = 13, // Bound table ref MATCH_RECOGNIZE = 14 // MATCH_RECOGNIZE }; diff --git a/src/duckdb/src/include/duckdb/common/file_system.hpp b/src/duckdb/src/include/duckdb/common/file_system.hpp index 0ee66ec7b..52846ed2a 100644 --- a/src/duckdb/src/include/duckdb/common/file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/file_system.hpp @@ -377,9 +377,6 @@ class FileSystem { DUCKDB_API virtual unique_ptr OpenCompressedFile(QueryContext context, unique_ptr handle, bool write); - //! Create a LocalFileSystem. - DUCKDB_API static unique_ptr CreateLocal(); - //! Whether this is a LocalFileSystem instance. DUCKDB_API virtual bool IsLocalFileSystem() const; diff --git a/src/duckdb/src/include/duckdb/common/helper.hpp b/src/duckdb/src/include/duckdb/common/helper.hpp index 30eca7b61..bb6da0de9 100644 --- a/src/duckdb/src/include/duckdb/common/helper.hpp +++ b/src/duckdb/src/include/duckdb/common/helper.hpp @@ -72,7 +72,7 @@ struct TemplatedUniqueIf template inline typename TemplatedUniqueIf::templated_unique_single_t -make_uniq(ARGS&&... args) // NOLINT: mimic std style +make_uniq(ARGS&&...args) // NOLINT: mimic std style { return unique_ptr, true>(new DATA_TYPE(std::forward(args)...)); } @@ -80,7 +80,7 @@ make_uniq(ARGS&&... args) // NOLINT: mimic std style template inline shared_ptr -make_shared_ptr(ARGS&&... args) // NOLINT: mimic std style +make_shared_ptr(ARGS&&...args) // NOLINT: mimic std style { return shared_ptr(duckdb_base_std::make_shared(std::forward(args)...)); } @@ -88,7 +88,7 @@ make_shared_ptr(ARGS&&... args) // NOLINT: mimic std style template inline typename TemplatedUniqueIf::templated_unique_single_t -make_unsafe_uniq(ARGS&&... args) // NOLINT: mimic std style +make_unsafe_uniq(ARGS&&...args) // NOLINT: mimic std style { return unique_ptr, false>(new DATA_TYPE(std::forward(args)...)); } @@ -127,13 +127,13 @@ template template -unique_ptr make_uniq_base(ARGS &&... args) { // NOLINT: mimic std style +unique_ptr make_uniq_base(ARGS &&...args) { // NOLINT: mimic std style return unique_ptr(new T(std::forward(args)...)); } #ifdef DUCKDB_ENABLE_DEPRECATED_API template -unique_ptr make_unique_base(Args &&... args) { +unique_ptr make_unique_base(Args &&...args) { return unique_ptr(new T(std::forward(args)...)); } #endif // DUCKDB_ENABLE_DEPRECATED_API @@ -157,7 +157,7 @@ typename std::remove_reference::type&& move(T&& t) noexcept { #endif template -static duckdb::unique_ptr make_unique(ARGS&&... __args) { // NOLINT: mimic std style +static duckdb::unique_ptr make_unique(ARGS&&...__args) { // NOLINT: mimic std style #ifndef DUCKDB_ENABLE_DEPRECATED_API static_assert(sizeof(T) == 0, "Use make_uniq instead of make_unique!"); #endif // DUCKDB_ENABLE_DEPRECATED_API @@ -165,7 +165,7 @@ static duckdb::unique_ptr make_unique(ARGS&&... __args) { // NOLINT: mimic st } template -static duckdb::shared_ptr make_shared(ARGS&&... __args) { // NOLINT: mimic std style +static duckdb::shared_ptr make_shared(ARGS&&...__args) { // NOLINT: mimic std style #ifndef DUCKDB_ENABLE_DEPRECATED_API static_assert(sizeof(T) == 0, "Use make_shared_ptr instead of make_shared!"); #endif // DUCKDB_ENABLE_DEPRECATED_API diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp index 1906d26aa..4ac76903c 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp @@ -409,7 +409,7 @@ class MultiFileFunction : public TableFunction { can_skip_file = true; } else { current_reader_data.reader->PrepareReader(context, *global_state.global_state); - if (global_state.read_ahead) { + if (global_state.read_ahead && global_state.read_ahead->PrefetchEnabled()) { current_reader_data.reader->PrepareReadAhead(context, *global_state.global_state); } } @@ -610,6 +610,7 @@ class MultiFileFunction : public TableFunction { // covers a cancellation that signals without the lock gstate.async_open_settled.wait_for(parallel_lock, std::chrono::milliseconds(10)); parallel_lock.unlock(); + // the throttled FastInterruptCheck() would only read the clock every ~2.5s of waiting here context.InterruptCheck(); parallel_lock.lock(); } @@ -754,7 +755,7 @@ class MultiFileFunction : public TableFunction { continue; } - if (gstate.read_ahead) { + if (gstate.read_ahead && gstate.read_ahead->PrefetchEnabled()) { // read-ahead: open files on the async pool ahead of decoding, then wait for the front one ScheduleFileOpens(context, bind_data, gstate, parallel_lock); } else if (TryOpenNextFile(context, bind_data, gstate, parallel_lock)) { @@ -763,7 +764,7 @@ class MultiFileFunction : public TableFunction { // Check if the current file is being opened, in that case we need to wait for it. if (current_reader_data.file_state == MultiFileFileState::OPENING) { - if (gstate.read_ahead) { + if (gstate.read_ahead && gstate.read_ahead->PrefetchEnabled()) { WaitForAsyncOpen(context, gstate, parallel_lock); } else { WaitForFile(gstate.file_index, gstate, parallel_lock); @@ -810,7 +811,7 @@ class MultiFileFunction : public TableFunction { if (!bind_data.interface->SupportsReadAhead(bind_data)) { return; } - gstate.read_ahead = ScanReadAhead::Create(context); + gstate.read_ahead = ScanReadAhead::Create(context, ScanReadAheadPolicy::ORDERED); } static unique_ptr MultiFileInitGlobal(ClientContext &context, @@ -1374,9 +1375,10 @@ class MultiFileFunction : public TableFunction { return data.interface->GetCardinality(context, data, estimated_file_count); } - static void MultiFileComplexFilterPushdown(ClientContext &context, LogicalGet &get, FunctionData *bind_data_p, + static void MultiFileComplexFilterPushdown(ClientContext &context, LogicalGet &get, + optional_ptr bind_data_p, vector> &filters) { - auto &data = bind_data_p->Cast(); + auto &data = get.bind_data.write().Cast(); MultiFilePushdownInfo info(get.table_index, data.names, get.GetColumnIds(), get.extra_info); auto new_list = diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp index 345831e17..84fddedf7 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_reader.hpp @@ -111,9 +111,6 @@ struct MultiFileReader { //! Create a default MultiFileReader, function_name is used for errors DUCKDB_API static unique_ptr CreateDefault(const string &function_name = ""); - //! Create a LIST Value from a vector of strings (list of file paths) - static Value CreateValueFromFileList(const vector &files); - //! Add the parameters for multi-file readers (e.g. union_by_name, filename) to a table function //! Which of the multi-file options to declare on a function. A function that reads exactly one file per call //! takes only "allow_empty"; the others describe how several files are combined diff --git a/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file.hpp b/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file.hpp index f7906e738..81d2c64f7 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file.hpp @@ -85,10 +85,11 @@ struct TableFunctionFileInitInput { //! (Optional) The virtual columns among the column indexes, as a map of the index they are projected in to the //! virtual column id wanted there. A virtual column gets an index of its own, past the columns the function bound optional_ptr> virtual_columns; - //! The index of the file this function reads within the scan, and the number of files the scan reads in total. + //! The index of the file this function reads within the scan. //! TableFunctionInitInput::op is the operator all those files are read for optional_idx file_index; - idx_t file_count = 1; + //! (Optional) The scan's file list. Use GetFileCount for a bounded count without expanding every file + optional_ptr file_list; //! The multi-file input of an initialization - an empty one when the function is not read as part of a //! multi-file scan @@ -302,9 +303,9 @@ class TableFunctionFileReader : public BaseFileReader { unordered_map virtual_columns; //! The key-value metadata the wrapped function reported for this file InsertionOrderPreservingMap metadata; - //! The operator this file is scanned for, and the number of files that scan reads + //! The operator and file list of the scan this file is read for optional_ptr scan_op; - idx_t scan_file_count = 1; + optional_ptr scan_file_list; public: //! The state of the wrapped function for this file, if it has been initialized @@ -317,7 +318,7 @@ class TableFunctionFileReader : public BaseFileReader { } private: - //! Take the operator and file count of the scan this file is read for from its state + //! Take the operator and file list of the scan this file is read for from its state void SetScanState(GlobalTableFunctionState &gstate); //! The input the wrapped function is initialized with - "file_input" receives what the scan adds to it TableFunctionInitInput GetInitInput(TableFunctionFileInitInput &file_input) const; diff --git a/src/duckdb/src/include/duckdb/common/operator/cast_operators.hpp b/src/duckdb/src/include/duckdb/common/operator/cast_operators.hpp index aa1b46268..99c78b4c1 100644 --- a/src/duckdb/src/include/duckdb/common/operator/cast_operators.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/cast_operators.hpp @@ -1076,6 +1076,19 @@ struct TryCastToGeometry { template <> bool TryCastToGeometry::Operation(string_t input, string_t &result, Vector &result_vector, CastParameters ¶meters); +//===--------------------------------------------------------------------===// +// GEOGRAPHY +//===--------------------------------------------------------------------===// +struct TryCastToGeography { + template + static inline bool Operation(SRC input, DST &result, Vector &result_vector, CastParameters ¶meters) { + throw InternalException("Unsupported type for try cast to geography"); + } +}; + +template <> +bool TryCastToGeography::Operation(string_t input, string_t &result, Vector &result_vector, CastParameters ¶meters); + //===--------------------------------------------------------------------===// // Pointers //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/include/duckdb/common/owning_string_map.hpp b/src/duckdb/src/include/duckdb/common/owning_string_map.hpp index 8cd08cb11..5962b713a 100644 --- a/src/duckdb/src/include/duckdb/common/owning_string_map.hpp +++ b/src/duckdb/src/include/duckdb/common/owning_string_map.hpp @@ -13,6 +13,8 @@ #include "duckdb/common/allocator.hpp" #include "duckdb/common/pair.hpp" #include "duckdb/common/map.hpp" +#include "duckdb/common/arena_stl_allocator.hpp" +#include "duckdb/common/arena_containers/arena_unordered_map.hpp" #include "duckdb/storage/arena_allocator.hpp" #include @@ -30,10 +32,20 @@ class OwningStringMap { using value_type = typename STRING_MAP_TYPE::value_type; using iterator = typename STRING_MAP_TYPE::iterator; using const_iterator = typename STRING_MAP_TYPE::const_iterator; + using allocator_type = typename STRING_MAP_TYPE::allocator_type; public: OwningStringMap() : free_type(AllocatorFreeType::DOES_NOT_REQUIRE_FREE) { } + //! For maps whose nodes are allocated from an arena as well + explicit OwningStringMap(ArenaAllocator &arena) + : map(allocator_type(arena)), free_type(AllocatorFreeType::DOES_NOT_REQUIRE_FREE) { + } + //! Copies an arena-backed map into another arena, the keys are not copied + OwningStringMap(const OwningStringMap &other, ArenaAllocator &arena) + : map(other.map, allocator_type(arena)), free_type(AllocatorFreeType::DOES_NOT_REQUIRE_FREE) { + D_ASSERT(!other.allocator); + } explicit OwningStringMap(Allocator &allocator) : allocator(&allocator), free_type(AllocatorFreeType::REQUIRES_FREE) { } @@ -90,6 +102,14 @@ class OwningStringMap { return map.size(); } + void reserve(size_type n) { // NOLINT: match std style + map.reserve(n); + } + + allocator_type get_allocator() const noexcept { // NOLINT: match std style + return map.get_allocator(); + } + bool empty() const noexcept { // NOLINT: match std style return map.empty(); } @@ -164,4 +184,12 @@ class OwningStringMap { template using OrderedOwningStringMap = OwningStringMap>; +//! Owning string maps whose nodes are allocated from an arena as well +template +using ArenaOwningStringMap = OwningStringMap>; + +template +using ArenaOrderedOwningStringMap = + OwningStringMap, arena_stl_allocator>>>; + } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/prefetch.hpp b/src/duckdb/src/include/duckdb/common/prefetch.hpp new file mode 100644 index 000000000..761d634ce --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/prefetch.hpp @@ -0,0 +1,27 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/prefetch.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/assert.hpp" +#include "duckdb/common/typedefs.hpp" + +namespace duckdb { + +//! Prefetch a future address, computing it only when supported and within bounds. +template +inline void Prefetch(idx_t index, idx_t count, idx_t distance, GET_ADDRESS get_address) { + D_ASSERT(index <= count); +#if defined(__GNUC__) || defined(__clang__) + if (count - index > distance) { + __builtin_prefetch(get_address(index + distance), 0, 3); + } +#endif +} + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/shared_ptr_ipp.hpp b/src/duckdb/src/include/duckdb/common/shared_ptr_ipp.hpp index 53f0cb8b3..fe31d24e4 100644 --- a/src/duckdb/src/include/duckdb/common/shared_ptr_ipp.hpp +++ b/src/duckdb/src/include/duckdb/common/shared_ptr_ipp.hpp @@ -271,10 +271,13 @@ class shared_ptr { // NOLINT: invalid case style V *ptr) noexcept { typedef typename std::remove_cv::type non_const_u_t; if (object && object->__weak_this_.expired()) { - // __weak_this__ is the mutable variable returned by 'shared_from_this' - // it is initialized here - auto non_const = const_cast(static_cast(ptr)); // NOLINT: const cast - object->__weak_this_ = shared_ptr(*this, non_const); + if constexpr (std::is_convertible::value) { + // Initialize the weak owner without a temporary strong reference. + object->__weak_this_.internal = internal; + } else { + auto non_const = const_cast(static_cast(ptr)); // NOLINT: const cast + object->__weak_this_ = shared_ptr(*this, non_const); + } } } diff --git a/src/duckdb/src/include/duckdb/common/sorting/hashed_sort.hpp b/src/duckdb/src/include/duckdb/common/sorting/hashed_sort.hpp index d76d7ce82..2dc959b41 100644 --- a/src/duckdb/src/include/duckdb/common/sorting/hashed_sort.hpp +++ b/src/duckdb/src/include/duckdb/common/sorting/hashed_sort.hpp @@ -80,6 +80,8 @@ class HashedSort : public SortStrategy { vector partition_key_ids; //! The PARTITION BY key types vector partition_key_types; + //! Whether two partition keys differ, over [keys..., other keys...] + unique_ptr partition_key_mismatch; //! The number of PARTITION BY keys idx_t partition_key_count = 0; //! Whether single-key hash groups can skip sorting diff --git a/src/duckdb/src/include/duckdb/common/sorting/partition_key_tracker.hpp b/src/duckdb/src/include/duckdb/common/sorting/partition_key_tracker.hpp index 401ff2840..b57c43e14 100644 --- a/src/duckdb/src/include/duckdb/common/sorting/partition_key_tracker.hpp +++ b/src/duckdb/src/include/duckdb/common/sorting/partition_key_tracker.hpp @@ -10,12 +10,14 @@ #include "duckdb/common/types/data_chunk.hpp" #include "duckdb/common/types/row/partitioned_tuple_data.hpp" +#include "duckdb/execution/expression_executor.hpp" namespace duckdb { class PartitionKeyTracker { public: - PartitionKeyTracker(Allocator &allocator, const vector &key_types); + PartitionKeyTracker(Context &context, Allocator &allocator, const vector &key_types, + const Expression &key_mismatch); void Reset(idx_t radix_bits); bool CanBypass(idx_t hash_bin) const; @@ -32,14 +34,15 @@ class PartitionKeyTracker { template idx_t BuildCandidates(DataChunk &keys, Vector &input_hashes, PartitionedTupleDataAppendState &append_state, idx_t count); - idx_t CompactCandidates(idx_t candidate_count); void CompareCandidates(DataChunk &keys, idx_t candidate_count); void CombineBin(const PartitionKeyTracker &source, idx_t bin_idx, idx_t &candidate_count); - idx_t CompactTrackerCandidates(idx_t candidate_count); void CompareTrackerCandidates(const PartitionKeyTracker &source, idx_t candidate_count); private: idx_t key_count; + //! Whether the keys differ, over [keys..., representatives...] + ExpressionExecutor key_mismatch; + DataChunk compare_keys; idx_t radix_bits = 0; unsafe_vector states; unsafe_vector hashes; diff --git a/src/duckdb/src/include/duckdb/common/sorting/sort.hpp b/src/duckdb/src/include/duckdb/common/sorting/sort.hpp index e7a21ad69..cc5171c44 100644 --- a/src/duckdb/src/include/duckdb/common/sorting/sort.hpp +++ b/src/duckdb/src/include/duckdb/common/sorting/sort.hpp @@ -85,6 +85,8 @@ class Sort { const ProgressData source_progress) const; //! The number of tuples that have been sorted so far idx_t GetSortedCount(GlobalSinkState &gstate) const; + //! The memory that sorting the tuples sunk into a local state requires + idx_t GetLocalSizeInBytes(LocalSinkState &lstate) const; //! Sink progress of a sort: half of the effort is sinking, half is sorting the sunk tuples static ProgressData GetSinkProgress(const ProgressData &source_progress, idx_t sorted_count, idx_t sunk_count, MonotonicProgress &monotonic_progress); diff --git a/src/duckdb/src/include/duckdb/common/string_util.hpp b/src/duckdb/src/include/duckdb/common/string_util.hpp index bbdc9fd84..ef283fa9e 100644 --- a/src/duckdb/src/include/duckdb/common/string_util.hpp +++ b/src/duckdb/src/include/duckdb/common/string_util.hpp @@ -389,5 +389,7 @@ class StringUtil { const char *enum_name, uint32_t enum_value); DUCKDB_API static const uint8_t ASCII_TO_LOWER_MAP[]; DUCKDB_API static const uint8_t ASCII_TO_UPPER_MAP[]; + + static string TruncateUTF8TOByteLength(const char *data, idx_t length, idx_t max_bytes); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/tree_renderer.hpp b/src/duckdb/src/include/duckdb/common/tree_renderer.hpp index 72f565bbb..56e62764c 100644 --- a/src/duckdb/src/include/duckdb/common/tree_renderer.hpp +++ b/src/duckdb/src/include/duckdb/common/tree_renderer.hpp @@ -52,10 +52,13 @@ class TreeRenderer { //! to print (the default renderer writes straight to the output stream), so it is never created for the //! string-producing paths. Formats can override this to provide a highlighting-aware sink. virtual unique_ptr GetPrintRenderer(); - //! Create a renderer for the given format, consulting the pluggable registry and configuring built-ins from the - //! client's "profiling_renderer_settings". Matched case-insensitively; throws if unknown, nullptr for "no_output". + //! Create a renderer for the given format, consulting the pluggable registry, and configure it from the client's + //! "profiling_renderer_settings". Matched case-insensitively; throws if unknown, nullptr for "no_output". static unique_ptr CreateRenderer(ClientContext &context, const string &name); static unique_ptr CreateRenderer(ClientContext &context, const ProfilerPrintFormat &format); + //! As above, but configures the renderer from the given renderer settings + static unique_ptr CreateRenderer(ClientContext &context, const string &name, + const unordered_map &settings); //! Create a built-in renderer without configuring it or consulting the registry (no ClientContext available) static unique_ptr CreateRenderer(const string &name); diff --git a/src/duckdb/src/include/duckdb/common/types.hpp b/src/duckdb/src/include/duckdb/common/types.hpp index ae14f4e14..5b5d6246f 100644 --- a/src/duckdb/src/include/duckdb/common/types.hpp +++ b/src/duckdb/src/include/duckdb/common/types.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/constants.hpp" +#include "duckdb/common/buffer_ptr.hpp" #include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/identifier.hpp" #include "duckdb/common/vector.hpp" @@ -33,8 +34,6 @@ struct string_t; // NOLINT: mimic std casing template using child_list_t = vector>; -template -using buffer_ptr = shared_ptr; template struct VectorStructType; @@ -45,11 +44,6 @@ struct VectorListType; //! Marker type selecting the VARIANT specialization of VectorIterator (see variant_iterator.hpp) struct VectorVariantType; -template -buffer_ptr make_buffer(ARGS &&...args) { // NOLINT: mimic std casing - return make_shared_ptr(std::forward(args)...); -} - struct list_entry_t { // NOLINT: mimic std casing list_entry_t() = default; list_entry_t(uint64_t offset, uint64_t length) : offset(offset), length(length) { @@ -247,6 +241,7 @@ enum class LogicalTypeId : uint8_t { UUID = 54, GEOMETRY = 60, + GEOGRAPHY = 61, STRUCT = 100, LIST = 101, @@ -511,9 +506,16 @@ struct LogicalType { DUCKDB_API bool IsValid() const; DUCKDB_API bool IsComplete() const; DUCKDB_API bool IsTemplated() const; + //! True, if a vector can hold the type: it has a physical type and child types, as do its children + DUCKDB_API bool HasPhysicalType() const; //! True, if this type supports in-place updates. bool SupportsRegularUpdate() const; + //! Whether two values of this type that compare equal are the same value, so that a function of them agrees and + //! either can stand for both. Not for types whose equal values can differ: FLOAT / DOUBLE (0.0 and -0.0), + //! INTERVAL (1 month and 30 days), a VARCHAR with a collation, VARIANT (an integer stored at two widths), nor + //! for a nested type over one of them. Types this is not known for count as such, too. + DUCKDB_API bool EqualValuesAreIdentical() const; private: //! Takes over a reference to "type_info" @@ -589,6 +591,9 @@ struct LogicalType { DUCKDB_API static LogicalType GEOMETRY(); // NOLINT DUCKDB_API static LogicalType GEOMETRY(const string &crs); DUCKDB_API static LogicalType GEOMETRY(const CoordinateReferenceSystem &crs); + DUCKDB_API static LogicalType GEOGRAPHY(); // NOLINT + DUCKDB_API static LogicalType GEOGRAPHY(const string &crs); + DUCKDB_API static LogicalType GEOGRAPHY(const CoordinateReferenceSystem &crs); // ANY but with special rules (default is LogicalType::ANY, 5) DUCKDB_API static LogicalType ANY_PARAMS(LogicalType target, idx_t cast_score = 5); // NOLINT DUCKDB_API static LogicalType TEMPLATE(const string &name); // NOLINT diff --git a/src/duckdb/src/include/duckdb/common/types/bignum.hpp b/src/duckdb/src/include/duckdb/common/types/bignum.hpp index 5cfba415c..b7b9d4141 100644 --- a/src/duckdb/src/include/duckdb/common/types/bignum.hpp +++ b/src/duckdb/src/include/duckdb/common/types/bignum.hpp @@ -95,6 +95,8 @@ class Bignum { DUCKDB_API static string FromByteArray(uint8_t *data, idx_t size, bool is_negative); //! Function to convert BIGNUM blob to a VARCHAR, a long conversion checks for interrupts through the context DUCKDB_API static string BignumToVarchar(const bignum_t &blob, optional_ptr context = nullptr); + //! Writes decimal text using reusable conversion buffers + DUCKDB_API static void BignumToVarchar(BignumCastScratch &state, const bignum_t &blob, string &result); //! Writes the decimal representation of a BIGNUM into the string heap of the result vector DUCKDB_API static string_t BignumToVarchar(const bignum_t &blob, Vector &result, BignumCastScratch &scratch); //! The BIGNUM -> VARCHAR cast function @@ -223,6 +225,11 @@ struct HugeintCastToBignum { } }; +template <> +DUCKDB_API bignum_t HugeintCastToBignum::Operation(hugeint_t input, StringHeap &heap); +template <> +DUCKDB_API bignum_t HugeintCastToBignum::Operation(uhugeint_t input, StringHeap &heap); + struct TryCastToBignum { template static inline bool Operation(SRC input, DST &result, Vector &result_vector, CastParameters ¶meters) { diff --git a/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp b/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp index 4b5780b87..f9bad23ca 100644 --- a/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp +++ b/src/duckdb/src/include/duckdb/common/types/bignum_decimal.hpp @@ -10,14 +10,17 @@ #include "duckdb/common/bignum.hpp" #include "duckdb/common/common.hpp" +#include "duckdb/common/optional_idx.hpp" #include "duckdb/common/types/decimal.hpp" #include "duckdb/common/types/hugeint.hpp" +#include "duckdb/common/types/string_heap.hpp" namespace duckdb { class ClientContext; class Context; class StringHeap; class Vector; +struct BignumCastScratch; //! The operations on the unscaled value of a DECIMAL wider than 38 digits, a bignum_t (the BIGNUM blob): the interface //! of the fixed-size tiers (see decimal_helper.hpp), whose results are owned blobs here as the values have no fixed @@ -37,6 +40,25 @@ struct DecimalHelper { BignumArithmeticState state; }; + //! Scratch reused across rescaled values. + struct RescaleState { + explicit RescaleState(optional_ptr context = nullptr) : arithmetic(context) { + } + + //! Invalidates scratch values; call before constructing the next input in heap. + void Reset() { + heap.GetAllocator().Reset(); + } + const string &GetPowerOfTen(idx_t exponent); + + StringHeap heap; + BignumArithmeticState arithmetic; + + private: + optional_idx cached_exponent; + string cached_power; + }; + //! 10^exponent as a BIGNUM blob, the powers of everyday widths are cached; a long computation checks for //! interrupts through the context, as do the other conversions below DUCKDB_API static string PowerOfTen(idx_t exponent, optional_ptr context = nullptr); @@ -58,6 +80,8 @@ struct DecimalHelper { //! The BIGNUM blob of an integer DUCKDB_API static string FromInteger(hugeint_t value); DUCKDB_API static string FromInteger(uhugeint_t value); + DUCKDB_API static void FromInteger(hugeint_t value, string &result); + DUCKDB_API static void FromInteger(uhugeint_t value, string &result); //! Converts an unscaled value to a hugeint, returns false if it does not fit DUCKDB_API static bool TryToHugeint(const bignum_t &value, hugeint_t &result); DUCKDB_API static bool TryToUhugeint(const bignum_t &value, uhugeint_t &result); @@ -84,6 +108,12 @@ struct DecimalHelper { //! rescaled value DUCKDB_API static string Rescale(const bignum_t &value, uint32_t source_scale, uint32_t target_scale, optional_ptr context = nullptr); + //! The result borrows from value or state; consume it before resetting state or releasing value. + DUCKDB_API static bignum_t Rescale(RescaleState &state, const bignum_t &value, uint32_t source_scale, + uint32_t target_scale); + //! Fixed-width inputs use integer arithmetic before encoding the result as a BIGNUM. + DUCKDB_API static bignum_t Rescale(RescaleState &state, hugeint_t value, uint32_t source_scale, + uint32_t target_scale); //! Rescales an unscaled value to target_scale (rounding half away from zero) and checks it fits target_width, the //! result is the BIGNUM blob of the rescaled value DUCKDB_API static bool TryRescale(const bignum_t &value, uint32_t source_scale, uint32_t target_width, @@ -96,6 +126,10 @@ struct DecimalHelper { optional_ptr context = nullptr); DUCKDB_API static bool TryToFloating(const bignum_t &value, uint32_t scale, double &result, optional_ptr context = nullptr); + DUCKDB_API static bool TryToFloating(BignumCastScratch &state, string &text, const bignum_t &value, uint32_t scale, + float &result); + DUCKDB_API static bool TryToFloating(BignumCastScratch &state, string &text, const bignum_t &value, uint32_t scale, + double &result); //! Converts an unscaled value with the given scale to a double, infinite when the value is out of range DUCKDB_API static double ToDouble(const bignum_t &value, uint32_t scale, optional_ptr context = nullptr); diff --git a/src/duckdb/src/include/duckdb/common/types/cast_helpers.hpp b/src/duckdb/src/include/duckdb/common/types/cast_helpers.hpp index 1c07ebf93..27525537a 100644 --- a/src/duckdb/src/include/duckdb/common/types/cast_helpers.hpp +++ b/src/duckdb/src/include/duckdb/common/types/cast_helpers.hpp @@ -79,6 +79,9 @@ class NumericHelper { return result; } + //! Formats value, including its sign, in reverse and returns a pointer to the beginning + static char *FormatSigned(hugeint_t value, char *ptr); + template static std::string ToString(T value) { return std::to_string(value); @@ -98,6 +101,8 @@ int NumericHelper::UnsignedLength(hugeint_t value); template <> char *NumericHelper::FormatUnsigned(hugeint_t value, char *ptr); +template <> +char *NumericHelper::FormatUnsigned(uhugeint_t value, char *ptr); template <> std::string NumericHelper::ToString(hugeint_t value); @@ -182,15 +187,7 @@ template <> void DecimalToString::FormatDecimal(hugeint_t value, uint32_t width, uint32_t scale, char *dst, idx_t len); struct UhugeintToStringCast { - static string_t Format(uhugeint_t value, StringHeap &heap) { - std::string str = value.ToString(); - string_t result = heap.EmptyString(str.length()); - auto data = result.GetDataWriteable(); - - memcpy(data, str.data(), str.length()); // NOLINT: null-termination not required - result.Finalize(); - return result; - } + static string_t Format(uhugeint_t value, StringHeap &heap); }; struct DateToStringCast { diff --git a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp index 843b93d0e..95a4144d7 100644 --- a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp +++ b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp @@ -208,7 +208,7 @@ class ColumnDataCollection { private: //! The Column Data Allocator - buffer_ptr allocator; + shared_ptr allocator; //! The types of the stored entries vector types; //! The number of entries stored in the column data collection diff --git a/src/duckdb/src/include/duckdb/common/types/date_lookup_cache.hpp b/src/duckdb/src/include/duckdb/common/types/date_lookup_cache.hpp index 8c713f330..ee831a0a9 100644 --- a/src/duckdb/src/include/duckdb/common/types/date_lookup_cache.hpp +++ b/src/duckdb/src/include/duckdb/common/types/date_lookup_cache.hpp @@ -23,8 +23,10 @@ class DateLookupCache { constexpr static int32_t CACHE_MAX_DATE = 29584; // 2050-12-31 public: - DateLookupCache() { - BuildCache(); + //! Returns the cache, which is built on first use + static const DateLookupCache &Get() { + static const DateLookupCache cache; + return cache; } //! Extracts the component, or returns nullopt if the date is infinite @@ -42,13 +44,16 @@ class DateLookupCache { } private: + DateLookupCache() { + BuildCache(); + } + static idx_t GetDateCacheEntry(date_t day) { return UnsafeNumericCast(day.days - DateLookupCache::CACHE_MIN_DATE); } void BuildCache() { D_ASSERT(CACHE_MAX_DATE > CACHE_MIN_DATE); - cache = make_unsafe_uniq_array_uninitialized(CACHE_MAX_DATE - CACHE_MIN_DATE); for (int32_t d = CACHE_MIN_DATE; d < CACHE_MAX_DATE; d++) { date_t date(d); auto cache_entry = OP::template Operation(date); @@ -57,7 +62,8 @@ class DateLookupCache { } private: - unsafe_unique_array cache; + //! A plain array keeps the static trivially destructible + CACHE_TYPE cache[CACHE_MAX_DATE - CACHE_MIN_DATE]; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/types/geometry.hpp b/src/duckdb/src/include/duckdb/common/types/geometry.hpp index 20c8d3cf4..eeee15fb9 100644 --- a/src/duckdb/src/include/duckdb/common/types/geometry.hpp +++ b/src/duckdb/src/include/duckdb/common/types/geometry.hpp @@ -34,6 +34,14 @@ enum class GeometryType : uint8_t { enum class VertexType : uint8_t { XY = 0, XYZ = 1, XYM = 2, XYZM = 3 }; +//! How coordinates are interpreted when computing and comparing extents +enum class GeometryModel : uint8_t { + //! Exact vertex min/max on a plane (GEOMETRY) + PLANAR = 0, + //! Coverage extent on the sphere, with an antimeridian-aware longitude axis (GEOGRAPHY) + GEODETIC = 1, +}; + struct VertexXY { static constexpr auto TYPE = VertexType::XY; static constexpr auto HAS_Z = false; @@ -153,39 +161,121 @@ class GeometryExtent { return std::isfinite(m_min) && std::isfinite(m_max); } - void Extend(const VertexXY &vertex) { - ExtendAxis(x_min, x_max, vertex.x); + // NOTE: planar (GEOMETRY) extents are exact vertex min/max. Geodetic (GEOGRAPHY) extents are + // *coverage* extents: Geometry::GetExtent additionally bounds the geodesic edges between the + // vertices (great-circle arcs bulge poleward beyond their endpoints) and the polygon interiors + // under the interior-on-the-left rule (S2's convention): a shell winding east around the globe + // encloses the north pole, one winding west the south pole, a shell that is counterclockwise on + // the sphere encloses its bounded side, and a clockwise one encloses the complement - covering + // (almost) the whole globe, so ESRI-style clockwise shells get full-globe extents. Orientation is + // decided on the sphere, not in planar lon/lat. This follows the precedent of other spherical + // engines that write coverage bounds into Parquet geospatial statistics; the bounds are wider than + // the Parquet spec's coordinate-based bbox definition, which is safe for any reader. + // + // The orientation rule is a convention, not a standard. The Parquet GEOGRAPHY spec says nothing + // about ring orientation, OGC Simple Features only describes it for planar polygons, and + // GeoParquet's optional `orientation` metadata only RECOMMENDS counterclockwise shells for + // spherical edges, noting that readers otherwise typically take the smaller of the two regions. + // BigQuery also takes the smaller region by default, and applies interior-on-the-left only with + // `oriented => TRUE`. Under the smaller-region reading, a shell whose left side is larger than a + // hemisphere (e.g. a ring along 30S winding east) has the other side as its interior, which these + // extents do not cover. GEOGRAPHY predicates must therefore use the same rule as the extents. + + // GeometryModel::GEODETIC enables antimeridian-aware longitude (X axis) math used by GEOGRAPHY: + // the X axis is treated as a circular [-180,180] degree axis where an arc may wrap (x_min > x_max), + // meaning the longitude range is [x_min, 180] u [-180, x_max]. The Y axis is never wrapped. + // GeometryModel::PLANAR is exact min/max, as used by GEOMETRY. + // + // The antimeridian seam is the only point identity the geodetic math models: +180 and -180 are + // treated as the same longitude. The poles are NOT identified - at y = +/-90 every longitude is + // physically the same point, but e.g. POINT(0 90) and POINT(90 90) still have disjoint coordinate + // extents (consistent with the coordinate-extent contract above). A geometric predicate that + // understands pole identity must account for this itself for pole-touching data. + + void Extend(const VertexXY &vertex, GeometryModel model = GeometryModel::PLANAR) { + ExtendX(vertex.x, model); ExtendAxis(y_min, y_max, vertex.y); } - void Extend(const VertexXYZ &vertex) { - ExtendAxis(x_min, x_max, vertex.x); + void Extend(const VertexXYZ &vertex, GeometryModel model = GeometryModel::PLANAR) { + ExtendX(vertex.x, model); ExtendAxis(y_min, y_max, vertex.y); ExtendAxis(z_min, z_max, vertex.z); } - void Extend(const VertexXYM &vertex) { - ExtendAxis(x_min, x_max, vertex.x); + void Extend(const VertexXYM &vertex, GeometryModel model = GeometryModel::PLANAR) { + ExtendX(vertex.x, model); ExtendAxis(y_min, y_max, vertex.y); ExtendAxis(m_min, m_max, vertex.m); } - void Extend(const VertexXYZM &vertex) { - ExtendAxis(x_min, x_max, vertex.x); + void Extend(const VertexXYZM &vertex, GeometryModel model = GeometryModel::PLANAR) { + ExtendX(vertex.x, model); ExtendAxis(y_min, y_max, vertex.y); ExtendAxis(z_min, z_max, vertex.z); ExtendAxis(m_min, m_max, vertex.m); } - void Merge(const GeometryExtent &other) { - MergeAxis(x_min, x_max, other.x_min, other.x_max); + // Extend the geodetic X (longitude) axis to cover the eastward arc from lo to hi + void ExtendXArc(double lo, double hi) { + if (!LonInRange(lo) || !LonInRange(hi)) { + // NaN or out-of-contract longitudes make the whole axis unknown, as in ExtendX + x_min = UNKNOWN_MIN; + x_max = UNKNOWN_MAX; + return; + } + if (!std::isfinite(x_min) || !std::isfinite(x_max)) { + if (x_min == EMPTY_MIN) { + x_min = lo; + x_max = hi; + } + // Otherwise the X axis is unknown; keep it unknown. + return; + } + LonArcMerge(x_min, x_max, lo, hi, x_min, x_max); + } + + void Merge(const GeometryExtent &other, GeometryModel model = GeometryModel::PLANAR) { MergeAxis(y_min, y_max, other.y_min, other.y_max); MergeAxis(z_min, z_max, other.z_min, other.z_max); MergeAxis(m_min, m_max, other.m_min, other.m_max); + + // Only the X axis is special-cased for geodetic merging, and only when both arcs are finite. + // A non-finite axis is "empty" or "unknown" and MergeAxis correctly propagates both. + const bool both_finite = + std::isfinite(x_min) && std::isfinite(x_max) && std::isfinite(other.x_min) && std::isfinite(other.x_max); + if (model == GeometryModel::GEODETIC && both_finite) { + if (LonInRange(x_min) && LonInRange(x_max) && LonInRange(other.x_min) && LonInRange(other.x_max)) { + LonArcMerge(x_min, x_max, other.x_min, other.x_max, x_min, x_max); + } else { + // Out-of-contract longitudes (only possible for data that bypassed validation): the arc + // math is undefined for them, so degrade to unknown rather than risk an under-covering arc. + x_min = UNKNOWN_MIN; + x_max = UNKNOWN_MAX; + } + } else { + MergeAxis(x_min, x_max, other.x_min, other.x_max); + } } - bool IntersectsXY(const GeometryExtent &other) const { - return !(x_min > other.x_max || x_max < other.x_min || y_min > other.y_max || y_max < other.y_min); + bool IntersectsXY(const GeometryExtent &other, GeometryModel model = GeometryModel::PLANAR) const { + if (y_min > other.y_max || y_max < other.y_min) { + return false; + } + const bool both_finite = + std::isfinite(x_min) && std::isfinite(x_max) && std::isfinite(other.x_min) && std::isfinite(other.x_max); + if (model == GeometryModel::GEODETIC && both_finite) { + if (!LonInRange(x_min) || !LonInRange(x_max) || !LonInRange(other.x_min) || !LonInRange(other.x_max)) { + // Out-of-contract longitudes: cannot decide, err on the side of intersecting. + return true; + } + // Widened by LON_EPSILON: a false "no intersection" here prunes rows, so round toward "intersects". + return LonArcContains(x_min, x_max, other.x_min, LON_EPSILON) || + LonArcContains(other.x_min, other.x_max, x_min, LON_EPSILON); + } + // Plain (and the non-finite empty/unknown cases): the inequalities handle +/- inf and NaN + // conservatively (any NaN comparison is false, so NaN yields "intersects"). + return !(x_min > other.x_max || x_max < other.x_min); } bool IntersectsXYZM(const GeometryExtent &other) const { @@ -193,11 +283,59 @@ class GeometryExtent { z_min > other.z_max || z_max < other.z_min || m_min > other.m_max || m_max < other.m_min); } - bool ContainsXY(const GeometryExtent &other) const { - return x_min <= other.x_min && x_max >= other.x_max && y_min <= other.y_min && y_max >= other.y_max; + bool ContainsXY(const GeometryExtent &other, GeometryModel model = GeometryModel::PLANAR) const { + if (!(y_min <= other.y_min && y_max >= other.y_max)) { + return false; + } + const bool both_finite = + std::isfinite(x_min) && std::isfinite(x_max) && std::isfinite(other.x_min) && std::isfinite(other.x_max); + if (model == GeometryModel::GEODETIC && both_finite) { + if (!LonInRange(x_min) || !LonInRange(x_max) || !LonInRange(other.x_min) || !LonInRange(other.x_max)) { + // Out-of-contract longitudes: cannot decide, err on the side of not containing. + return false; + } + // Narrowed by LON_EPSILON: a false "contains" can elide a filter entirely, so round toward + // "does not contain". + return LonArcContainsArc(x_min, x_max, other.x_min, other.x_max, -LON_EPSILON); + } + return x_min <= other.x_min && x_max >= other.x_max; + } + + // The X axis as a plain numeric [min, max] range over the raw coordinate values, e.g. for numeric + // statistics of the extracted X ordinate. A geodetic arc is widened to the full range when it wraps + // or touches the seam (a coordinate of either sign may be stored for the same longitude), and is + // otherwise padded by LON_EPSILON to cover coordinates the rounded arc math absorbed. + void GetNumericXRange(GeometryModel model, double &out_min, double &out_max) const { + out_min = x_min; + out_max = x_max; + if (model != GeometryModel::GEODETIC || !HasX()) { + return; + } + if (x_min > x_max || x_min == -180.0 || x_max == 180.0) { + out_min = -180.0; + out_max = 180.0; + return; + } + out_min = MaxValue(x_min - LON_EPSILON, -180.0); + out_max = MinValue(x_max + LON_EPSILON, 180.0); } private: + // The X axis of a geodetic extent is an eastward arc on the longitude circle: it covers the + // longitudes traveled going east from x_min to x_max, so x_min > x_max means the arc crosses + // the antimeridian. [-180, 180] is the canonical full-circle arc, and +180/-180 denote the same + // physical longitude. Arc endpoints are always actual input coordinates (or +/-180 for the full + // circle) and are never synthesized with arithmetic. The containment tests still round at ~1 ulp + // of 360 degrees, so a merge can absorb a coordinate up to that far beyond an endpoint without + // widening the arc: the public predicates guard this with LON_EPSILON in the safe direction, and + // GetNumericXRange pads by it. + static constexpr double LON_EPSILON = 1e-9; // ~0.1mm of longitude at the equator + + // Is this longitude within the canonical [-180, 180] range the arc math requires? + static bool LonInRange(double x) { + return x >= -180.0 && x <= 180.0; + } + //! A NaN coordinate cannot be placed on the axis, so it makes the range of the axis unknown static void ExtendAxis(double &min, double &max, double value) { if (std::isnan(value)) { @@ -219,6 +357,94 @@ class GeometryExtent { max = MaxValue(max, other_max); } + // Canonicalize the antimeridian seam: +180 and -180 are the same longitude. + static double LonCanon(double x) { + return x == 180.0 ? -180.0 : x; + } + + // Eastward angular distance (degrees) from a to b, in [0, 360). Inputs finite, in [-180, 180]. + static double LonEastDist(double a, double b) { + double d = LonCanon(b) - LonCanon(a); + if (d < 0.0) { + d += 360.0; + } + return d; + } + + // Eastward width of the arc [lo, hi], in [0, 360]. Only the full circle [-180, 180] has width 360. + static double LonArcWidth(double lo, double hi) { + if (lo == -180.0 && hi == 180.0) { + return 360.0; + } + return LonEastDist(lo, hi); + } + + // Does the arc [lo, hi] contain the longitude p, with the given slack (may be negative)? + static bool LonArcContains(double lo, double hi, double p, double slack = 0.0) { + return LonEastDist(lo, p) <= LonArcWidth(lo, hi) + slack; + } + + // Does the outer arc fully contain the inner arc, with the given slack (may be negative)? + static bool LonArcContainsArc(double olo, double ohi, double ilo, double ihi, double slack = 0.0) { + const double ow = LonArcWidth(olo, ohi); + if (ow >= 360.0) { + return true; + } + const double off = LonEastDist(olo, ilo); + return off <= ow + slack && off + LonArcWidth(ilo, ihi) <= ow + slack; + } + + // Merge two arcs into a covering arc, writing the result to out_lo/out_hi (which may alias the + // inputs). The narrowest covering arc starts at one arc's start and ends at one arc's end: try + // those four candidates with their exact endpoint values and keep the narrowest one that covers + // both inputs. If none does (the arcs jointly cover the whole circle), the result is the full circle. + static void LonArcMerge(double also, double ahi, double blo, double bhi, double &out_lo, double &out_hi) { + const double cand_lo[4] = {also, also, blo, blo}; + const double cand_hi[4] = {ahi, bhi, ahi, bhi}; + double best_lo = -180.0; + double best_hi = 180.0; + double best_width = 360.0; + for (idx_t i = 0; i < 4; i++) { + if (!LonArcContainsArc(cand_lo[i], cand_hi[i], also, ahi) || + !LonArcContainsArc(cand_lo[i], cand_hi[i], blo, bhi)) { + continue; + } + const double width = LonArcWidth(cand_lo[i], cand_hi[i]); + if (width < best_width) { + best_width = width; + best_lo = cand_lo[i]; + best_hi = cand_hi[i]; + } + } + out_lo = best_lo; + out_hi = best_hi; + } + + // Extend the X (longitude) axis to include x. For geodetic this uses circular arc math. + void ExtendX(double x, GeometryModel model) { + if (model == GeometryModel::PLANAR) { + ExtendAxis(x_min, x_max, x); + return; + } + if (std::isnan(x) || !LonInRange(x)) { + // A NaN or out-of-contract longitude (only possible for data that bypassed validation) + // makes the whole axis unknown. + x_min = UNKNOWN_MIN; + x_max = UNKNOWN_MAX; + return; + } + if (!std::isfinite(x_min) || !std::isfinite(x_max)) { + if (x_min == EMPTY_MIN) { + // First vertex into an empty extent. + x_min = x; + x_max = x; + } + // Otherwise the X axis is "unknown" (infinite); keep it unknown. + return; + } + LonArcMerge(x_min, x_max, x, x, x_min, x_max); + } + public: double x_min; double y_min; @@ -273,6 +499,8 @@ class Geometry { public: static constexpr idx_t MAX_RECURSION_DEPTH = 16; static constexpr StorageVersion VERSION_ADDED = StorageVersion::V1_5_0; // Added to core in DuckDB v1.5.0 + //! GEOGRAPHY shares the WKB representation, but was only added to core in DuckDB v2.1.0 + static constexpr StorageVersion GEOGRAPHY_VERSION_ADDED = StorageVersion::V2_1_0; //! Check for legayc geometry type (pre v1.5) static bool IsSpatialGeometryType(const LogicalType &type); @@ -300,9 +528,19 @@ class Geometry { //! Get the geometry type and vertex type from the WKB DUCKDB_API static pair GetType(const string_t &wkb); + //! The geometry model used for statistics and extent predicates of the given GEOMETRY or GEOGRAPHY type + static GeometryModel GetModel(const LogicalType &type) { + return type.id() == LogicalTypeId::GEOGRAPHY ? GeometryModel::GEODETIC : GeometryModel::PLANAR; + } + //! Update the bounding box, return number of vertices processed - DUCKDB_API static uint32_t GetExtent(const string_t &wkb, GeometryExtent &extent); - DUCKDB_API static uint32_t GetExtent(const string_t &wkb, GeometryExtent &extent, bool &has_any_empty); + DUCKDB_API static uint32_t GetExtent(const string_t &wkb, GeometryExtent &extent, + GeometryModel model = GeometryModel::PLANAR); + DUCKDB_API static uint32_t GetExtent(const string_t &wkb, GeometryExtent &extent, bool &has_any_empty, + GeometryModel model = GeometryModel::PLANAR); + //! Whether the geometry's coordinates lie within the canonical GEOGRAPHY ranges + //! (X in [-180, 180], Y in [-90, 90]). Empty geometries are always valid. + DUCKDB_API static bool IsValidGeography(const string_t &wkb); //! Convert to vectorized format DUCKDB_API static void ToVectorizedFormat(const Vector &source, Vector &target, idx_t count, GeometryType geom_type, diff --git a/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp b/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp index bc5eefdc5..f9858a33a 100644 --- a/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp +++ b/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp @@ -138,6 +138,10 @@ class PartitionedTupleData { idx_t Count() const; //! Get the size (in bytes) of this PartitionedTupleData idx_t SizeInBytes() const; + //! Materialized row and heap bytes, excluding allocation overhead + idx_t GetDataSize() const { + return data_size; + } //! Buffer-manager memory charged for row and heap blocks, plus allocator metadata idx_t GetAllocatedSizeInBytes() const; //! Get the number of partitions of this PartitionedTupleData diff --git a/src/duckdb/src/include/duckdb/common/types/selection_vector.hpp b/src/duckdb/src/include/duckdb/common/types/selection_vector.hpp index cc5bac4cb..e980c3308 100644 --- a/src/duckdb/src/include/duckdb/common/types/selection_vector.hpp +++ b/src/duckdb/src/include/duckdb/common/types/selection_vector.hpp @@ -22,11 +22,6 @@ class VectorBuffer; struct SelectionData { DUCKDB_API explicit SelectionData(idx_t count); - // Out-of-line destructor: prevents GCC IPA-ICF from folding - // _Sp_counted_ptr_inplace::_M_dispose with the - // corresponding instantiation for TemplatedValidityData, which produces - // a spurious -Warray-bounds with g++ >= 14. - DUCKDB_API ~SelectionData(); AllocatedData owned_data; }; @@ -104,7 +99,7 @@ struct SelectionVector { capacity = capacity_p; } void Initialize(idx_t count = STANDARD_VECTOR_SIZE) { - selection_data = make_shared_ptr(count); + selection_data = make_buffer(count); sel_vector = reinterpret_cast(selection_data->owned_data.get()); capacity = count; } diff --git a/src/duckdb/src/include/duckdb/common/types/value.hpp b/src/duckdb/src/include/duckdb/common/types/value.hpp index 22b8b0e08..ae0929ce8 100644 --- a/src/duckdb/src/include/duckdb/common/types/value.hpp +++ b/src/duckdb/src/include/duckdb/common/types/value.hpp @@ -224,6 +224,8 @@ class Value { DUCKDB_API static Value GEOMETRY(const_data_ptr_t data, idx_t len); DUCKDB_API static Value GEOMETRY(const_data_ptr_t data, idx_t len, const CoordinateReferenceSystem &crs); + DUCKDB_API static Value GEOGRAPHY(const_data_ptr_t data, idx_t len); + DUCKDB_API static Value GEOGRAPHY(const_data_ptr_t data, idx_t len, const CoordinateReferenceSystem &crs); DUCKDB_API static Value TYPE(const LogicalType &type); DUCKDB_API static Value TYPE(const string_t &serialized_type); diff --git a/src/duckdb/src/include/duckdb/common/types/variant.hpp b/src/duckdb/src/include/duckdb/common/types/variant.hpp index bc323ec88..c83672df7 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant.hpp @@ -161,6 +161,7 @@ enum class VariantLogicalType : uint8_t { BITSTRING = 32, GEOMETRY = 33, TIMESTAMP_NANOS_TZ = 34, + GEOGRAPHY = 35, ENUM_SIZE /* always kept as last item of the enum */ }; diff --git a/src/duckdb/src/include/duckdb/common/types/variant/variant_builder.hpp b/src/duckdb/src/include/duckdb/common/types/variant/variant_builder.hpp index 20e1bda9e..62bdb2088 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant/variant_builder.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant/variant_builder.hpp @@ -333,6 +333,7 @@ struct VariantBuilder { case LogicalTypeId::BIGNUM: case LogicalTypeId::BIT: case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: case LogicalTypeId::VARCHAR: { if (type_id == LogicalTypeId::BLOB) { variant_type = VariantLogicalType::BLOB; @@ -342,6 +343,8 @@ struct VariantBuilder { variant_type = VariantLogicalType::BITSTRING; } else if (type_id == LogicalTypeId::GEOMETRY) { variant_type = VariantLogicalType::GEOMETRY; + } else if (type_id == LogicalTypeId::GEOGRAPHY) { + variant_type = VariantLogicalType::GEOGRAPHY; } else { variant_type = VariantLogicalType::VARCHAR; } @@ -475,7 +478,8 @@ struct VariantBuilder { case VariantLogicalType::BLOB: case VariantLogicalType::BIGNUM: case VariantLogicalType::BITSTRING: - case VariantLogicalType::GEOMETRY: { + case VariantLogicalType::GEOMETRY: + case VariantLogicalType::GEOGRAPHY: { auto str = it.GetString(); VariantBuilderAppendVarint(blob, NumericCast(str.GetSize())); VariantBuilderAppendBytes(blob, const_data_ptr_cast(str.GetData()), str.GetSize()); diff --git a/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp b/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp index 4012d3184..fda067822 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp @@ -31,6 +31,7 @@ enum class VariantComparisonType : uint8_t { TIME_TZ, // TIME WITH TIME ZONE INTERVAL, GEOMETRY, + GEOGRAPHY, BITSTRING, ARRAY, OBJECT, diff --git a/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp b/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp index 73e3a01cc..76b17c47a 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp @@ -92,6 +92,7 @@ class VariantVisitor { case VariantLogicalType::BITSTRING: case VariantLogicalType::BIGNUM: case VariantLogicalType::GEOMETRY: + case VariantLogicalType::GEOGRAPHY: return VisitString(type_id, variant, row, values_idx, std::forward(args)...); case VariantLogicalType::DECIMAL: return VisitDecimal(variant, row, values_idx, std::forward(args)...); @@ -179,6 +180,7 @@ class VariantVisitor { case VariantLogicalType::BITSTRING: case VariantLogicalType::BIGNUM: case VariantLogicalType::GEOMETRY: + case VariantLogicalType::GEOGRAPHY: return VisitString(type_id, node.GetString(), std::forward(args)...); case VariantLogicalType::DECIMAL: return VisitDecimal(node, std::forward(args)...); @@ -318,6 +320,9 @@ class VariantVisitor { if (type_id == VariantLogicalType::GEOMETRY) { return Visitor::VisitGeometry(decoded_string, std::forward(args)...); } + if (type_id == VariantLogicalType::GEOGRAPHY) { + return Visitor::VisitGeography(decoded_string, std::forward(args)...); + } if (type_id == VariantLogicalType::BITSTRING) { return Visitor::VisitBitstring(decoded_string, std::forward(args)...); } @@ -338,6 +343,9 @@ class VariantVisitor { if (type_id == VariantLogicalType::GEOMETRY) { return Visitor::VisitGeometry(value, std::forward(args)...); } + if (type_id == VariantLogicalType::GEOGRAPHY) { + return Visitor::VisitGeography(value, std::forward(args)...); + } if (type_id == VariantLogicalType::BITSTRING) { return Visitor::VisitBitstring(value, std::forward(args)...); } diff --git a/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp b/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp index fb00ab727..c81dbeeca 100644 --- a/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp +++ b/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp @@ -83,7 +83,7 @@ class VectorBufferHolder : public AuxiliaryDataHolder { }; //! The VectorBuffer is a class used by the vector to hold its data -class VectorBuffer : public enable_shared_from_this { +class VectorBuffer : public enable_buffer_from_this { public: explicit VectorBuffer(VectorType vector_type, VectorBufferType type, count_t count_p) : vector_type(vector_type), buffer_type(type), v_size(count_p) { diff --git a/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp b/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp index 9968ba4fb..cc3f48c5b 100644 --- a/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp @@ -72,6 +72,8 @@ class VirtualFileSystem : public FileSystem { vector ListSubSystems() override; FileSystem &GetDefaultFileSystem(); + //! The local file system: the default file system if it is local, otherwise one owned by this VirtualFileSystem + FileSystem &GetLocalFileSystem(); std::string GetName() const override; @@ -116,6 +118,8 @@ class VirtualFileSystem : public FileSystem { bool for_writing); private: + //! Only set if the default file system is not local + unique_ptr owned_local_file_system; mutex registry_lock; shared_ptr file_system_registry; vector> unregistered_file_systems; diff --git a/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp b/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp index 0cee0f02a..d2a485fc5 100644 --- a/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp +++ b/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp @@ -163,6 +163,8 @@ class GroupedAggregateHashTable : public BaseAggregateHashTable { idx_t GetRadixBits() const; //! Get the total number of tuples materialized currently in this HT idx_t GetMaterializedCount() const; + //! Materialized row and heap bytes, including rows awaiting partitioning + idx_t GetMaterializedSize() const; //! Read-only adaptivity observations; mutations follow the HT's lifecycle. const AggregateHTAdaptivityState &GetAdaptivityState() const { return adaptivity; @@ -291,8 +293,10 @@ class GroupedAggregateHashTable : public BaseAggregateHashTable { optional_ptr source_rows = nullptr); void InitializeLookupState(AggregateHTLookupState &lookup_state) const; - //! Verify the pointer table of the HT + //! Verify the whole pointer table of the HT: a scan of every entry, so only run where the table is rebuilt void Verify(); + //! Verify the entries of the rows of a chunk after FindOrCreateGroups + void VerifyEntries(const Vector &group_hashes, const Vector &addresses, idx_t count); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/executor.hpp b/src/duckdb/src/include/duckdb/execution/executor.hpp index e743bda9c..e0503c743 100644 --- a/src/duckdb/src/include/duckdb/execution/executor.hpp +++ b/src/duckdb/src/include/duckdb/execution/executor.hpp @@ -157,9 +157,10 @@ class Executor { idx_t PartialChunkCount(); void InitializeInternal(PhysicalOperator &physical_plan); - void ScheduleEvents(const vector> &meta_pipelines, - unique_ptr resolved_schedule = nullptr); + //! Create the events of the pipelines and collect the ones without dependencies, which start the schedule void ScheduleEventsInternal(ScheduleEventData &event_data); + //! Schedule the events without dependencies: this creates tasks, so the caller must not hold executor_lock + static void ScheduleReadyEvents(const vector> &ready_events); static void VerifyScheduledEvents(const vector> &events); static void VerifyScheduledEventsInternal(const idx_t i, const vector> &vertices, diff --git a/src/duckdb/src/include/duckdb/execution/expression_executor.hpp b/src/duckdb/src/include/duckdb/execution/expression_executor.hpp index 94a464d72..d01a74f10 100644 --- a/src/duckdb/src/include/duckdb/execution/expression_executor.hpp +++ b/src/duckdb/src/include/duckdb/execution/expression_executor.hpp @@ -81,11 +81,11 @@ class ExpressionExecutor { DUCKDB_API idx_t SelectExpression(DataChunk &input, SelectionVector &sel); DUCKDB_API idx_t SelectExpression(DataChunk &input, SelectionVector &result_sel, - optional_ptr current_sel, idx_t current_count); + optional_ptr current_sel, idx_t current_count); DUCKDB_API idx_t SelectExpression(DataChunk &input, optional_ptr true_sel, optional_ptr false_sel, - optional_ptr current_sel, idx_t current_count); + optional_ptr current_sel, idx_t current_count); //! Execute the expression with index `expr_idx` and store the result in the result vector DUCKDB_API void ExecuteExpression(idx_t expr_idx, Vector &result); diff --git a/src/duckdb/src/include/duckdb/execution/ht_entry.hpp b/src/duckdb/src/include/duckdb/execution/ht_entry.hpp index 69e159da1..6fd0f626c 100644 --- a/src/duckdb/src/include/duckdb/execution/ht_entry.hpp +++ b/src/duckdb/src/include/duckdb/execution/ht_entry.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/assert.hpp" +#include "duckdb/common/prefetch.hpp" #include "duckdb/common/typedefs.hpp" namespace duckdb { @@ -99,12 +100,8 @@ struct ht_entry_t { // NOLINT //! Prefetch a future bucket, evaluating its address only within the loop bounds. template inline void PrefetchHashTableEntry(idx_t row_idx, idx_t row_count, GET_ENTRY get_entry) { -#if defined(__GNUC__) || defined(__clang__) constexpr idx_t PREFETCH_DISTANCE = 64; - if (row_idx + PREFETCH_DISTANCE < row_count) { - __builtin_prefetch(get_entry(row_idx + PREFETCH_DISTANCE), 0, 3); - } -#endif + Prefetch(row_idx, row_count, PREFETCH_DISTANCE, get_entry); } // uses an AND operation to apply the modulo operation instead of an if condition that could be branch mispredicted diff --git a/src/duckdb/src/include/duckdb/execution/index/art/prefix.hpp b/src/duckdb/src/include/duckdb/execution/index/art/prefix.hpp index ed65a1279..97eef7976 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/prefix.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/prefix.hpp @@ -13,8 +13,6 @@ namespace duckdb { -class ARTKey; - //! Prefix is a wrapper class to access a prefix. //! The prefix contains up to the ART's prefix size bytes and an additional byte for the count. //! It also contains a child NodePtr. @@ -41,9 +39,6 @@ class Prefix { static uint8_t GetByte(const ART &art, const NodePtr &node_ptr, const uint8_t pos); public: - //! Get a new list of prefix nodes. The node reference holds the child of the last prefix node. - static void New(ART &art, reference &node_ptr_ref, const ARTKey &key, const idx_t depth, idx_t count); - //! Removes up to pos bytes from the prefix. //! Shifts all subsequent bytes by pos. Frees empty nodes. static void Reduce(ART &art, NodePtr &node_ptr, const idx_t pos); diff --git a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp index 90aefed24..049417003 100644 --- a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp +++ b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp @@ -22,6 +22,8 @@ #include "duckdb/common/vector/dictionary_vector.hpp" #include "duckdb/execution/aggregate_hashtable.hpp" #include "duckdb/execution/ht_entry.hpp" +#include "duckdb/execution/perfect_hash_join_table.hpp" +#include "duckdb/parallel/sharded_counter.hpp" #include "duckdb/planner/filter/table_filter_functions.hpp" #include "duckdb/planner/joinside.hpp" @@ -34,7 +36,6 @@ struct ColumnDataAppendState; struct ClientConfig; struct ResidualPredicateInfo; class PhysicalHashJoin; -class PerfectHashJoinTable; //! Each producer has its own refcounts; emitted vectors retain the original dictionaries through these owners. class DictionaryOwnershipCache { @@ -45,6 +46,13 @@ class DictionaryOwnershipCache { const buffer_ptr &GetEntry(idx_t column, const buffer_ptr &entry); void Reset(); + SelectionVector &GetNullSelection(idx_t count) { + if (null_selection.Capacity() < count) { + null_selection.Initialize(count); + } + return null_selection; + } + private: struct DictionaryOwner { explicit DictionaryOwner(const buffer_ptr &entry) : entry(entry) { @@ -56,6 +64,7 @@ class DictionaryOwnershipCache { const idx_t column_count; //! Allocated once on first use; resetting owners does not invalidate references to these slots. unique_array> entries; + SelectionVector null_selection; }; struct JoinHTScanState { @@ -92,7 +101,7 @@ struct JoinHTScanState { The pointers are either NULL Two-phase lifecycle: the constructor populates only layout-INDEPENDENT state; all layout-DEPENDENT state - (layout_ptr, row matchers, tuple_size/pointer_offset/entry_size, data_collection, sink_collection, dead_end, + (layout_ptr, row matchers, tuple_size/pointer_offset, data_collection, sink_collection, dict_info) is published by FinishInitWithLayout on the first build chunk, so slot widths (and the dictionary a narrowed slot indexes into) can be chosen from the data's actual runtime encoding. Until then the JHT is unusable except for the null-safe Count() / SizeInBytes() accessors; the layout-dependent accessors assert @@ -142,6 +151,8 @@ struct DictSurvivingInfo { static LogicalType IndexType(uint8_t index_width); }; +struct JoinBuildSelection; + class JoinHashTable { public: using ValidityBytes = TemplatedValidityMask; @@ -253,10 +264,7 @@ class JoinHashTable { public: void AdvancePointers(); void AdvancePointers(const SelectionVector &sel, idx_t sel_count); - void GatherResult(Vector &result, const SelectionVector &result_vector, const SelectionVector &sel_vector, - const idx_t count, const idx_t col_idx); void GatherResult(Vector &result, const SelectionVector &sel_vector, const idx_t count, const idx_t col_idx); - void GatherResult(Vector &result, const idx_t count, const idx_t col_idx); idx_t ResolvePredicates(DataChunk &keys, DataChunk &probe_data, SelectionVector &match_sel, optional_ptr no_match_sel); }; @@ -265,8 +273,6 @@ class JoinHashTable { struct SharedState { SharedState(); - Vector salt_v; - SelectionVector keys_to_compare_sel; SelectionVector keys_no_match_sel; }; @@ -277,17 +283,14 @@ class JoinHashTable { //! The current dictionary vector id (if any) string dictionary_id; - DataChunk unique_values; - TupleDataChunkState unique_key_state; - Vector new_dictionary_pointers; - SelectionVector unique_entries; - //! Per-slot head-of-chain pointer cache; nullptr marks a miss - unique_ptr dictionary_pointers; + //! Row pointers, membership bits or one-based dictionary positions; zero marks a miss. + unsafe_unique_array dictionary_results; unsafe_unique_array found_entry; idx_t capacity = 0; - SelectionVector match_sel; //! Number of dict slots already resolved; the unique-entries walk is skipped once it reaches dict_size idx_t resolved_count = 0; + DataChunk unique_values; + SelectionVector unique_entries; }; struct ProbeState : SharedState { @@ -296,13 +299,15 @@ class JoinHashTable { Vector hashes; Vector ht_offsets_and_salts_v; Vector hashes_dense_v; - SelectionVector non_empty_sel; + unique_ptr spill_hashes; + SelectionVector spill_false_sel; //! Allocated only when the operator gates the compressed-probe paths on; null otherwise unique_ptr dict_state; }; struct InsertState : SharedState { explicit InsertState(const JoinHashTable &ht); + Vector salt_v; /// Because of the index hick up SelectionVector remaining_sel; SelectionVector key_match_sel; @@ -382,29 +387,7 @@ class JoinHashTable { static idx_t FillWithHTOffsets(JoinHTScanState &state, Vector &addresses); //! Materialize RHS dictionaries after all finalize tasks complete. - void BuildDictionaryArrays(const PhysicalHashJoin &op); - //! Emit RHS dictionaries using build-row positions. - void EmitDictVectors(const SelectionVector &build_sel, idx_t count, DataChunk &result, idx_t rhs_col_offset, - DictionaryOwnershipCache &dictionary_state) const; - //! Emit RHS dictionaries using selected row pointers. - void EmitDictVectors(const data_ptr_t *row_ptrs, const SelectionVector &ptr_sel, idx_t count, DataChunk &result, - idx_t rhs_col_offset, DictionaryOwnershipCache &dictionary_state) const; - //! Emit RHS output columns for matched rows row_ptrs[ptr_sel[0..count)] into result starting at - //! result column rhs_col_offset; routes through EmitDictVectors when use_dict_emission is active. - void GatherRHS(Vector &row_ptrs, const SelectionVector &ptr_sel, const idx_t count, DataChunk &result, - idx_t rhs_col_offset, DictionaryOwnershipCache &dictionary_state) const; - //! Follow the chain pointer; when USE_DICT_EMISSION, resolves via aux_next_ptrs - template - inline data_ptr_t GetNextPointer(data_ptr_t row_ptr) const { - if (USE_DICT_EMISSION) { - if (!chains_longer_than_one.load(std::memory_order_relaxed)) { - // aux_next_ptrs is unallocated in this case - return nullptr; - } - return aux_next_ptrs_data[Load(row_ptr + pointer_offset)]; - } - return cast_uint64_to_pointer(Load(row_ptr + pointer_offset)); - } + void BuildDictionaryArrays(const PhysicalHashJoin &op, idx_t reservation_size); idx_t Count() const { return data_collection ? data_collection->Count() : 0; @@ -438,8 +421,8 @@ class JoinHashTable { //! Choose direct lookup from the completed in-memory build. bool TryInitializePerfectHashTable(); - //! Whether lookup produces row pointers for compressed-probe fan-out. - bool SupportsCompressedProbe() const; + + idx_t GetTotalProbeMatches() const; ClientContext &context; const PhysicalOperator &op; @@ -482,8 +465,6 @@ class JoinHashTable { //! Number of hash entries, direct-directory slots or bitmap words to initialize. idx_t capacity = DConstants::INVALID_INDEX; - //! The size of an entry as stored in the HashTable - idx_t entry_size; //! The total tuple size idx_t tuple_size; //! Next pointer offset in tuple, also used for the position of the hash, which then gets overwritten by the pointer @@ -502,8 +483,6 @@ class JoinHashTable { bool single_join_error_on_multiple_rows = true; //! Whether or not to perform deduplication based on join_keys when building ht bool insert_duplicate_keys = true; - //! Number of probe matches, isolated from immutable probe metadata. - PaddedAtomic total_probe_matches {0}; //! Residual predicate to evaluate during probing optional_ptr residual_predicate; //! Residual predicate mapping info @@ -511,22 +490,12 @@ class JoinHashTable { //! Mapping from lhs_output_columns positions to lhs_probe_data positions vector lhs_output_in_probe; - //! True once BuildDictionaryArrays has embedded dictionary indices into NEXT_PTR - bool use_dict_emission = false; - //! Pre-materialized columnar data, one entry per RHS output column - vector> dict_arrays; - //! Dict-surviving descriptor shared with every other per-thread JHT of the same join; set by - //! FinishInitWithLayout, nullptr when no build payload column is narrowed + //! Dict-surviving descriptor shared with every per-thread table of the same join. shared_ptr dict_info; - //! Saved NEXT_PTR values, indexed by dict index; only allocated when chains_longer_than_one - AllocatedData aux_next_ptrs; - //! Typed pointer into aux_next_ptrs; set by BuildDictionaryArrays alongside the allocation - data_ptr_t *aux_next_ptrs_data = nullptr; - //! Total bytes the dict_arrays allocation would cost for the given RHS output types - idx_t ComputeBuildPayloadBytes(const vector &rhs_output_types) const; - //! Returns true iff small-build-side dictionary emission should activate - bool CanUseDictionaryEmission(const PhysicalHashJoin &op, bool external, idx_t probe_cardinality) const; + //! Peak allocation estimate, or zero when materialized dictionary emission is unsuitable. + idx_t GetDictionaryReservationSize(const PhysicalHashJoin &op, bool external, idx_t probe_cardinality) const; + idx_t GetMaterializedDictionarySize() const; struct { mutex mj_lock; @@ -550,6 +519,25 @@ class JoinHashTable { } mark_join_info; private: + //! Emit RHS dictionaries using build-row positions. + void EmitDictVectors(const SelectionVector &build_sel, idx_t count, DataChunk &result, idx_t rhs_col_offset, + DictionaryOwnershipCache &dictionary_state) const; + //! Emit RHS dictionaries using selected row pointers. + void EmitDictVectors(const data_ptr_t *row_ptrs, const JoinBuildSelection &selection, DataChunk &result, + idx_t rhs_col_offset, DictionaryOwnershipCache &dictionary_state) const; + //! Emit RHS output columns for matched rows row_ptrs[ptr_sel[0..count)] into result starting at + //! result column rhs_col_offset, preserving prepared or surviving dictionaries where possible. + void GatherRHS(Vector &row_ptrs, const SelectionVector &ptr_sel, const idx_t count, DataChunk &result, + idx_t rhs_col_offset, DictionaryOwnershipCache &dictionary_state) const; + void GatherRHS(Vector &row_ptrs, const JoinBuildSelection &selection, DataChunk &result, idx_t rhs_col_offset, + DictionaryOwnershipCache &dictionary_state) const; + //! Advance selected equality chains, compacting the surviving probe positions. + idx_t AdvancePointers(Vector &pointers, SelectionVector &out_sel, const SelectionVector &sel, idx_t count) const; + //! Mark selected build rows after all join predicates have matched. + void MarkMatchedRows(Vector &pointers, const SelectionVector &sel, idx_t count) const; + //! Mark every build row in the selected equality groups. + void MarkMatchedChains(Vector &pointers, const SelectionVector &sel, idx_t count) const; + void InitializeScanStructure(ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, optional_ptr ¤t_sel); void Hash(DataChunk &keys, const SelectionVector &sel, idx_t count, Vector &hashes); @@ -565,6 +553,12 @@ class JoinHashTable { //! Constant-vector variant of Probe. Returns false if the LHS keys are not a constant vector. bool TryProbeConstant(ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, ProbeState &probe_state); + PerfectHashJoinTable::Type GetProbeResultType() const; + void ResolveProbeKeys(ScanStructure &scan, DataChunk &keys, ProbeState &state, array_ptr results, + const SelectionVector &result_sel); + template + void ExpandProbeResults(ScanStructure &scan, DataChunk &keys, TupleDataChunkState &key_state, + array_ptr results, const SelectionVector &result_sel); bool UseSalt() const; @@ -589,6 +583,28 @@ class JoinHashTable { return reinterpret_cast *>(hash_map.get()); } + void InitializeMatchFlags(const Vector &rows) const; + atomic &GetMatchFlag(data_ptr_t row) const; + idx_t SelectBuildMatches(array_ptr rows, idx_t &offset, array_ptr result, + bool matched) const; + + template + data_ptr_t GetNextPointer(data_ptr_t row) const; + template + idx_t AdvancePointers(Vector &pointers, SelectionVector &out_sel, const SelectionVector &sel, idx_t count) const; + template + void MarkMatchedChains(Vector &pointers, const SelectionVector &sel, idx_t count) const; + + struct MaterializedDictionary { + vector> columns; + //! Original chain links, indexed by the dictionary position embedded in each row. + AllocatedData next_pointers; + }; + unique_ptr materialized_dictionary; + + //! Number of matches from completed probe chunks. + ShardedCounter probe_matches; + //! Lock for combining data_collection when merging HTs mutex data_lock; //! Partitioned data collection that the data is sunk into when building @@ -607,24 +623,17 @@ class JoinHashTable { idx_t bucket_shift = 0; //! Whether or not NULL values are considered equal in each of the comparisons vector null_values_are_equal; - //! An empty tuple that's a "dead end", can be used to stop chains early - unsafe_unique_array dead_end; - //! Bloom filter over the join keys. An external join fills it during Sink, an in-memory join during - //! finalize. Shared by every thread-local hash table of this operator, and shared again with any scan it - //! gets published to, so it outlives a reset of this table - shared_ptr bloom_filter; + //! Bloom filters indexed by equality key. External joins fill them during Sink, in-memory joins during + //! finalize. Shared with thread-local hash tables and published scans, so they can outlive a table reset. + vector> bloom_filters; + //! Which key filters finalize should build from the materialized build side. + vector should_build_bloom_filters; //! Unpublished filter kept from a previous recursive iteration so finalize can reuse its allocation. - //! Only ever set on the global hash table, never on the thread-local ones that share bloom_filter + //! Used only by the global hash table of a single-key join. shared_ptr recycled_bloom_filter; - //! Whether finalize should build the bloom filter from the materialized build side - bool should_build_bloom_filter = false; - - //! Per-key-column bloom filters of a join with several equality keys - vector> key_bloom_filters; - vector should_build_key_bloom_filters; - //! Per-column bitmap budget after sharing memory with the other runtime filters. - idx_t key_bloom_filter_budget = NumericLimits::Maximum(); + //! Per-column bitmap budget for multi-key joins, shared with the other runtime filters. + idx_t bloom_filter_budget = NumericLimits::Maximum(); //! Prefix-range filters, indexed by key column vector> prefix_range_filters; @@ -707,35 +716,45 @@ class JoinHashTable { return PointerTableCapacity(count) * sizeof(data_ptr_t); } - void SetBloomFilter(shared_ptr filter) { - bloom_filter = std::move(filter); + void SetBloomFilter(idx_t key_idx, shared_ptr filter) { + D_ASSERT(key_idx < equality_predicate_columns.size()); + bloom_filters.resize(equality_predicate_columns.size()); + bloom_filters[key_idx] = std::move(filter); } //! Whether the join has one equality key, so the hash table hashes are that key's hashes bool HasSingleEqualityKey() const { return equality_predicate_columns.size() == 1; } + //! Creates the per-key-column bloom filters that an external join with several equality keys fills during + //! Sink. They split the memory budget between them + void InitializeBloomFilters(const vector &key_idxs, idx_t build_estimate, idx_t memory_budget); + void SetBloomFilters(vector> filters) { +#ifdef DEBUG + for (auto &filter : filters) { + D_ASSERT(!filter || !filter->IsSealed()); + } +#endif + bloom_filters = std::move(filters); + } + const vector> &GetBloomFilters() const { + return bloom_filters; + } //! Requests a finalize-built bloom filter for a key column (in-memory joins only) void SetBuildBloomFilter(idx_t key_idx); - void SetKeyBloomFilterBudget(idx_t bytes) { - key_bloom_filter_budget = bytes; + void SetBloomFilterBudget(idx_t bytes) { + bloom_filter_budget = bytes; } - shared_ptr GetBloomFilter() { - return bloom_filter; - } - shared_ptr GetBloomFilter(idx_t key_idx); + shared_ptr GetBloomFilter(idx_t key_idx) const; //! Hands an unpublished filter from a previous recursive iteration to the finalize-built filter path void SetRecycledBloomFilter(shared_ptr filter) { // a null argument would drop a parked filter; callers must only hand over live, unpublished filters D_ASSERT(filter && !filter->IsPublished()); recycled_bloom_filter = std::move(filter); } - //! Marks the bloom filter complete. The reference stays, because the thread-local tables hold it too - void SealBloomFilter(); + //! Marks all bloom filters complete, retaining references shared with thread-local tables. + void SealBloomFilters(); //! Whether the filter is complete and rejects enough for pushing it into a scan to pay off - bool HasPublishableBloomFilter() const { - return bloom_filter && bloom_filter->IsSealed() && bloom_filter->IsUseful(); - } bool HasPublishableBloomFilter(idx_t key_idx) const; void SetPrefixRangeFilter(idx_t key_idx, unique_ptr filter) { @@ -762,11 +781,16 @@ class JoinHashTable { idx_t GetPrefixRangeBuildStateSize() const; void MergePrefixRangeBuildState(PrefixRangeBuildStates &states); - //! Get total size of HT if all partitions would be built + void MergePerfectHashBounds(const vector> &local_hts); + enum class LookupSizing { SELECTED, HASH_ONLY }; + //! Cost the whole build using the selected lookup representation. idx_t GetTotalSize(const vector> &local_hts, idx_t &max_partition_size, - idx_t &max_partition_count) const; + idx_t &max_partition_count, LookupSizing lookup_sizing = LookupSizing::SELECTED) const; + //! External partitions always use ordinary hashing. idx_t GetTotalSize(const vector &partition_sizes, const vector &partition_counts, idx_t &max_partition_size, idx_t &max_partition_count) const; + //! Dictionaries retained outside spillable tuple storage. + idx_t GetRetainedDictionarySize() const; //! Get the remaining size of the unbuilt partitions idx_t GetRemainingSize() const; //! Sets number of radix bits according to the max ht size @@ -816,9 +840,14 @@ class JoinHashTable { //! pinned upstream dictionary, or the reserved NULL index for a NULL-only chunk (e.g. the unmatched-build scan of //! a FULL/RIGHT join upstream). Any other shape means the build pipeline is not single-source and throws. void EncodeDictSurvivingColumn(const DictSurvivingColumn &column, idx_t build_col_idx, const Vector &incoming, - idx_t count, vector &buffers, vector &vectors); + idx_t count, Vector &result); private: + //! Build is local to this table; its buffers are initialized on the first nonempty chunk. + struct BuildState; + BuildState &GetBuildState(); + unique_ptr build_state; + //! The current number of radix bits used to partition idx_t radix_bits; diff --git a/src/duckdb/src/include/duckdb/execution/merge_sort_tree.hpp b/src/duckdb/src/include/duckdb/execution/merge_sort_tree.hpp index 167f898ad..c171f54dd 100644 --- a/src/duckdb/src/include/duckdb/execution/merge_sort_tree.hpp +++ b/src/duckdb/src/include/duckdb/execution/merge_sort_tree.hpp @@ -365,7 +365,7 @@ void MergeSortTree::Build(ClientContext &context) { while (build_level.load() < tree.size()) { // A failed run never completes its level, so the waiting threads // leave through the interrupt that the executor raises for the failure - context.InterruptCheck(); + context.FastInterruptCheck(); idx_t level_idx; idx_t run_idx; if (TryNextRun(level_idx, run_idx)) { diff --git a/src/duckdb/src/include/duckdb/execution/nested_loop_join.hpp b/src/duckdb/src/include/duckdb/execution/nested_loop_join.hpp index 5924b6b15..b8f6463e3 100644 --- a/src/duckdb/src/include/duckdb/execution/nested_loop_join.hpp +++ b/src/duckdb/src/include/duckdb/execution/nested_loop_join.hpp @@ -24,6 +24,9 @@ struct NestedLoopJoinInner { struct NestedLoopJoinMark { static void Perform(DataChunk &left, ColumnDataCollection &right, bool found_match[], const vector &conditions, optional_ptr found_unknown = nullptr); + //! Marks the rows of `left` that a row of `right` matches + static void Perform(const Vector &left, const Vector &right, idx_t left_count, idx_t right_count, + bool found_match[], ExpressionType comparison); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/operator/aggregate/aggregate_object.hpp b/src/duckdb/src/include/duckdb/execution/operator/aggregate/aggregate_object.hpp index b8b50d1ae..7122b8e3a 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/aggregate/aggregate_object.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/aggregate/aggregate_object.hpp @@ -17,20 +17,21 @@ class BoundAggregateExpression; class BoundWindowExpression; struct FunctionDataWrapper { - explicit FunctionDataWrapper(unique_ptr function_data_p) : function_data(std::move(function_data_p)) { + explicit FunctionDataWrapper(cow_ptr function_data_p) : function_data(std::move(function_data_p)) { } - unique_ptr function_data; + cow_ptr function_data; }; struct AggregateObject { // NOLINT: work-around bug in clang-tidy - AggregateObject(BoundAggregateFunction function, FunctionData *bind_data, idx_t child_count, idx_t payload_size, - AggregateType aggr_type, PhysicalType return_type, optional_ptr filter = nullptr); + AggregateObject(BoundAggregateFunction function, optional_ptr bind_data, idx_t child_count, + idx_t payload_size, AggregateType aggr_type, PhysicalType return_type, + optional_ptr filter = nullptr); explicit AggregateObject(BoundAggregateExpression &aggr); explicit AggregateObject(BoundAggregateExpression *aggr); explicit AggregateObject(const BoundWindowExpression &window); - FunctionData *GetFunctionData() const { + optional_ptr GetFunctionData() const { return bind_data_wrapper ? bind_data_wrapper->function_data.get() : nullptr; } @@ -63,6 +64,8 @@ struct AggregateFilterData { SelectionVector true_sel; //! The number of rows selected by the last Select idx_t selected_count = 0; + //! Whether the last Select selected every row of the chunk: the payload is then used as it is + bool all_selected = false; //! The non-distinct aggregates that use this filter unsafe_vector aggregates; //! The payload columns (the children of those aggregates) that ApplyFilter slices diff --git a/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_streaming_window.hpp b/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_streaming_window.hpp index 1cad1ec35..57002e696 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_streaming_window.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_streaming_window.hpp @@ -1,7 +1,7 @@ //===----------------------------------------------------------------------===// // DuckDB // -// duckdb/execution/operator/aggregate/physical_window.hpp +// duckdb/execution/operator/aggregate/physical_streaming_window.hpp // // //===----------------------------------------------------------------------===// @@ -24,12 +24,16 @@ class PhysicalStreamingWindow : public PhysicalOperator { public: PhysicalStreamingWindow(PhysicalPlan &physical_plan, vector types, vector> select_list, idx_t estimated_cardinality, - PhysicalOperatorType type = PhysicalOperatorType::STREAMING_WINDOW); + optional_idx partition_limit = optional_idx()); //! The projection list of the WINDOW statement vector> select_list; + //! The partition size limit (if any) + optional_idx partition_limit; public: + PipelineSourceConsumption GetSourceConsumption() const override; + unique_ptr GetGlobalOperatorState(ClientContext &context) const override; OperatorResultType Execute(ExecutionContext &context, DataChunk &input, DataChunk &chunk, diff --git a/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_window.hpp b/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_window.hpp index e24f722d2..ab5ed7564 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_window.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_window.hpp @@ -20,10 +20,11 @@ class PhysicalWindow : public PhysicalOperator { static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::WINDOW; public: - PhysicalWindow(PhysicalPlan &physical_plan, vector types, vector> select_list, - idx_t estimated_cardinality, vector partitions); - PhysicalWindow(PhysicalPlan &physical_plan, vector types, vector> select_list, - idx_t estimated_cardinality); + PhysicalWindow(PhysicalPlan &physical_plan, ClientContext &context, vector types, + vector> select_list, idx_t estimated_cardinality, + vector partitions); + PhysicalWindow(PhysicalPlan &physical_plan, ClientContext &context, vector types, + vector> select_list, idx_t estimated_cardinality); //! The projection list of the WINDOW statement (may contain aggregates) vector> select_list; @@ -34,6 +35,10 @@ class PhysicalWindow : public PhysicalOperator { bool is_order_dependent; //! The partitions over which this is grouped (if any) OperatorPartitionInfo partition_info; + //! DISTINCT FROM comparison of the partition keys + unique_ptr partition_distinct_from; + //! DISTINCT FROM comparison of the order keys of every window expression, by the end of its order key prefix + unordered_map> order_distinct_from; public: // Source interface diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_option.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_option.hpp index cb19031dc..b35f81bd4 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_option.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_option.hpp @@ -57,11 +57,6 @@ struct CSVOption { // NOLINT: work-around bug in clang-tidy } } - // this is due to a hacky implementation in the read csv relation - void ChangeSetByUserTrue() { - set_by_user = true; - } - bool operator==(const CSVOption &other) const { return value == other.value; } diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp index 1592a2a21..27aabdac1 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp @@ -157,26 +157,20 @@ struct CSVReaderOptions { bool GetHeader() const; void SetHeader(bool has_header); - string GetEscape() const; void SetEscape(const string &escape); idx_t GetSkipRows() const; void SetSkipRows(int64_t rows); void SetQuote(const string "e); - string GetQuote() const; void SetComment(const string &comment); - string GetComment() const; void SetDelimiter(const string &delimiter); - string GetDelimiter() const; //! If we can safely ignore errors (i.e., they are being ignored and not being stored in a rejects table) bool IgnoreErrors() const; - string GetNewline() const; void SetNewline(const string &input); - bool GetRFC4180() const; void SetRFC4180(bool rfc4180); CSVOption GetSingleByteDelimiter() const; @@ -193,7 +187,6 @@ struct CSVReaderOptions { const vector &expected_names); void SetWriteOption(Context &context, const Identifier &loption, const Value &value); void SetDateFormat(LogicalTypeId type, const string &format, bool read_format); - void ToNamedParameters(named_parameter_map_t &out) const; void FromNamedParameters(const named_argument_map_t &in, ClientContext &context, MultiFileOptions &file_options); void ParseOption(ClientContext &context, const Identifier &key, const Value &val); //! Verify options are not conflicting diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp index 667f2c681..81da5a1c2 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp @@ -10,7 +10,10 @@ #include "duckdb/common/typedefs.hpp" #include "duckdb/common/file_system.hpp" +#include "duckdb/common/types/data_chunk.hpp" +#include "duckdb/execution/expression_executor.hpp" #include "duckdb/function/encoding_function.hpp" +#include "duckdb/planner/expression.hpp" #include "duckdb/main/client_context.hpp" namespace duckdb { @@ -65,13 +68,24 @@ class CSVEncoder { //! The actual encoded buffer CSVEncoderBuffer encoded_buffer; - //! Potential remaining bytes - CSVEncoderBuffer remaining_bytes_buffer; - //! Actual Encoding Function - optional_ptr encoding_function; + //! Decoded bytes that did not fit in the output buffer yet + string pending_decoded; + idx_t pending_pos = 0; + //! The streaming overload of the encoding's scalar function, executed on (encoded buffer, is_last) + unique_ptr decode_expression; + unique_ptr decode_executor; + DataChunk decode_input; + //! The maximum number of input bytes that make up one character + idx_t minimum_input_window = 1; //! Pass-on Byte, used to check if we are done with the file, but must be appended to next buffer char pass_on_byte; bool has_pass_on_byte = false; idx_t encoded_bytes_read = 0; + +private: + //! Decodes the encoded buffer into the output buffer until either one is exhausted + idx_t DecodeBuffer(char *output_buffer, idx_t output_pos, idx_t output_size); + //! Runs the encoding's scalar function over the input, returns the number of bytes consumed + idx_t Decode(const char *input, idx_t input_size, bool is_last, string &decoded); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/global_csv_state.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/global_csv_state.hpp index a40a9e4bd..5c22598c7 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/global_csv_state.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/global_csv_state.hpp @@ -48,7 +48,7 @@ struct CSVLocalState : public LocalTableFunctionState { struct CSVGlobalState : public GlobalTableFunctionState { public: CSVGlobalState(ClientContext &context_p, ReadCSVData &csv_data, const vector &column_names, - idx_t total_file_count, optional_ptr scan_op = nullptr); + idx_t file_count, optional_ptr scan_op = nullptr); ~CSVGlobalState() override { } @@ -72,10 +72,8 @@ struct CSVGlobalState : public GlobalTableFunctionState { //! Reference to the client context that created this scan ClientContext &context; ReadCSVData &csv_data; - //! The operator the files are scanned for, and how many files it scans - together they tell the rejects tables - //! which file of which scan an error belongs to + //! Identifies the scan that each file belongs to in the rejects tables optional_ptr scan_op; - idx_t total_file_count; //! The names of the columns that are read - used when filling the rejects table const vector &column_names; diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/string_value_scanner.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/string_value_scanner.hpp index 264df4437..fc695a1ae 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/string_value_scanner.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/string_value_scanner.hpp @@ -294,6 +294,8 @@ class StringValueResult : public ScannerResult { void NullPaddingQuotedNewlineCheck() const; //! Handles EmptyLine states static inline bool EmptyLine(StringValueResult &result, const idx_t buffer_pos); + //! Moves the start of the current line behind an empty line + void StartLineAfterEmptyLine(); inline bool AddRowInternal(); //! The bookkeeping of a value that is not projected inline void SkipValueInternal(); diff --git a/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp b/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp index 652e1e4d5..85c956722 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp @@ -24,6 +24,9 @@ class LogicalGet; class JoinHashTable; class PhysicalOperator; class PhysicalComparisonJoin; +class BloomFilter; +class Event; +class Pipeline; struct GlobalUngroupedAggregateState; struct LocalUngroupedAggregateState; @@ -65,6 +68,8 @@ struct JoinFilterPushdownColumn { enum class DeferredRuntimeFilterType : uint8_t { BLOOM_FILTER, PREFIX_RANGE }; +enum class InFilterMode { PRUNING_ONLY, ADAPTIVE_ROW_FILTERING }; + struct DeferredRuntimeFilterPushdown { DeferredRuntimeFilterType type = DeferredRuntimeFilterType::BLOOM_FILTER; const PhysicalOperator *op = nullptr; @@ -124,6 +129,15 @@ struct JoinFilterPushdownInfo { bool build_side_has_filter; public: + //! Bound replicated prefix-range build state independently of the radix partitions. + static constexpr idx_t MAX_PREFIX_RANGE_BUILD_MEMORY = 16ULL * 1024ULL * 1024ULL; + static idx_t GetMemoryBudget(ClientContext &context); + static void InitializeBloomFilters(ClientContext &context, const PhysicalComparisonJoin &op, JoinHashTable &ht, + shared_ptr recycled_filter = nullptr); + //! Complete optional read preparation before publishing filters and finalizing the hash table. + static void FinalizeRuntimeFilters(Pipeline &pipeline, Event &event, const PhysicalOperator &op, JoinHashTable &ht, + optional_ptr gstate, idx_t num_threads); + unique_ptr GetGlobalState(ClientContext &context, const PhysicalOperator &op) const; unique_ptr GetLocalState(JoinFilterGlobalState &gstate) const; @@ -143,7 +157,7 @@ struct JoinFilterPushdownInfo { bool PushInFilter(ClientContext &context, const JoinFilterPushdownFilter &info, const JoinFilterPushdownColumn &column, JoinHashTable &ht, const PhysicalOperator &op, - idx_t filter_idx, ProjectionIndex filter_col_idx) const; + idx_t filter_idx, ProjectionIndex filter_col_idx, InFilterMode mode) const; void DeferRuntimeFilter(DeferredRuntimeFilterType type, const PhysicalOperator &op, const JoinFilterPushdownFilter &info, const JoinFilterPushdownColumn &column, diff --git a/src/duckdb/src/include/duckdb/execution/operator/join/outer_join_marker.hpp b/src/duckdb/src/include/duckdb/execution/operator/join/outer_join_marker.hpp index 17de0f8cf..7c06efbda 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/join/outer_join_marker.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/join/outer_join_marker.hpp @@ -63,8 +63,9 @@ class OuterJoinMarker { //! Initialize a local scan void InitializeScan(OuterJoinGlobalScanState &gstate, OuterJoinLocalScanState &lstate); - //! Perform the scan - void Scan(OuterJoinGlobalScanState &gstate, OuterJoinLocalScanState &lstate, DataChunk &result); + //! Perform the scan: the rows without a match, or with `matched` the rows with one + void Scan(OuterJoinGlobalScanState &gstate, OuterJoinLocalScanState &lstate, DataChunk &result, + bool matched = false); //! Read-only matches vector const bool *GetMatches() const { diff --git a/src/duckdb/src/include/duckdb/execution/operator/join/physical_iejoin.hpp b/src/duckdb/src/include/duckdb/execution/operator/join/physical_iejoin.hpp index f9a3be837..b5fc48849 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/join/physical_iejoin.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/join/physical_iejoin.hpp @@ -20,11 +20,11 @@ class PhysicalIEJoin : public PhysicalRangeJoin { static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::IE_JOIN; public: - PhysicalIEJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, PhysicalOperator &left, - PhysicalOperator &right, vector cond, JoinType join_type, idx_t estimated_cardinality, - unique_ptr pushdown_info); - PhysicalIEJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, PhysicalOperator &left, - PhysicalOperator &right, vector cond, JoinType join_type, + PhysicalIEJoin(PhysicalPlan &physical_plan, ClientContext &context, LogicalComparisonJoin &op, + PhysicalOperator &left, PhysicalOperator &right, vector cond, JoinType join_type, + idx_t estimated_cardinality, unique_ptr pushdown_info); + PhysicalIEJoin(PhysicalPlan &physical_plan, ClientContext &context, LogicalComparisonJoin &op, + PhysicalOperator &left, PhysicalOperator &right, vector cond, JoinType join_type, idx_t estimated_cardinality); vector join_key_types; diff --git a/src/duckdb/src/include/duckdb/execution/operator/join/physical_nested_loop_join.hpp b/src/duckdb/src/include/duckdb/execution/operator/join/physical_nested_loop_join.hpp index 718b50c0a..57ef12115 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/join/physical_nested_loop_join.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/join/physical_nested_loop_join.hpp @@ -18,12 +18,13 @@ class PhysicalNestedLoopJoin : public PhysicalComparisonJoin { static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::NESTED_LOOP_JOIN; public: - PhysicalNestedLoopJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, PhysicalOperator &left, - PhysicalOperator &right, vector cond, JoinType join_type, - idx_t estimated_cardinality, unique_ptr pushdown_info); - PhysicalNestedLoopJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, PhysicalOperator &left, - PhysicalOperator &right, vector cond, JoinType join_type, - idx_t estimated_cardinality); + PhysicalNestedLoopJoin(PhysicalPlan &physical_plan, ClientContext &context, LogicalComparisonJoin &op, + PhysicalOperator &left, PhysicalOperator &right, vector cond, + JoinType join_type, idx_t estimated_cardinality, + unique_ptr pushdown_info); + PhysicalNestedLoopJoin(PhysicalPlan &physical_plan, ClientContext &context, LogicalComparisonJoin &op, + PhysicalOperator &left, PhysicalOperator &right, vector cond, + JoinType join_type, idx_t estimated_cardinality); public: // Operator Interface @@ -76,6 +77,9 @@ class PhysicalNestedLoopJoin : public PhysicalComparisonJoin { //! Returns a list of the types of the join conditions vector GetJoinTypes() const; + //! The condition "#0 #1" of SEMI/ANTI joins with a predicate (can be nullptr) + unique_ptr condition_comparison; + private: vector mark_projection_map; bool track_unknown; @@ -83,6 +87,8 @@ class PhysicalNestedLoopJoin : public PhysicalComparisonJoin { private: // resolve joins that output max N elements (SEMI, ANTI, MARK) void ResolveSimpleJoin(ExecutionContext &context, DataChunk &input, DataChunk &chunk, OperatorState &state) const; + // mark the build rows a probe chunk matches (RIGHT SEMI); the source phase emits them + void ResolveRightSemiJoin(ExecutionContext &context, DataChunk &input, OperatorState &state) const; // resolve joins that can potentially output N*M elements (INNER, LEFT, FULL) OperatorResultType ResolveComplexJoin(ExecutionContext &context, DataChunk &input, DataChunk &chunk, OperatorState &state) const; diff --git a/src/duckdb/src/include/duckdb/execution/operator/join/physical_piecewise_merge_join.hpp b/src/duckdb/src/include/duckdb/execution/operator/join/physical_piecewise_merge_join.hpp index f9cfb756a..32e132f56 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/join/physical_piecewise_merge_join.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/join/physical_piecewise_merge_join.hpp @@ -22,9 +22,10 @@ class PhysicalPiecewiseMergeJoin : public PhysicalRangeJoin { static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::PIECEWISE_MERGE_JOIN; public: - PhysicalPiecewiseMergeJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, PhysicalOperator &left, - PhysicalOperator &right, vector cond, JoinType join_type, - idx_t estimated_cardinality, unique_ptr pushdown_info); + PhysicalPiecewiseMergeJoin(PhysicalPlan &physical_plan, ClientContext &context, LogicalComparisonJoin &op, + PhysicalOperator &left, PhysicalOperator &right, vector cond, + JoinType join_type, idx_t estimated_cardinality, + unique_ptr pushdown_info); vector join_key_types; vector lhs_orders; @@ -78,6 +79,8 @@ class PhysicalPiecewiseMergeJoin : public PhysicalRangeJoin { private: // resolve joins that output max N elements (SEMI, ANTI, MARK) void ResolveSimpleJoin(ExecutionContext &context, DataChunk &input, DataChunk &chunk, OperatorState &state) const; + // find the build rows a probe chunk matches (RIGHT SEMI); the source phase emits them + void ResolveRightSemiJoin(ExecutionContext &context, DataChunk &input, OperatorState &state) const; // resolve joins that can potentially output N*M elements (INNER, LEFT, FULL) OperatorResultType ResolveComplexJoin(ExecutionContext &context, DataChunk &input, DataChunk &chunk, OperatorState &state) const; diff --git a/src/duckdb/src/include/duckdb/execution/operator/join/physical_range_join.hpp b/src/duckdb/src/include/duckdb/execution/operator/join/physical_range_join.hpp index bc37edaa6..f0d2c7ac5 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/join/physical_range_join.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/join/physical_range_join.hpp @@ -152,6 +152,8 @@ class PhysicalRangeJoin : public PhysicalComparisonJoin { //! The full set of types (left + right child) vector unprojected_types; + //! The conditions that are not sort keys, over [left tail keys..., right tail keys...] (can be nullptr) + unique_ptr tail_predicate; public: // Compare conditions for priority @@ -161,9 +163,11 @@ class PhysicalRangeJoin : public PhysicalComparisonJoin { static void SliceSortedPayload(DataChunk &chunk, GlobalSortedTable &table, ExternalBlockIteratorState &state, TupleDataChunkState &chunk_state, const idx_t chunk_idx, const unsafe_vector &result, SortedRunScanState &scan_state); - // Apply a tail condition to the current selection - static idx_t SelectJoinTail(const ExpressionType &condition, const Vector &left, const Vector &right, - const SelectionVector *sel, idx_t count, SelectionVector *true_sel); + //! The conjunction of the conditions from tail_begin on, over [left tail keys..., right tail keys...] + static unique_ptr CreateTailPredicate(ClientContext &context, const vector &conditions, + idx_t tail_begin); + //! The input types of CreateTailPredicate + static vector GetTailTypes(const vector &conditions, idx_t tail_begin); //! Utility to project full width internal chunks to projected results void ProjectResult(DataChunk &chunk, DataChunk &result) const; diff --git a/src/duckdb/src/include/duckdb/execution/operator/order/physical_top_n.hpp b/src/duckdb/src/include/duckdb/execution/operator/order/physical_top_n.hpp index c99b9ef4f..be4383088 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/order/physical_top_n.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/order/physical_top_n.hpp @@ -21,11 +21,14 @@ class PhysicalTopN : public PhysicalOperator { static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::TOP_N; public: - PhysicalTopN(PhysicalPlan &physical_plan, vector types, vector orders, idx_t limit, - idx_t offset, shared_ptr dynamic_filter, idx_t estimated_cardinality); + PhysicalTopN(PhysicalPlan &physical_plan, ClientContext &context, vector types, + vector orders, idx_t limit, idx_t offset, + shared_ptr dynamic_filter, idx_t estimated_cardinality); ~PhysicalTopN() override; vector orders; + //! NOT DISTINCT FROM comparison of the boundary value for every order column + vector> not_distinct_from; idx_t limit; idx_t offset; //! Dynamic table filter (if any) diff --git a/src/duckdb/src/include/duckdb/execution/operator/persistent/collection_merger.hpp b/src/duckdb/src/include/duckdb/execution/operator/persistent/collection_merger.hpp index 3de759426..272475458 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/persistent/collection_merger.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/persistent/collection_merger.hpp @@ -85,15 +85,16 @@ class CollectionMerger { } auto flushed_row_group_idx = result_collection.Append(scan_chunk, append_state); if (flushed_row_group_idx.IsValid()) { - writer.WriteNewRowGroup(optimistic_collection, flushed_row_group_idx.GetIndex()); + writer.WriteNewRowGroup(context.GetContext(), optimistic_collection, + flushed_row_group_idx.GetIndex()); } } data_table.ResetOptimisticCollection(context, collection_indexes[i]); } result_collection.FinalizeAppend(DuckTransaction::Get(context, data_table.db), append_state); - writer.WriteUnflushedRowGroups(optimistic_collection); + writer.WriteUnflushedRowGroups(context.GetContext(), optimistic_collection); } else if (batch_type == RowGroupBatchType::NOT_FLUSHED) { - writer.WriteUnflushedRowGroups(optimistic_collection); + writer.WriteUnflushedRowGroups(context.GetContext(), optimistic_collection); } collection_indexes.clear(); diff --git a/src/duckdb/src/include/duckdb/execution/operator/persistent/csv_rejects_table.hpp b/src/duckdb/src/include/duckdb/execution/operator/persistent/csv_rejects_table.hpp index daa7b961d..5311332d6 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/persistent/csv_rejects_table.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/persistent/csv_rejects_table.hpp @@ -14,13 +14,15 @@ #include "duckdb/common/shared_ptr.hpp" #include "duckdb/common/string.hpp" #include "duckdb/common/constants.hpp" -#include "duckdb/common/unordered_map.hpp" +#include "duckdb/common/reference_map.hpp" +#include "duckdb/common/vector.hpp" namespace duckdb { struct ReadCSVData; class TableCatalogEntry; class ClientContext; +class PhysicalOperator; class CSVRejectsTable : public ObjectCacheEntry { public: @@ -32,7 +34,7 @@ class CSVRejectsTable : public ObjectCacheEntry { mutex file_index_lock; idx_t file_index_query_id = DConstants::INVALID_INDEX; idx_t next_file_index = 0; - unordered_map scan_file_index_base; + reference_map_t> scan_file_indexes; string name; idx_t count; string scan_table; @@ -42,9 +44,8 @@ class CSVRejectsTable : public ObjectCacheEntry { const string &rejects_error); void InitializeTable(ClientContext &context, const ReadCSVData &options); - //! The first file index of a scan. The files of a scan get a block of indexes, so that they keep the order they - //! have in the scan, and the scans of a query do not report their files under the same indexes - idx_t GetFileIndexBase(idx_t query_id, const void *scan_key, idx_t file_count); + //! Allocate query-wide file indexes on demand, preserving file order within each scan + idx_t GetFileIndex(idx_t query_id, optional_ptr scan_op, idx_t file_index); TableCatalogEntry &GetErrorsTable(ClientContext &context); TableCatalogEntry &GetScansTable(ClientContext &context); diff --git a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_batch_copy_to_file.hpp b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_batch_copy_to_file.hpp index b6d47dbfe..d89b4c067 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_batch_copy_to_file.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_batch_copy_to_file.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/enums/copy_overwrite_mode.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/filename_pattern.hpp" #include "duckdb/execution/physical_operator.hpp" @@ -23,13 +24,13 @@ class PhysicalBatchCopyToFile : public PhysicalOperator { public: PhysicalBatchCopyToFile(PhysicalPlan &physical_plan, vector types, CopyFunction function, - unique_ptr bind_data, idx_t estimated_cardinality); + cow_ptr bind_data, idx_t estimated_cardinality); public: InsertionOrderPreservingMap ParamsToString() const override; CopyFunction function; - unique_ptr bind_data; + cow_ptr bind_data; string file_path; bool use_tmp_file; CopyFunctionReturnType return_type; @@ -42,8 +43,20 @@ class PhysicalBatchCopyToFile : public PhysicalOperator { optional_idx batch_size; optional_idx batch_size_bytes; + //! File rotation: file_path is a directory, and the files in it are written one after another + optional_idx batches_per_file; + optional_idx file_size_bytes; + CopyOverwriteMode overwrite_mode = CopyOverwriteMode::COPY_ERROR_ON_CONFLICT; + FilenamePattern filename_pattern; + string file_extension; + + bool Rotate() const { + return file_size_bytes.IsValid() || batches_per_file.IsValid(); + } + public: // Source interface + unique_ptr GetGlobalSourceState(ClientContext &context) const override; SourceResultType GetDataInternal(ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input) const override; @@ -86,5 +99,11 @@ class PhysicalBatchCopyToFile : public PhysicalOperator { bool ExecuteTask(ClientContext &context, GlobalSinkState &gstate_p) const; void ExecuteTasks(ClientContext &context, GlobalSinkState &gstate_p) const; SinkFinalizeType FinalFlush(ClientContext &context, GlobalSinkState &gstate_p) const; + +private: + //! Moves on to the next file once the current one has reached a rotation limit + void RotateFile(ClientContext &context, GlobalSinkState &gstate_p) const; + //! The result of a rotating copy: its files in the order they were written + SourceResultType GetRotatedFiles(ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input) const; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_copy_to_file.hpp b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_copy_to_file.hpp index 2e9f37705..9f443d544 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_copy_to_file.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_copy_to_file.hpp @@ -31,6 +31,8 @@ struct CopyToFileInfo { Value partition_keys; }; +class CopyOutputLifecycle; + //! Copy the contents of a query into a table class PhysicalCopyToFile : public PhysicalOperator { public: @@ -38,7 +40,7 @@ class PhysicalCopyToFile : public PhysicalOperator { public: PhysicalCopyToFile(PhysicalPlan &physical_plan, vector types, CopyFunction function, - unique_ptr bind_data, idx_t estimated_cardinality); + cow_ptr bind_data, idx_t estimated_cardinality); ~PhysicalCopyToFile() override; public: @@ -48,6 +50,9 @@ class PhysicalCopyToFile : public PhysicalOperator { static string GetTrimmedPath(ClientContext &context, const string &file_path); static void MoveTmpFile(ClientContext &context, const string &tmp_file_path); static string GetNonTmpFile(ClientContext &context, const string &tmp_file_path); + //! Creates or checks the directory a COPY writes several files into + static void PrepareOutputDirectory(ClientContext &context, const string &directory, + CopyOverwriteMode overwrite_mode, CopyOutputLifecycle &output_lifecycle); static void ReturnStatistics(Context &context, DataChunk &chunk, CopyToFileInfo &written_file_info); //! Adds the RETURN_STATS row of a COPY that wrote no file, so that RETURN_COLUMN_TYPES can still return the types static void ReturnNoFileStatistics(DataChunk &chunk); @@ -110,7 +115,7 @@ class PhysicalCopyToFile : public PhysicalOperator { public: //! Function and associated bind data CopyFunction function; - unique_ptr bind_data; + cow_ptr bind_data; //! Names and types going into the file(s) vector names; diff --git a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_update.hpp b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_update.hpp index 5d851faa8..78ab8b18a 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_update.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_update.hpp @@ -68,6 +68,19 @@ class PhysicalUpdate : public PhysicalOperator { bool ParallelSink() const override { return true; } + +public: + //! A thread stages out-of-order in-place updates until they use 1/STAGED_UPDATE_MEMORY_FRACTION of the memory + //! limit divided over the threads, bounded by STAGED_UPDATE_MIN_MEMORY and STAGED_UPDATE_MAX_MEMORY + static constexpr idx_t STAGED_UPDATE_MEMORY_FRACTION = 10; + static constexpr idx_t STAGED_UPDATE_MIN_MEMORY = 1ULL << 20ULL; + static constexpr idx_t STAGED_UPDATE_MAX_MEMORY = 64ULL << 20ULL; + +private: + void StageUpdates(ExecutionContext &context, GlobalSinkState &gstate, LocalSinkState &lstate, DataChunk &updates, + Vector &row_ids, InterruptState &interrupt_state) const; + void FlushStagedUpdates(ExecutionContext &context, GlobalSinkState &gstate, LocalSinkState &lstate, + InterruptState &interrupt_state) const; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp b/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp index b8f57ea36..92b4f74b2 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp @@ -21,7 +21,7 @@ class PhysicalTableInOutFunction : public PhysicalOperator { public: PhysicalTableInOutFunction(PhysicalPlan &physical_plan, vector types, BoundTableFunction function_p, - unique_ptr bind_data_p, vector column_ids_p, + cow_ptr bind_data_p, vector column_ids_p, vector projection_ids_p, unique_ptr table_filters_p, idx_t estimated_cardinality, vector projected_input); @@ -59,7 +59,7 @@ class PhysicalTableInOutFunction : public PhysicalOperator { //! The table function BoundTableFunction function; //! Bind data of the function - unique_ptr bind_data; + cow_ptr bind_data; //! The set of column ids to fetch vector column_ids; //! The projected-out column ids diff --git a/src/duckdb/src/include/duckdb/execution/operator/scan/physical_table_scan.hpp b/src/duckdb/src/include/duckdb/execution/operator/scan/physical_table_scan.hpp index 84d390952..659149b4a 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/scan/physical_table_scan.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/scan/physical_table_scan.hpp @@ -29,7 +29,7 @@ class PhysicalTableScan : public PhysicalOperator { public: //! Table scan that immediately projects out filter columns that are unused in the remainder of the query plan PhysicalTableScan(PhysicalPlan &physical_plan, vector types, BoundTableFunction function, - unique_ptr bind_data, vector returned_types, + cow_ptr bind_data, vector returned_types, vector column_ids, vector projection_ids, vector names, unique_ptr table_filters, idx_t estimated_cardinality, ExtraOperatorInfo extra_info, vector parameters, virtual_column_map_t virtual_columns); @@ -37,7 +37,7 @@ class PhysicalTableScan : public PhysicalOperator { //! The table function BoundTableFunction function; //! Bind data of the function - unique_ptr bind_data; + cow_ptr bind_data; //! The types of ALL columns that can be returned by the table function vector returned_types; //! The column ids used within the table function diff --git a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte.hpp b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte.hpp index c5516dd0e..fb4c3412a 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte.hpp @@ -136,6 +136,8 @@ class PhysicalRecursiveCTE : public PhysicalOperator { vector key_representative_indices; // Contains SQL-level distinct comparisons for the finalized payload columns vector> payload_comparisons; + //! DISTINCT FROM comparison of the previous and current value of every payload column + vector> payload_distinct_from; //! Physical-only partial-key indexes required by direct recursive state probes. vector partial_key_index_specs; //! Physical recursive inputs inside the recursive member diff --git a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_delta.hpp b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_delta.hpp index e476e7a29..9a9c9ce2c 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_delta.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_delta.hpp @@ -4,6 +4,8 @@ #include "duckdb/execution/aggregate_hashtable.hpp" #include "duckdb/execution/operator/set/physical_recursive_cte.hpp" +#include "duckdb/execution/expression_executor.hpp" + namespace duckdb { class RecursiveCTEGroupAddressSet { @@ -87,6 +89,8 @@ struct RecursiveCTEKeyDeltaState { DataChunk previous_scan_rows; DataChunk key_scan_rows; DataChunk comparison_rows; + //! DISTINCT FROM comparison of every payload column + vector> payload_distinct_from; Vector matched_addresses; Vector finalize_addresses; SelectionVector found_groups; diff --git a/src/duckdb/src/include/duckdb/execution/perfect_aggregate_hashtable.hpp b/src/duckdb/src/include/duckdb/execution/perfect_aggregate_hashtable.hpp index 5ceecbff5..0b45b925e 100644 --- a/src/duckdb/src/include/duckdb/execution/perfect_aggregate_hashtable.hpp +++ b/src/duckdb/src/include/duckdb/execution/perfect_aggregate_hashtable.hpp @@ -11,6 +11,7 @@ #include "duckdb/execution/base_aggregate_hashtable.hpp" #include "duckdb/storage/arena_allocator.hpp" #include "duckdb/common/clustered_aggregate.hpp" +#include "duckdb/common/row_operations/row_operations.hpp" namespace duckdb { @@ -67,6 +68,8 @@ class PerfectAggregateHashTable : public BaseAggregateHashTable { vector> stored_allocators; ClusteredAggrState clustered_state; + //! The finalize state of the scan, kept across Scan calls like the finalize local states it holds + unique_ptr scan_row_state; private: //! Try adding a chunk using the clustered aggregation path. Returns false if not applicable. diff --git a/src/duckdb/src/include/duckdb/execution/perfect_hash_join_table.hpp b/src/duckdb/src/include/duckdb/execution/perfect_hash_join_table.hpp index 42908d805..69eecac92 100644 --- a/src/duckdb/src/include/duckdb/execution/perfect_hash_join_table.hpp +++ b/src/duckdb/src/include/duckdb/execution/perfect_hash_join_table.hpp @@ -23,32 +23,46 @@ class PerfectHashJoinTable { public: enum class Type { BITMAP, ROWS, DICTIONARY }; - PerfectHashJoinTable(Type type, bool nulls_equal) : nulls_equal(nulls_equal), type(type) { + PerfectHashJoinTable(Type type, bool nulls_equal, bool track_matches) + : nulls_equal(nulls_equal), track_matches(track_matches), type(type) { D_ASSERT(type != Type::DICTIONARY); + D_ASSERT(!track_matches || type == Type::BITMAP); } virtual ~PerfectHashJoinTable(); - static unique_ptr Create(PhysicalType key_type, Type type, bool nulls_equal); + static unique_ptr Create(PhysicalType key_type, Type type, bool nulls_equal, + bool track_matches); //! Accumulate bounds before allocating the directory, independently of runtime filters. virtual void UpdateBounds(const Vector &keys) = 0; virtual void MergeBounds(const PerfectHashJoinTable &other) = 0; - virtual bool Initialize(Allocator &allocator, idx_t build_count, idx_t pointer_table_size) = 0; + //! Allocation size including match tracking, or zero for an unaffordable domain. + virtual idx_t EstimateSize(idx_t build_count, idx_t pointer_table_size) const = 0; + virtual bool Initialize(BufferAllocator &allocator, idx_t build_count, idx_t pointer_table_size) = 0; //! Returns whether duplicate keys produced a chain. virtual bool Insert(const Vector &rows, const TupleDataLayout &layout, idx_t pointer_offset, bool parallel) = 0; virtual void GetRowPointers(const Vector &keys, optional_ptr sel, idx_t &count, Vector &pointers, SelectionVector &matches) const = 0; virtual idx_t ProbeMembership(const Vector &keys, unsafe_unique_array &found_match) const = 0; virtual idx_t ProbeDictionary(const Vector &keys, SelectionVector &probe_sel, SelectionVector &build_sel) const = 0; + //! Select retained rows by their equality group's match state. + virtual idx_t SelectMatches(array_ptr rows, const TupleDataLayout &layout, idx_t &offset, + array_ptr result, bool matched) const = 0; void InitializeEntries(idx_t from, idx_t to); void ConvertToDictionary(idx_t pointer_offset); idx_t EntryCount() const { return entries.GetSize() / sizeof(uint64_t); } + idx_t SizeInBytes() const { + return entries.GetSize() + match_entries.GetSize(); + } Type GetType() const { return type; } + bool TracksMatches() const { + return track_matches; + } protected: bool IsBitmap() const { @@ -63,10 +77,16 @@ class PerfectHashJoinTable { array_ptr> GetAtomicEntries() { return {reinterpret_cast *>(entries.get()), EntryCount()}; } + array_ptr> GetMatchEntries() const { + D_ASSERT(track_matches); + return {reinterpret_cast *>(match_entries.get()), EntryCount()}; + } static constexpr idx_t MAX_BYTES = 8 * 1024 * 1024; - AllocatedData entries; + HugeAllocation entries; + mutable HugeAllocation match_entries; const bool nulls_equal; + const bool track_matches; private: Type type; diff --git a/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp b/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp index 684218fc1..2b91ebebc 100644 --- a/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp +++ b/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp @@ -49,7 +49,7 @@ class PhysicalPlan { public: template - PhysicalOperator &Make(ARGS &&... args) { + PhysicalOperator &Make(ARGS &&...args) { static_assert(std::is_base_of::value, "T must be a physical operator"); auto ptr = arena.Make(*this, std::forward(args)...); ops.push_back(*ptr); @@ -118,7 +118,7 @@ class PhysicalPlanGenerator { PhysicalOperator &child, vector &partition_columns); //! Make a physical operator in the physical plan. template - PhysicalOperator &Make(ARGS &&... args) { + PhysicalOperator &Make(ARGS &&...args) { return physical_plan->Make(std::forward(args)...); } @@ -197,11 +197,10 @@ class PhysicalPlanGenerator { vector right_map; vector original_types; }; - PrunedJoinProjection ExtractPrunedJoinProjection(LogicalComparisonJoin &op, const PhysicalOperator &left, + PrunedJoinProjection ExtractPrunedJoinProjection(LogicalJoin &op, const PhysicalOperator &left, const PhysicalOperator &right, bool expand_left, bool expand_right); - PhysicalOperator &RestorePrunedJoinProjection(LogicalComparisonJoin &op, PhysicalOperator &join, - PrunedJoinProjection info); + PhysicalOperator &RestorePrunedJoinProjection(LogicalJoin &op, PhysicalOperator &join, PrunedJoinProjection info); PhysicalOperator &PlanDelimJoin(LogicalComparisonJoin &op); PhysicalOperator &ExtractAggregateExpressions(PhysicalOperator &child, vector> &expressions, vector> &groups, 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 23ce5ef97..3b988b579 100644 --- a/src/duckdb/src/include/duckdb/execution/radix_ht_adaptivity.hpp +++ b/src/duckdb/src/include/duckdb/execution/radix_ht_adaptivity.hpp @@ -12,25 +12,47 @@ namespace duckdb { +class GroupedAggregateHashTable; class RadixHTGlobalSinkState; class RadixHTLocalSinkState; -//! Policy for the local sink HT. Called at fill-cycle boundaries without memory pressure. +//! Policy for growth, abandonment and lookups of one local sink HT. +//! Lookup decisions are independent of HLL and external aggregation. class RadixHTAdaptivity { public: + enum class SinkResult { UNCHANGED, ABANDONED, GROWN }; + +public: + //! Handle a full local table or memory pressure. + SinkResult HandleSinkBoundary(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate, bool memory_pressure); + void Reset(); + + //! Minimum cumulative input before lookups may first be skipped + static constexpr idx_t MIN_INPUT_ROWS_BEFORE_LOOKUP_SKIP = 1024 * 1024; + //! Minimum input processed while skipping before retrying lookups + static constexpr idx_t MIN_LOOKUP_RETRY_ROWS = 128 * 1024; + +private: //! Grow a profitable table within the memory budget, resuming lookups on success. static bool TryGrow(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate); //! Consider skipping lookups using the completed cycle, before abandonment. - static void MaybeSkipLookups(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate); + void MaybeSkipLookups(const RadixHTGlobalSinkState &gstate, GroupedAggregateHashTable &ht); //! Periodically retry lookups at the existing capacity, after abandonment. - static void MaybeResumeLookups(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate); - - //! Minimum input before skipping lookups and between subsequent retries - static constexpr idx_t LOOKUP_SAMPLE_SIZE = 1048576; + void MaybeResumeLookups(GroupedAggregateHashTable &ht) const; private: + static constexpr idx_t LOOKUP_HISTORY_DECAY_THRESHOLD_ROWS = 128 * 1024; + static constexpr idx_t MAX_LOOKUP_RETRY_ROWS = 1024 * 1024; + static constexpr idx_t LOOKUP_RETRY_MATERIALIZED_ROWS_DIVISOR = 8; static constexpr double GROWTH_DUPLICATE_BYTES_FACTOR = 4.0; static constexpr double MINIMUM_SMALL_TABLE_REDUCTION = 0.05; + +private: + //! Decayed observations from completed lookup-enabled cycles + idx_t recent_input_rows = 0; + idx_t recent_reduced_rows = 0; + //! Input rows before retrying, chosen when skipping starts + idx_t retry_interval_rows = MIN_LOOKUP_RETRY_ROWS; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/radix_ht_sink_state.hpp b/src/duckdb/src/include/duckdb/execution/radix_ht_sink_state.hpp index 8f7005668..565f89f8b 100644 --- a/src/duckdb/src/include/duckdb/execution/radix_ht_sink_state.hpp +++ b/src/duckdb/src/include/duckdb/execution/radix_ht_sink_state.hpp @@ -11,6 +11,7 @@ #include "duckdb/execution/radix_partitioned_hashtable.hpp" #include "duckdb/execution/aggregate_hashtable.hpp" #include "duckdb/execution/aggregate_state_spilling.hpp" +#include "duckdb/execution/radix_ht_adaptivity.hpp" #include "duckdb/storage/temporary_memory_manager.hpp" namespace duckdb { @@ -142,6 +143,8 @@ class RadixHTGlobalSinkState : public GlobalSinkState { const RadixPartitionedHashTable &radix_ht; //! The spill metadata of the aggregate layout, set if the states can spill unique_ptr spill_plan; + //! debug_force_external: also export every arena-backed state that has a spill plan + const bool force_external; //! Config for partitioning RadixHTConfig config; @@ -190,6 +193,8 @@ class RadixHTLocalSinkState : public LocalSinkState { idx_t local_sink_capacity; //! Spillable size of the HT after it was last abandoned idx_t size_after_abandon = 0; + //! Adaptivity policy for this local sink + RadixHTAdaptivity adaptivity; //! Data that is abandoned ends up here (only if we're doing external aggregation) unique_ptr abandoned_data; //! Exported abandoned aggregate states, aligned one-to-one with the partitions of abandoned_data diff --git a/src/duckdb/src/include/duckdb/function/aggregate/distributive_function_utils.hpp b/src/duckdb/src/include/duckdb/function/aggregate/distributive_function_utils.hpp index de0391839..f0ad154ad 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate/distributive_function_utils.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate/distributive_function_utils.hpp @@ -97,6 +97,8 @@ struct CountFunctionBase { static AggregateFunction GetFunction(); }; +bool IsFirstLastOrAnyValue(const BoundAggregateFunction &function); + struct FirstFunctionGetter { static AggregateFunction GetFunction(const LogicalType &type); }; diff --git a/src/duckdb/src/include/duckdb/function/aggregate_function.hpp b/src/duckdb/src/include/duckdb/function/aggregate_function.hpp index a476bc054..cd1fad5bd 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate_function.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate_function.hpp @@ -102,8 +102,8 @@ typedef void (*aggregate_finalize_t)(Vector &state, AggregateFinalizeInputData & //! Initializes the local state used by the finalize of the aggregate (optional). //! The local state can be used to cache expensive intermediates between finalized groups - callers can keep the //! local state alive to re-use it across multiple finalize calls (see AggregateFinalizeInputData). -typedef unique_ptr (*aggregate_init_local_state_finalize_t)(const BoundAggregateFunction &function, - optional_ptr bind_data); +typedef unique_ptr (*aggregate_init_local_state_finalize_t)( + const BoundAggregateFunction &function, optional_ptr bind_data); //! The type used for propagating statistics in aggregate functions (optional) typedef unique_ptr (*aggregate_statistics_t)(ClientContext &context, BoundAggregateExpression &expr, AggregateStatisticsInput &input); @@ -136,7 +136,7 @@ typedef void (*aggregate_window_batch_t)(AggregateInputData &aggr_input_data, co typedef void (*aggregate_wininit_t)(AggregateInputData &aggr_input_data, const WindowPartitionInput &partition, data_ptr_t g_state); -typedef void (*aggregate_serialize_t)(Serializer &serializer, const optional_ptr bind_data, +typedef void (*aggregate_serialize_t)(Serializer &serializer, const optional_ptr bind_data, const BoundAggregateFunction &function); typedef unique_ptr (*aggregate_deserialize_t)(Deserializer &deserializer, BoundAggregateFunction &function); @@ -355,6 +355,9 @@ class AggregateFunctionProperties : public FunctionProperties { //! Whether an aggregate is holistic (e.g., don't use it for window segment trees...) bool is_holistic = false; + //! Whether combining can leave the target referencing the source's memory + AggregateCombineSourceRetention combine_source_retention = AggregateCombineSourceRetention::MAY_RETAIN; + bool operator==(const AggregateFunctionProperties &rhs) const; bool operator!=(const AggregateFunctionProperties &rhs) const; }; @@ -405,6 +408,10 @@ class BaseAggregateFunction { auto IsHolistic() const -> bool { return properties.is_holistic; } auto SetIsHolistic(bool value) -> void { properties.is_holistic = value; } + //! Whether combining can leave the target referencing the source's memory + auto GetCombineSourceRetention() const -> AggregateCombineSourceRetention { return properties.combine_source_retention; } + auto SetCombineSourceRetention(AggregateCombineSourceRetention value) -> void { properties.combine_source_retention = value; } + // Derived properties bool CanAggregate() const { return callbacks.update || callbacks.combine || callbacks.finalize; } bool CanWindow() const { return callbacks.window || callbacks.window_batch; } @@ -511,7 +518,7 @@ class BaseAggregateFunction { function_info = std::move(info); } template - auto SetExtraFunctionInfo(ARGS &&... args) -> void { + auto SetExtraFunctionInfo(ARGS &&...args) -> void { function_info = make_shared_ptr(std::forward(args)...); } auto GetFunctionInfo() const -> shared_ptr { @@ -926,7 +933,7 @@ class BoundAggregateFunction : public BaseAggregateFunction, public BoundSimpleF const LogicalType &GetLogicalReturnType() const { return logical_return_type; } - AggregateStateLayout GetStateType(optional_ptr bind_data) const { + AggregateStateLayout GetStateType(optional_ptr bind_data) const { D_ASSERT(callbacks.get_state_type); AggregateLayoutInput input(*this, bind_data); return callbacks.get_state_type(input); diff --git a/src/duckdb/src/include/duckdb/function/aggregate_state.hpp b/src/duckdb/src/include/duckdb/function/aggregate_state.hpp index 854c5895b..78b3b07b0 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate_state.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate_state.hpp @@ -27,13 +27,15 @@ enum class AggregateOrderDependent : uint8_t { ORDER_DEPENDENT = 1, NOT_ORDER_DE enum class AggregateDistinctDependent : uint8_t { DISTINCT_DEPENDENT = 1, NOT_DISTINCT_DEPENDENT = 2 }; //! Whether or not the combiner needs to preserve the source enum class AggregateCombineType : uint8_t { PRESERVE_INPUT = 1, ALLOW_DESTRUCTIVE = 2 }; +//! Whether a combined target can keep referencing the source state's memory (e.g. by splicing it) +enum class AggregateCombineSourceRetention : uint8_t { MAY_RETAIN = 1, NEVER_RETAINS = 2 }; //! Whether or not we are exporting the state of the aggregate enum class AggregateStateExportMode : uint8_t { NONE = 1, STATE_EXPORT = 2 }; class BoundAggregateExpression; struct AggregateInputData { - AggregateInputData(const BoundAggregateFunction &function_p, optional_ptr bind_data_p, + AggregateInputData(const BoundAggregateFunction &function_p, optional_ptr bind_data_p, ArenaAllocator &allocator_p, AggregateCombineType combine_type_p = AggregateCombineType::PRESERVE_INPUT) : function(function_p), bind_data(bind_data_p), allocator(allocator_p), combine_type(combine_type_p) { @@ -44,7 +46,7 @@ struct AggregateInputData { AggregateCombineType combine_type_p = AggregateCombineType::PRESERVE_INPUT); const BoundAggregateFunction &function; - optional_ptr bind_data; + optional_ptr bind_data; ArenaAllocator &allocator; AggregateCombineType combine_type; optional_ptr clustered; @@ -54,12 +56,12 @@ struct AggregateInputData { //! Input to the get_state_type callback - bundles the bound aggregate function with its bind data so that the //! callback can resolve the exported state layout (including any constant parameters stored in the bind data). struct AggregateLayoutInput { - AggregateLayoutInput(const BoundAggregateFunction &function_p, optional_ptr bind_data_p) + AggregateLayoutInput(const BoundAggregateFunction &function_p, optional_ptr bind_data_p) : function(function_p), bind_data(bind_data_p) { } const BoundAggregateFunction &function; - optional_ptr bind_data; + optional_ptr bind_data; }; //! Input to the state size/init callbacks - bundles the bound aggregate function with its bind data so that the @@ -79,7 +81,7 @@ struct AggregateStateInput { //! re-used across multiple finalize calls (e.g. for the duration of a hash table scan). struct AggregateFinalizeInputData : public AggregateInputData { DUCKDB_API AggregateFinalizeInputData(const BoundAggregateFunction &function_p, - optional_ptr bind_data_p, ArenaAllocator &allocator_p, + optional_ptr bind_data_p, ArenaAllocator &allocator_p, optional_ptr local_state_p = nullptr); DUCKDB_API AggregateFinalizeInputData(const BoundAggregateExpression &expr, ArenaAllocator &allocator_p, optional_ptr local_state_p = nullptr); @@ -89,6 +91,11 @@ struct AggregateFinalizeInputData : public AggregateInputData { //! The local state of the finalize (set if the function defines an "init_local_state_finalize" callback) optional_ptr local_state; + //! Whether the local state is owned by this input (and so does not outlive the finalize call) + bool OwnsLocalState() const { + return owned_state != nullptr; + } + private: //! Initializes the local state when the caller did not pass in an external one void InitializeLocalState(); @@ -153,12 +160,13 @@ struct AggregateFinalizeData { }; struct AggregateStatisticsInput { - AggregateStatisticsInput(optional_ptr bind_data_p, vector &child_stats_p, + AggregateStatisticsInput(cow_ptr &bind_data_p, vector &child_stats_p, optional_ptr node_stats_p) : bind_data(bind_data_p), child_stats(child_stats_p), node_stats(node_stats_p) { } - optional_ptr bind_data; + //! The bind data of the aggregate - use write() to modify it + cow_ptr &bind_data; vector &child_stats; optional_ptr node_stats; }; diff --git a/src/duckdb/src/include/duckdb/function/aggregate_state_serialization.hpp b/src/duckdb/src/include/duckdb/function/aggregate_state_serialization.hpp index 3a6a51605..4da530175 100644 --- a/src/duckdb/src/include/duckdb/function/aggregate_state_serialization.hpp +++ b/src/duckdb/src/include/duckdb/function/aggregate_state_serialization.hpp @@ -30,7 +30,7 @@ enum class StateMemoryOwnership : uint8_t { //! state export layouts. Used by the aggregate state export functions and by state spilling. struct AggregateStateSerialization { //! Serialize `count` states into `result` (of the layout's logical type) at [offset, offset + count) - static void SerializeStates(const BoundAggregateFunction &aggr, optional_ptr bind_data, + static void SerializeStates(const BoundAggregateFunction &aggr, optional_ptr bind_data, const AggregateStateLayout &layout, Vector &states, idx_t count, Vector &result, ArenaAllocator &allocator, idx_t offset); //! Serialize `count` states at the given addresses, without an aggregate-specific export callback diff --git a/src/duckdb/src/include/duckdb/function/built_in_functions.hpp b/src/duckdb/src/include/duckdb/function/built_in_functions.hpp index 766466847..e83ca7c6f 100644 --- a/src/duckdb/src/include/duckdb/function/built_in_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/built_in_functions.hpp @@ -33,8 +33,8 @@ class BuiltinFunctions { void AddFunction(TableFunction function); void AddFunction(CopyFunction function); - void AddCollation(string name, ScalarFunction function, bool combinable = false, - bool not_required_for_equality = false); + //! Registers the function as the string collation with the given name (as collate_) + void AddCollation(const string &name, ScalarFunction function, bool combinable = false); private: CatalogTransaction transaction; @@ -54,11 +54,13 @@ class BuiltinFunctions { void RegisterArrowFunctions(); void RegisterSnifferFunction(); void RegisterCopyFunctions(); + void RegisterEncodingFunctions(); void RegisterExtensionOverloads(); // pragmas void RegisterPragmaFunctions(); + void RegisterCollations(); void AddExtensionFunction(ScalarFunctionSet set); }; diff --git a/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp b/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp index 92d710fdb..6feb3f37c 100644 --- a/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp @@ -108,14 +108,6 @@ struct CastLocalStateParameters { optional_ptr cast_data; }; -//! The local state of a cast to or from a wide DECIMAL: the context lets long BIGNUM conversions check for interrupts -struct WideDecimalCastState : public FunctionLocalState { - explicit WideDecimalCastState(optional_ptr context_p) : context(context_p) { - } - - optional_ptr context; -}; - typedef bool (*cast_function_t)(Vector &source, Vector &result, idx_t count, CastParameters ¶meters); typedef unique_ptr (*init_cast_local_state_t)(CastLocalStateParameters ¶meters); diff --git a/src/duckdb/src/include/duckdb/function/cast/variant/primitive_to_variant.hpp b/src/duckdb/src/include/duckdb/function/cast/variant/primitive_to_variant.hpp index f5a73191d..3a107dba8 100644 --- a/src/duckdb/src/include/duckdb/function/cast/variant/primitive_to_variant.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/variant/primitive_to_variant.hpp @@ -396,6 +396,9 @@ bool ConvertPrimitiveToVariant(ToVariantSourceData &source, ToVariantGlobalResul case LogicalTypeId::GEOMETRY: return ConvertPrimitiveTemplated( source, result, count, selvec, values_index_selvec, empty_payload, is_root); + case LogicalTypeId::GEOGRAPHY: + return ConvertPrimitiveTemplated( + source, result, count, selvec, values_index_selvec, empty_payload, is_root); case LogicalTypeId::BLOB: return ConvertPrimitiveTemplated( source, result, count, selvec, values_index_selvec, empty_payload, is_root); diff --git a/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp b/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp index 3bf35f0b0..35a4123e0 100644 --- a/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp @@ -111,6 +111,9 @@ struct VariantToVariantSizeAnalyzer { static uint32_t VisitGeometry(const string_t &geom, AnalyzeState &state) { return VisitString(geom, state); } + static uint32_t VisitGeography(const string_t &geog, AnalyzeState &state) { + return VisitString(geog, state); + } static uint32_t VisitBitstring(const string_t &bits, AnalyzeState &state) { return VisitString(bits, state); } @@ -219,6 +222,9 @@ struct VariantToVariantDataWriter { static void VisitGeometry(const string_t &geom, WriteState &state) { return VisitString(geom, state); } + static void VisitGeography(const string_t &geog, WriteState &state) { + return VisitString(geog, state); + } static void VisitBitstring(const string_t &bits, WriteState &state) { return VisitString(bits, state); } diff --git a/src/duckdb/src/include/duckdb/function/cast/wide_decimal_cast.hpp b/src/duckdb/src/include/duckdb/function/cast/wide_decimal_cast.hpp new file mode 100644 index 000000000..4638ada3f --- /dev/null +++ b/src/duckdb/src/include/duckdb/function/cast/wide_decimal_cast.hpp @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// DuckDB +// +// duckdb/function/cast/wide_decimal_cast.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/function/cast/default_casts.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/bignum_decimal.hpp" + +namespace duckdb { + +//! Arithmetic and formatting buffers reused by a bound wide-decimal cast. +struct WideDecimalCastState : public FunctionLocalState { + explicit WideDecimalCastState(optional_ptr context_p) : context(context_p) { + } + + DecimalHelper::RescaleState &GetRescaleState() { + if (!rescale) { + rescale = make_uniq::RescaleState>(context); + } + return *rescale; + } + + BignumCastScratch &GetFormattingState() { + if (!formatting) { + formatting = make_uniq(context); + } + return *formatting; + } + + optional_ptr context; + string unscaled_blob; + string formatted; + +private: + unique_ptr::RescaleState> rescale; + unique_ptr formatting; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/compression_function.hpp b/src/duckdb/src/include/duckdb/function/compression_function.hpp index c3d36db46..0a3b8c013 100644 --- a/src/duckdb/src/include/duckdb/function/compression_function.hpp +++ b/src/duckdb/src/include/duckdb/function/compression_function.hpp @@ -161,6 +161,13 @@ typedef void (*compression_scan_vector_t)(ColumnSegment &segment, ColumnScanStat //! Function prototype used for reading an arbitrary ('scan_count') number of values typedef void (*compression_scan_partial_t)(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset); +//! Validity codecs decode into a mask; the column layer handles the result vector's representation. +//! Partial scans preserve existing invalid bits and bits outside the requested range. +typedef void (*compression_scan_validity_t)(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, + ValidityMask &result, idx_t result_offset, ScanVectorType scan_type); +typedef void (*compression_select_validity_t)(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, + ValidityMask &result, const SelectionVector &sel, idx_t sel_count, + idx_t result_offset); //! Function prototype used for reading a subset of the values of a vector indicated by a selection vector //! The selected values are written to 'result' starting at 'result_offset'. Emitting a compressed vector (e.g. a //! constant vector) is only allowed if 'scan_type' is SCAN_ENTIRE_VECTOR @@ -265,6 +272,9 @@ class CompressionFunction { //! this can request > vector_size as well //! this is used if a vector crosses segment boundaries, or for child columns of lists compression_scan_partial_t scan_partial; + //! Mask-only callbacks used by the shared validity column scan adapters + compression_scan_validity_t scan_validity = nullptr; + compression_select_validity_t select_validity = nullptr; //! scan a subset of a vector compression_select_t select; //! Scan and apply a filter to a vector while scanning diff --git a/src/duckdb/src/include/duckdb/function/copy_function.hpp b/src/duckdb/src/include/duckdb/function/copy_function.hpp index 70d5d7a5c..4ad096c0a 100644 --- a/src/duckdb/src/include/duckdb/function/copy_function.hpp +++ b/src/duckdb/src/include/duckdb/function/copy_function.hpp @@ -129,7 +129,8 @@ struct CopyOptionsInput { struct CopyToPropagateStatsInput { ClientContext &context; - FunctionData &bind_data; + //! The bind data of the copy - use write() to modify it + cow_ptr &bind_data; const vector> &column_stats; }; @@ -140,14 +141,16 @@ typedef void (*copy_options_t)(ClientContext &context, CopyOptionsInput &input); typedef unique_ptr (*copy_to_bind_t)(ClientContext &context, CopyFunctionBindInput &input, const vector &names, const vector &sql_types); -typedef unique_ptr (*copy_to_initialize_local_t)(ExecutionContext &context, FunctionData &bind_data); -typedef unique_ptr (*copy_to_initialize_global_t)(ClientContext &context, FunctionData &bind_data, +typedef unique_ptr (*copy_to_initialize_local_t)(ExecutionContext &context, + const FunctionData &bind_data); +typedef unique_ptr (*copy_to_initialize_global_t)(ClientContext &context, + const FunctionData &bind_data, const string &file_path); -typedef void (*copy_to_sink_t)(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +typedef void (*copy_to_sink_t)(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate, DataChunk &input); -typedef void (*copy_to_combine_t)(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +typedef void (*copy_to_combine_t)(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate); -typedef void (*copy_to_finalize_t)(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate); +typedef void (*copy_to_finalize_t)(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate); typedef void (*copy_to_serialize_t)(Serializer &serializer, const FunctionData &bind_data, const CopyFunction &function); @@ -159,19 +162,19 @@ typedef unique_ptr (*copy_from_bind_t)(ClientContext &context, Cop vector &expected_types); typedef CopyFunctionExecutionMode (*copy_to_execution_mode_t)(bool preserve_insertion_order, bool supports_batch_index); -typedef unique_ptr (*copy_prepare_batch_t)(ClientContext &context, FunctionData &bind_data, +typedef unique_ptr (*copy_prepare_batch_t)(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, unique_ptr collection); -typedef void (*copy_flush_batch_t)(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +typedef void (*copy_flush_batch_t)(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, PreparedBatchData &batch); typedef optional_idx (*copy_default_batch_size_t)(); typedef optional_idx (*copy_default_batch_size_bytes_t)(); typedef idx_t (*copy_file_size_bytes_t)(GlobalFunctionData &gstate); -typedef optional_idx (*copy_desired_batch_size_t)(ClientContext &context, FunctionData &bind_data); +typedef optional_idx (*copy_desired_batch_size_t)(ClientContext &context, const FunctionData &bind_data); -typedef void (*copy_to_get_written_statistics_t)(ClientContext &context, FunctionData &bind_data, +typedef void (*copy_to_get_written_statistics_t)(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, CopyFunctionFileStatistics &statistics); typedef vector> (*copy_to_select_t)(CopyToSelectInput &input); diff --git a/src/duckdb/src/include/duckdb/function/create_sort_key.hpp b/src/duckdb/src/include/duckdb/function/create_sort_key.hpp index f2e0e235a..4a82c5a5c 100644 --- a/src/duckdb/src/include/duckdb/function/create_sort_key.hpp +++ b/src/duckdb/src/include/duckdb/function/create_sort_key.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/function/function_set.hpp" +#include "duckdb/common/vector.hpp" namespace duckdb { @@ -47,8 +48,19 @@ struct OrderModifiers { } }; +struct CreateSortKeyState : FunctionLocalState { + unsafe_vector lengths; + unsafe_vector offsets; + unsafe_vector data_pointers; +}; + struct CreateSortKeyHelpers { + static constexpr const char *NON_NULL_RESULT_PROPERTY = "duckdb.create_sort_key.non_null_result"; + + static bool IsNonNullSortKey(const Expression &expression); static void CreateSortKey(DataChunk &input, const vector &modifiers, Vector &result); + static void CreateSortKey(DataChunk &input, const vector &modifiers, Vector &result, + CreateSortKeyState &state); static void CreateSortKey(const Vector &input, OrderModifiers modifiers, Vector &result); static void CreateSortKey(const Vector &input, idx_t count, OrderModifiers modifiers, Vector &result); static bool IsNullSortKey(const_data_ptr_t data, OrderByNullType null_order); diff --git a/src/duckdb/src/include/duckdb/function/encoding_function.hpp b/src/duckdb/src/include/duckdb/function/encoding_function.hpp index 8e7cd70d1..97b0f6626 100644 --- a/src/duckdb/src/include/duckdb/function/encoding_function.hpp +++ b/src/duckdb/src/include/duckdb/function/encoding_function.hpp @@ -9,87 +9,56 @@ #pragma once #include "duckdb/common/common.hpp" -#include "duckdb/common/enums/compression_type.hpp" -#include "duckdb/common/map.hpp" -#include "duckdb/common/mutex.hpp" -#include "duckdb/function/function.hpp" -#include "duckdb/function/map_entry_encoding.hpp" -#include "duckdb/storage/data_pointer.hpp" -#include "duckdb/storage/storage_info.hpp" +#include +#include "duckdb/function/function_set.hpp" +#include "duckdb/parser/parsed_data/create_function_info.hpp" +#include "duckdb/function/scalar_function.hpp" namespace duckdb { -struct DBConfig; +//! Decodes a prefix of the encoded input to UTF-8 and returns how many input bytes were consumed. +//! The output has room for input_size * max_output_bytes bytes. Unless is_last is set, an incomplete trailing +//! character is left unconsumed. With is_last set, all input is consumed or an error is thrown. +typedef std::function + decode_t; -class EncodingFunction; +//! Encodes UTF-8 input and returns the number of bytes written. The output has room for +//! input_size * minimum_input_window bytes. Throws if the input has a character the encoding cannot represent. +typedef std::function encode_t; -struct CSVEncoderBuffer; -//! Decode function, basically takes information about the decoded and the encoded buffers. -typedef void (*encode_t)(CSVEncoderBuffer &encoded_buffer, char *decoded_buffer, idx_t &decoded_buffer_current_position, - const idx_t decoded_buffer_size, char *remaining_bytes_buffer, idx_t &remaining_bytes_size, - EncodingFunction *encoding_function); +class ClientContext; +class ScalarFunctionCatalogEntry; +class Expression; -class EncodingFunction { -public: - DUCKDB_API EncodingFunction() : encode_function(nullptr), max_bytes_per_iteration(0) { - } +//! An encoding is a set of scalar functions named after the encoding in the system.encodings schema: +//! system.encodings.""(BLOB) -> VARCHAR decodes the complete input +//! system.encodings.""(BLOB, BOOLEAN) -> STRUCT(decoded VARCHAR, consumed BIGINT) +//! decodes a prefix of a stream, see decode_t +//! system.encodings.""(VARCHAR) -> BLOB encodes the input, see encode_t (optional) +struct EncodingFunction { + static constexpr const char *SCHEMA = "encodings"; + //! Integer function property: the maximum number of input bytes that make up one character + static constexpr const char *MINIMUM_INPUT_WINDOW_PROPERTY = "duckdb.encodings.minimum_input_window"; - DUCKDB_API EncodingFunction(const string &encode_name, encode_t encode_function, const idx_t bytes_per_iteration, - const idx_t lookup_bytes) - : name(encode_name), encode_function(encode_function), max_bytes_per_iteration(bytes_per_iteration), - lookup_bytes(lookup_bytes) { - D_ASSERT(encode_function); - D_ASSERT(bytes_per_iteration > 0); - D_ASSERT(lookup_bytes > 0); - }; - - DUCKDB_API EncodingFunction(const string &encode_name, encode_t encode_function, const idx_t bytes_per_iteration, - const idx_t lookup_bytes, const map_entry_encoding *map, const size_t map_size) - : conversion_map(map), map_size(map_size), name(encode_name), encode_function(encode_function), - max_bytes_per_iteration(bytes_per_iteration), lookup_bytes(lookup_bytes) { - D_ASSERT(encode_function); - D_ASSERT(bytes_per_iteration > 0); - D_ASSERT(lookup_bytes > 0); - }; - - DUCKDB_API ~EncodingFunction() {}; - - DUCKDB_API string GetName() const { - return name; - } - DUCKDB_API encode_t GetFunction() const { - return encode_function; - } - DUCKDB_API idx_t GetBytesPerIteration() const { - return max_bytes_per_iteration; - } - DUCKDB_API idx_t GetLookupBytes() const { - return lookup_bytes; - } - - //! Optional conversion map, that indicates byte replacements. - const map_entry_encoding *conversion_map {}; - size_t map_size {}; - -protected: - //! The encoding type of this function (e.g., utf-8) - string name; - //! The actual encoding function - encode_t encode_function; - //! How many bytes in the decoded buffer one iteration of the encoded function can cause. - //! e.g., one iteration of Latin-1 to UTF-8 can generate max 2 bytes. - //! However, one iteration of UTF-16 to UTF-8, can generate up to 3 UTF-8 bytes. - idx_t max_bytes_per_iteration; - //! How many bytes we have to lookup before knowing the bytes we have to output - idx_t lookup_bytes = 1; -}; - -//! The set of encoding functions -struct EncodingFunctionSet { - EncodingFunctionSet() {}; - static void Initialize(DBConfig &config); - mutex lock; - case_insensitive_map_t functions; + //! The name of the scalar function that decodes the encoding + DUCKDB_API static string FunctionName(const string &encoding_name); + //! Registers the functions of an encoding in the system.encodings schema + DUCKDB_API static void SetSchema(CreateFunctionInfo &info); + //! The type returned by the streaming overload + DUCKDB_API static LogicalType StreamResultType(); + //! Creates the scalar functions for an encoding that is decoded by the given function + DUCKDB_API static ScalarFunctionSet Create(const string &encoding_name, decode_t decode, const encode_t &encode, + idx_t minimum_input_window, idx_t max_output_bytes); + //! Finds the functions of an encoding, autoloading the encodings extension if needed. Returns null if not found. + DUCKDB_API static optional_ptr Find(ClientContext &context, + const string &encoding_name); + //! The sorted names of all encodings, including utf-8 + DUCKDB_API static vector GetEncodings(ClientContext &context); + //! Binds encode(string, encoding) and decode(blob, encoding) to the function of the encoding. Returns null if the + //! encoding is not a constant that names an encoding (e.g. an error option of decode). + DUCKDB_API static unique_ptr BindCall(ClientContext &context, vector> &children, + bool is_encode); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/function.hpp b/src/duckdb/src/include/duckdb/function/function.hpp index 025598466..cfdb36261 100644 --- a/src/duckdb/src/include/duckdb/function/function.hpp +++ b/src/duckdb/src/include/duckdb/function/function.hpp @@ -11,12 +11,14 @@ #include "duckdb/common/identifier.hpp" #include "duckdb/common/named_parameter_map.hpp" #include "duckdb/common/types/data_chunk.hpp" +#include "duckdb/common/unordered_map.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/main/external_dependencies.hpp" #include "duckdb/common/enums/function_errors.hpp" #include "duckdb/common/optional_idx.hpp" #include "duckdb/common/optional.hpp" #include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/cow_ptr.hpp" #include "duckdb/parser/qualified_name.hpp" namespace duckdb { @@ -593,6 +595,16 @@ class FunctionProperties { requires_ordered_execution = value; } + //! Sets a generic property, e.g. "duckdb.collation.combinable", overwriting any previous value + DUCKDB_API void SetProperty(const string &name, Value value); + //! Returns the value of a generic property, or nullptr if it is not set + DUCKDB_API optional_ptr GetProperty(const string &name) const; + //! Returns whether a generic property is the BOOLEAN true; an absent or non-BOOLEAN property is false + DUCKDB_API bool GetBooleanProperty(const string &name) const; + auto GetGenericProperties() const -> const unordered_map & { + return generic_properties; + } + // Helpers auto SetFallible() -> void { errors = FunctionErrors::CAN_THROW_RUNTIME_ERROR; @@ -604,6 +616,9 @@ class FunctionProperties { bool operator==(const FunctionProperties &rhs) const; bool operator!=(const FunctionProperties &rhs) const; +private: + bool GenericPropertiesEqual(const FunctionProperties &rhs) const; + public: FunctionStability stability = FunctionStability::CONSISTENT; //! How this function handles NULL values @@ -620,6 +635,8 @@ class FunctionProperties { bool requires_expression_names = false; //! Whether calls to this function must follow input order bool requires_ordered_execution = false; + //! Generic properties by name, e.g. "duckdb.collation.combinable" + unordered_map generic_properties; }; class BoundSimpleFunction { diff --git a/src/duckdb/src/include/duckdb/function/function_serialization.hpp b/src/duckdb/src/include/duckdb/function/function_serialization.hpp index 2711e1f86..393520f11 100644 --- a/src/duckdb/src/include/duckdb/function/function_serialization.hpp +++ b/src/duckdb/src/include/duckdb/function/function_serialization.hpp @@ -76,7 +76,7 @@ class FunctionSerializer { public: template - static void Serialize(Serializer &serializer, const FUNC &function, optional_ptr bind_info) { + static void Serialize(Serializer &serializer, const FUNC &function, optional_ptr bind_info) { D_ASSERT(!function.GetName().empty()); if (!serializer.ShouldSerialize(StorageVersion::V2_0_0)) { serializer.WriteProperty(500, "name", function.GetName()); diff --git a/src/duckdb/src/include/duckdb/function/lambda_functions.hpp b/src/duckdb/src/include/duckdb/function/lambda_functions.hpp index 7538b3a5e..73a6e5005 100644 --- a/src/duckdb/src/include/duckdb/function/lambda_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/lambda_functions.hpp @@ -54,7 +54,7 @@ struct ListLambdaBindData final : public LambdaFunctionData { } //! Serializes a lambda function's bind data - static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, + static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundScalarFunction &function); //! Deserializes a lambda function's bind data static unique_ptr Deserialize(Deserializer &deserializer, BoundScalarFunction &); diff --git a/src/duckdb/src/include/duckdb/function/macro_function.hpp b/src/duckdb/src/include/duckdb/function/macro_function.hpp index 493a6c4d9..6aa8ba240 100644 --- a/src/duckdb/src/include/duckdb/function/macro_function.hpp +++ b/src/duckdb/src/include/duckdb/function/macro_function.hpp @@ -61,7 +61,7 @@ class MacroFunction { Binder &binder, const vector> ¯o_functions, const Identifier &name, FunctionExpression &function_expr, vector> &positional_arguments, InsertionOrderPreservingMap, Identifier, identifier_map_t> &named_arguments, - idx_t depth); + idx_t depth, optional_ptr calling_binder); static unique_ptr CreateDummyBinding(const MacroFunction ¯o_def, const Identifier &name, vector> &positional_arguments, diff --git a/src/duckdb/src/include/duckdb/function/map_entry_encoding.hpp b/src/duckdb/src/include/duckdb/function/map_entry_encoding.hpp deleted file mode 100644 index 85e9d5040..000000000 --- a/src/duckdb/src/include/duckdb/function/map_entry_encoding.hpp +++ /dev/null @@ -1,24 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/function/map_entry_encoding.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -// Deliberately doesn't include DuckDB headers, so the encodings extension can use compilation caches efficiently. -#include - -namespace duckdb { - -//! Encoding Map Entry Struct used for byte replacement -typedef struct { - size_t key_len; - const char *key; - size_t value_len; - const char *value; -} map_entry_encoding; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/scalar/crypto_hash.hpp b/src/duckdb/src/include/duckdb/function/scalar/crypto_hash.hpp index 8b5c90240..781c06b06 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/crypto_hash.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/crypto_hash.hpp @@ -33,7 +33,8 @@ struct LocalState : public FunctionLocalState { }; template -unique_ptr InitLocalState(ExpressionState &state, const BoundFunctionExpression &, FunctionData *) { +unique_ptr InitLocalState(ExpressionState &state, const BoundFunctionExpression &, + optional_ptr) { auto &db = state.GetContext().GetDatabase(); auto &config = DBConfig::GetConfig(db); auto force_mbedtls = Settings::Get(config); diff --git a/src/duckdb/src/include/duckdb/function/scalar/generic_common.hpp b/src/duckdb/src/include/duckdb/function/scalar/generic_common.hpp index 6e77374f9..cc5738bf5 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/generic_common.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/generic_common.hpp @@ -15,7 +15,9 @@ #include "duckdb/common/serializer/deserializer.hpp" namespace duckdb { +class BoundAggregateFunction; class BoundFunctionExpression; +struct AggregateStateLayout; struct SortedAggregateStateOrder; struct ConstantOrNull { @@ -35,6 +37,10 @@ struct ExportAggregateFunction { static unique_ptr StateToSQL(const LogicalType &type, unique_ptr value); //! The per-key (column, modifiers) of the AGGREGATE_STATE type of an ordered aggregate static void GetSortedStateOrders(const LogicalType &state_type, vector &orders); + //! The state layout of the aggregate whose states a bound combine_aggr accumulates. Returns false for any other + //! function, and for an aggregate whose state the field layout alone does not describe + static bool TryGetCombinedStateLayout(const BoundAggregateFunction &function, + optional_ptr bind_data, AggregateStateLayout &layout); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/scalar/generic_functions.hpp b/src/duckdb/src/include/duckdb/function/scalar/generic_functions.hpp index a221dc8d3..7e37dbc59 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/generic_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/generic_functions.hpp @@ -43,6 +43,7 @@ struct ErrorFun { static constexpr const char *Categories = ""; static ScalarFunction GetFunction(); + static bool IsError(const BoundScalarFunction &function); }; struct HasErrorFun { diff --git a/src/duckdb/src/include/duckdb/function/scalar/geometry_functions.hpp b/src/duckdb/src/include/duckdb/function/scalar/geometry_functions.hpp index e96916f10..6aad70c7a 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/geometry_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/geometry_functions.hpp @@ -25,6 +25,16 @@ struct StGeomfromwkbFun { static ScalarFunction GetFunction(); }; +struct StGeogfromwkbFun { + static constexpr const char *Name = "st_geogfromwkb"; + static constexpr const char *Parameters = "wkb"; + static constexpr const char *Description = "Creates a geography from Well-Known Binary (WKB) representation, validating the canonical coordinate ranges"; + static constexpr const char *Example = "ST_GeogFromWKB(X'01010000000000000000000000000000000000000000000000')"; + static constexpr const char *Categories = "geometry"; + + static ScalarFunction GetFunction(); +}; + struct StAswkbFun { static constexpr const char *Name = "st_aswkb"; static constexpr const char *Parameters = "geom"; @@ -32,7 +42,7 @@ struct StAswkbFun { static constexpr const char *Example = "st_aswkb(ST_GeomFromWKB(X'01010000000000000000000000000000000000000000000000000'))"; static constexpr const char *Categories = "geometry"; - static ScalarFunction GetFunction(); + static ScalarFunctionSet GetFunctions(); }; struct StAsbinaryFun { @@ -48,7 +58,7 @@ struct StAstextFun { static constexpr const char *Example = "ST_AsText(ST_GeomFromWKB(X'01010000000000000000000000000000000000000000000000'))"; static constexpr const char *Categories = "geometry"; - static ScalarFunction GetFunction(); + static ScalarFunctionSet GetFunctions(); }; struct StAswktFun { @@ -64,7 +74,7 @@ struct StIntersectsExtentFun { static constexpr const char *Example = "'POINT(5 5)'::GEOMETRY && 'LINESTRING(0 0, 10 20)'::GEOMETRY;"; static constexpr const char *Categories = "geometry"; - static ScalarFunction GetFunction(); + static ScalarFunctionSet GetFunctions(); }; struct StIntersectsExtentFunAlias { @@ -80,7 +90,7 @@ struct StCrsFun { static constexpr const char *Example = ""; static constexpr const char *Categories = "geometry"; - static ScalarFunction GetFunction(); + static ScalarFunctionSet GetFunctions(); }; struct StSetcrsFun { @@ -90,7 +100,7 @@ struct StSetcrsFun { static constexpr const char *Example = ""; static constexpr const char *Categories = "geometry"; - static ScalarFunction GetFunction(); + static ScalarFunctionSet GetFunctions(); }; struct VertexExtractFun { @@ -100,7 +110,7 @@ struct VertexExtractFun { static constexpr const char *Example = "vertex_extract('POINT(1 2 3)', 'Z')"; static constexpr const char *Categories = "geometry"; - static ScalarFunction GetFunction(); + static ScalarFunctionSet GetFunctions(); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/scalar/nested_functions.hpp b/src/duckdb/src/include/duckdb/function/scalar/nested_functions.hpp index 284132e7a..db67b69bc 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/nested_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/nested_functions.hpp @@ -66,7 +66,7 @@ struct VariableReturnBindData : public FunctionData { auto &other = other_p.Cast(); return stype == other.stype; } - static void Serialize(Serializer &serializer, const optional_ptr bind_data, + static void Serialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { auto &info = bind_data->Cast(); serializer.WriteProperty(100, "variable_return_type", info.stype); diff --git a/src/duckdb/src/include/duckdb/function/scalar/regexp.hpp b/src/duckdb/src/include/duckdb/function/scalar/regexp.hpp index ae8a52307..27b3d82b0 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/regexp.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/regexp.hpp @@ -40,7 +40,7 @@ struct RegexpExtractAll { static void Execute(DataChunk &args, ExpressionState &state, Vector &result); static unique_ptr Bind(BindScalarFunctionInput &input); static unique_ptr InitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data); + optional_ptr bind_data); }; struct RegexpBaseBindData : public FunctionData { @@ -78,7 +78,7 @@ struct RegexpExtractAllStruct { static void Execute(DataChunk &args, ExpressionState &state, Vector &result); static unique_ptr Bind(BindScalarFunctionInput &input); static unique_ptr InitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data); + optional_ptr bind_data); }; struct RegexpMatchesBindData : public RegexpBaseBindData { @@ -169,7 +169,7 @@ struct RegexStringPieceArgs { }; struct RegexLocalState : public FunctionLocalState { - explicit RegexLocalState(RegexpBaseBindData &info, bool extract_all = false) + explicit RegexLocalState(const RegexpBaseBindData &info, bool extract_all = false) : constant_pattern(duckdb_re2::StringPiece(info.constant_string.c_str(), info.constant_string.size()), info.options) { if (!constant_pattern.ok()) { @@ -190,7 +190,7 @@ struct RegexLocalState : public FunctionLocalState { }; unique_ptr RegexInitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data); + optional_ptr bind_data); unique_ptr RegexpMatchesBind(BindScalarFunctionInput &input); } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/scalar/strftime_format.hpp b/src/duckdb/src/include/duckdb/function/scalar/strftime_format.hpp index d4fcacd70..f431ed528 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/strftime_format.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/strftime_format.hpp @@ -96,18 +96,18 @@ struct StrTimeFormat { }; struct StrfTimeFormat : public StrTimeFormat { // NOLINT: work-around bug in clang-tidy - DUCKDB_API idx_t GetLength(date_t date, dtime_t time, int32_t utc_offset, const char *tz_name); + DUCKDB_API idx_t GetLength(date_t date, dtime_t time, int32_t utc_offset, const char *tz_name) const; DUCKDB_API idx_t GetLength(date_t date, int32_t data[8], const char *tz_name) const; DUCKDB_API void FormatStringNS(date_t date, int32_t data[8], const char *tz_name, char *target) const; - DUCKDB_API void FormatString(date_t date, int32_t data[8], const char *tz_name, char *target); - void FormatString(date_t date, dtime_t time, char *target); + DUCKDB_API void FormatString(date_t date, int32_t data[8], const char *tz_name, char *target) const; + void FormatString(date_t date, dtime_t time, char *target) const; DUCKDB_API static string Format(timestamp_t timestamp, const string &format); - DUCKDB_API void ConvertDateVector(const Vector &input, Vector &result); - DUCKDB_API void ConvertTimestampVector(const Vector &input, Vector &result); - DUCKDB_API void ConvertTimestampNSVector(const Vector &input, Vector &result); + DUCKDB_API void ConvertDateVector(const Vector &input, Vector &result) const; + DUCKDB_API void ConvertTimestampVector(const Vector &input, Vector &result) const; + DUCKDB_API void ConvertTimestampNSVector(const Vector &input, Vector &result) const; protected: //! The variable-length specifiers. To determine total string size, these need to be checked. diff --git a/src/duckdb/src/include/duckdb/function/scalar_function.hpp b/src/duckdb/src/include/duckdb/function/scalar_function.hpp index 4a7c909de..e0f33a21e 100644 --- a/src/duckdb/src/include/duckdb/function/scalar_function.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar_function.hpp @@ -62,14 +62,15 @@ class ScalarFunctionCatalogEntry; struct StatementProperties; struct FunctionStatisticsPruneInput { - FunctionStatisticsPruneInput(const BoundFunctionExpression &function_p, optional_ptr bind_data_p, + FunctionStatisticsPruneInput(const BoundFunctionExpression &function_p, + optional_ptr bind_data_p, const vector> &child_stats_p) : function(function_p), bind_data(bind_data_p), child_stats(child_stats_p) { } //! The bound function expression being checked (gives access to the argument expressions) const BoundFunctionExpression &function; - optional_ptr bind_data; + optional_ptr bind_data; //! Statistics for each function argument (an entry is null if it could not be derived for that argument) const vector> &child_stats; @@ -81,30 +82,31 @@ struct FunctionStatisticsPruneInput { }; struct FunctionStatisticsInput { - FunctionStatisticsInput(BoundFunctionExpression &expr_p, optional_ptr bind_data_p, + FunctionStatisticsInput(BoundFunctionExpression &expr_p, cow_ptr &bind_data_p, vector &child_stats_p, unique_ptr *expr_ptr_p) : expr(expr_p), bind_data(bind_data_p), child_stats(child_stats_p), expr_ptr(expr_ptr_p) { } BoundFunctionExpression &expr; - optional_ptr bind_data; + //! The bind data of the function - use write() to modify it + cow_ptr &bind_data; vector &child_stats; unique_ptr *expr_ptr; }; struct FunctionModifiedDatabasesInput { - FunctionModifiedDatabasesInput(optional_ptr bind_data_p, StatementProperties &properties) + FunctionModifiedDatabasesInput(optional_ptr bind_data_p, StatementProperties &properties) : bind_data(bind_data_p), properties(properties) { } - optional_ptr bind_data; + optional_ptr bind_data; StatementProperties &properties; }; struct FunctionBindExpressionInput { FunctionBindExpressionInput(ClientContext &context_p, BoundScalarFunction &bound_function, - optional_ptr bind_data_p, vector> &children_p, - optional_ptr binder_p = nullptr, + optional_ptr bind_data_p, + vector> &children_p, optional_ptr binder_p = nullptr, optional_ptr decimal_width_limit_p = nullptr) : context(context_p), bound_function(bound_function), bind_data(bind_data_p), children(children_p), binder(binder_p), decimal_width_limit(decimal_width_limit_p) { @@ -112,7 +114,7 @@ struct FunctionBindExpressionInput { ClientContext &context; BoundScalarFunction &bound_function; - optional_ptr bind_data; + optional_ptr bind_data; vector> &children; //! The binder of the query the function is bound in, if any optional_ptr binder; @@ -132,13 +134,13 @@ struct FunctionUnbindInput { }; struct FunctionToStringInput { - FunctionToStringInput(const BoundScalarFunction &bound_function, optional_ptr bind_data_p, + FunctionToStringInput(const BoundScalarFunction &bound_function, optional_ptr bind_data_p, const vector> &children_p) : bound_function(bound_function), bind_data(bind_data_p), children(children_p) { } const BoundScalarFunction &bound_function; - optional_ptr bind_data; + optional_ptr bind_data; const vector> &children; const Expression &GetChild(idx_t i) const { @@ -158,7 +160,7 @@ typedef void (*resolve_scalar_types_t)(ResolveScalarFunctionTypesInput &input); //! The type to initialize a thread local state for the scalar function typedef unique_ptr (*init_local_state_t)(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data); + optional_ptr bind_data); //! The type to directly access the selection vector of a scalar function typedef idx_t (*scalar_function_select_t)(DataChunk &args, ExpressionState &state, optional_ptr sel, @@ -174,7 +176,7 @@ typedef LogicalType (*bind_lambda_function_t)(ClientContext &context, const vect //! The type to bind lambda-specific parameter types typedef void (*get_modified_databases_t)(ClientContext &context, FunctionModifiedDatabasesInput &input); -typedef void (*function_serialize_t)(Serializer &serializer, const optional_ptr bind_data, +typedef void (*function_serialize_t)(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function); typedef unique_ptr (*function_deserialize_t)(Deserializer &deserializer, BoundScalarFunction &function); @@ -388,7 +390,7 @@ class BaseScalarFunction { function_info = std::move(info); } template - void SetExtraFunctionInfo(ARGS &&... args) { + void SetExtraFunctionInfo(ARGS &&...args) { function_info = make_shared_ptr(std::forward(args)...); } shared_ptr GetFunctionInfo() const { diff --git a/src/duckdb/src/include/duckdb/function/table/native_scan_job.hpp b/src/duckdb/src/include/duckdb/function/table/native_scan_job.hpp new file mode 100644 index 000000000..4d152852c --- /dev/null +++ b/src/duckdb/src/include/duckdb/function/table/native_scan_job.hpp @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/function/table/native_scan_job.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/parallel/scan_read_ahead.hpp" +#include "duckdb/storage/table/scan_state.hpp" + +namespace duckdb { + +//! Unordered read-ahead carries storage ranges, leaving decoding state with its worker. +struct NativeScanJob : public ScanReadAheadJob { + explicit NativeScanJob(BlockAllocator &allocator) : allocator(allocator) { + } + ~NativeScanJob() override { + SettleIO(); + } + optional_idx ResolveAffinity() override { + auto hint = blocks.GetCachedShard(allocator); + blocks.blocks.clear(); + return hint; + } + idx_t GetMemoryUsage() const override { + return sizeof(*this) + blocks.blocks.capacity() * sizeof(shared_ptr); + } + + TableScanAssignment assignment; + PrefetchState blocks; + BlockAllocator &allocator; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp b/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp index d1fb227b4..5ba61d042 100644 --- a/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp +++ b/src/duckdb/src/include/duckdb/function/table/system_catalog_scanner.hpp @@ -47,16 +47,25 @@ struct SystemCatalogScannerStats { idx_t entries_scanned = 0; }; +//! Names of a function's identity columns; nullptr means the function has no such column. A column counts only when +//! its declared type is the one the filters are evaluated against (VARCHAR for names, BIGINT for oids). The catalog +//! and schema names default to the ones every system function uses; the entry columns default to none. Pointers must +//! outlive the CreateBindData call (string literals in practice). +struct SystemCatalogIdentityColumns { + const char *database_name = "database_name"; + const char *database_oid = "database_oid"; + const char *schema_name = "schema_name"; + const char *schema_oid = "schema_oid"; + const char *entry_name = nullptr; + const char *entry_oid = nullptr; +}; + class SystemCatalogScanner { public: - //! Bind helper: locate the identity columns by name in `names`. A column counts only when its declared type is - //! the one the filters are evaluated against (VARCHAR for names, BIGINT for oids). `entry_name_column` and - //! `entry_oid_column` name the function's entry identity columns (e.g. "table_name", "table_oid"); pass nullptr - //! for a function without them. Always returns non-null bind data. - static unique_ptr CreateBindData(const vector &names, - const vector &return_types, - const char *entry_name_column = nullptr, - const char *entry_oid_column = nullptr); + //! Bind helper: locate the identity columns by name in `names`. Always returns non-null bind data. + static unique_ptr + CreateBindData(const vector &names, const vector &return_types, + const SystemCatalogIdentityColumns &columns = SystemCatalogIdentityColumns()); //! Init helper: the schemas that satisfy the pushed-down catalog and schema filters, in Catalog::GetAllSchemas //! order. Without such filters this is exactly Catalog::GetAllSchemas(context). static vector> GetSchemas(ClientContext &context, TableFunctionInitInput &input, diff --git a/src/duckdb/src/include/duckdb/function/table_function.hpp b/src/duckdb/src/include/duckdb/function/table_function.hpp index d9c88962b..15cdf2e82 100644 --- a/src/duckdb/src/include/duckdb/function/table_function.hpp +++ b/src/duckdb/src/include/duckdb/function/table_function.hpp @@ -20,6 +20,7 @@ #include "duckdb/parallel/async_result.hpp" #include "duckdb/common/exception/binder_exception.hpp" #include "duckdb/common/enums/order_preservation_type.hpp" +#include "duckdb/common/enums/pipeline_execution_order.hpp" #include "duckdb/common/enums/statement_type.hpp" namespace duckdb { @@ -166,6 +167,9 @@ struct TableFunctionInitInput { optional_ptr op; //! (Optional) Set when a multi-file scan initializes this function to read one of its files optional_ptr multi_file_input; + //! Runtime pipeline requirements, supplied only when initializing the source's local state. + PipelineExecutionOrder execution_order = PipelineExecutionOrder::ORDERED; + idx_t max_threads = 1; bool CanRemoveFilterColumns() const { if (projection_ids.empty()) { @@ -215,7 +219,7 @@ struct TableFunctionPartitionInput { }; struct TableFunctionProjectionExpressionInput { - const LogicalGet &get; + LogicalGet &get; const Expression &expr; //! Position of pushed down column within get, usage: get.GetColumnIds()[column_index] ProjectionIndex column_index; @@ -268,13 +272,13 @@ struct GetPartitionStatsInput { struct TableFunctionGetBindInfoInput { public: - TableFunctionGetBindInfoInput(ClientContext &context, optional_ptr bind_data_p) + TableFunctionGetBindInfoInput(ClientContext &context, optional_ptr bind_data_p) : context(context), bind_data(bind_data_p) { } public: ClientContext &context; - optional_ptr bind_data; + optional_ptr bind_data; }; struct TableFunctionGetMetricsInput { @@ -385,7 +389,7 @@ typedef unique_ptr (*table_function_cardinality_t)(ClientContext const FunctionData *bind_data); typedef void (*table_function_get_metrics_t)(TableFunctionGetMetricsInput &input); typedef void (*table_function_pushdown_complex_filter_t)(ClientContext &context, LogicalGet &get, - FunctionData *bind_data, + optional_ptr bind_data, vector> &filters); typedef bool (*table_function_pushdown_expression_t)(ClientContext &context, const LogicalGet &get, Expression &expr); typedef InsertionOrderPreservingMap (*table_function_to_string_t)(TableFunctionToStringInput &input); @@ -399,7 +403,7 @@ struct TableFunctionToSQLResult { //! Return an owned table reference without executing the source, or a reason why reconstruction is unsupported. typedef TableFunctionToSQLResult (*table_function_to_sql_t)(ClientContext &context, const LogicalGet &get); -typedef void (*table_function_serialize_t)(Serializer &serializer, const optional_ptr bind_data, +typedef void (*table_function_serialize_t)(Serializer &serializer, const optional_ptr bind_data, const BoundTableFunction &function); typedef unique_ptr (*table_function_deserialize_t)(Deserializer &deserializer, BoundTableFunction &function); @@ -412,17 +416,18 @@ typedef TablePartitionInfo (*table_function_get_partition_info_t)(ClientContext typedef vector (*table_function_get_partition_stats_t)(ClientContext &context, GetPartitionStatsInput &input); +//! Called while binding: the bind data is not shared yet and may be modified typedef virtual_column_map_t (*table_function_get_virtual_columns_t)(ClientContext &context, optional_ptr bind_data); typedef vector (*table_function_get_row_id_columns)(ClientContext &context, - optional_ptr bind_data); + optional_ptr bind_data); typedef void (*table_function_set_scan_order)(unique_ptr order_options, - optional_ptr bind_data); + cow_ptr &bind_data); typedef void (*table_function_set_partitions_to_scan_t)(vector partition_indices, - optional_ptr bind_data); + cow_ptr &bind_data); //! When to call init_global to initialize the table function enum class TableFunctionInitialization { INITIALIZE_ON_EXECUTE, INITIALIZE_ON_SCHEDULE }; diff --git a/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp b/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp index 1a9628271..443c45174 100644 --- a/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp +++ b/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp @@ -70,6 +70,7 @@ struct VariantNormalizer { static void VisitBlob(const string_t &blob, VariantNormalizerState &state); static void VisitBignum(const string_t &bignum, VariantNormalizerState &state); static void VisitGeometry(const string_t &geom, VariantNormalizerState &state); + static void VisitGeography(const string_t &geog, VariantNormalizerState &state); static void VisitBitstring(const string_t &bits, VariantNormalizerState &state); template diff --git a/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp b/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp index e48911771..f9bab6099 100644 --- a/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp +++ b/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp @@ -86,6 +86,9 @@ struct ValueConverter { static Value VisitGeometry(const string_t &str) { return Value::GEOMETRY(const_data_ptr_cast(str.GetData()), str.GetSize()); } + static Value VisitGeography(const string_t &str) { + return Value::GEOGRAPHY(const_data_ptr_cast(str.GetData()), str.GetSize()); + } static Value VisitBitstring(const string_t &str) { return Value::BIT(const_data_ptr_cast(str.GetData()), str.GetSize()); } diff --git a/src/duckdb/src/include/duckdb/function/window/window_collection.hpp b/src/duckdb/src/include/duckdb/function/window/window_collection.hpp index 280dcbbaa..ad47fa02e 100644 --- a/src/duckdb/src/include/duckdb/function/window/window_collection.hpp +++ b/src/duckdb/src/include/duckdb/function/window/window_collection.hpp @@ -14,6 +14,7 @@ #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/execution/expression_executor.hpp" #include @@ -201,6 +202,8 @@ class WindowCollectionChunkScanner { //! Return a struct type for comparing keys LogicalType PrefixStructType(column_t end, column_t begin = 0); + //! Return the struct type for comparing the keys [begin, end) of the given column types + static LogicalType PrefixStructType(const vector &types, column_t end, column_t begin = 0); //! Reference the chunk into a struct vector matching the keys static void ReferenceStructColumns(DataChunk &chunk, Vector &vec, column_t end, column_t begin = 0); @@ -211,8 +214,9 @@ class WindowCollectionChunkScanner { }; template -static void WindowDeltaScanner(ColumnDataCollection &collection, idx_t block_begin, idx_t block_end, - const vector &scan_cols, const idx_t key_count, OP operation) { +static void WindowDeltaScanner(Context &context, const Expression &distinct_from_expr, ColumnDataCollection &collection, + idx_t block_begin, idx_t block_end, const vector &scan_cols, + const idx_t key_count, OP operation) { // Stop if there is no work to do if (!collection.Count()) { return; @@ -237,6 +241,9 @@ static void WindowDeltaScanner(ColumnDataCollection &collection, idx_t block_beg const auto key_type = scanner.PrefixStructType(key_count); Vector compare_curr(key_type); Vector compare_prev(key_type); + DataChunk compare; + compare.InitializeEmpty({key_type, key_type}); + ExpressionExecutor distinct_from(context, distinct_from_expr); bool boundary_compare = (block_begin > 0); idx_t row_idx = 1; @@ -293,8 +300,10 @@ static void WindowDeltaScanner(ColumnDataCollection &collection, idx_t block_beg scanner.ReferenceStructColumns(*prev, compare_prev, key_count); scanner.ReferenceStructColumns(*curr, compare_curr, key_count); - const auto ndistinct = - VectorOperations::DistinctFrom(compare_curr, compare_prev, nullptr, count, &distinct, &matching); + compare.data[0].Slice(compare_curr, 0, count); + compare.data[1].Slice(compare_prev, 0, count); + compare.CheckCardinality(count); + const auto ndistinct = distinct_from.SelectExpression(compare, &distinct, &matching, nullptr, count); // If n is 0, neither SV has been filled in? auto match_sel = ndistinct ? &matching : FlatVector::IncrementalSelectionVector(); diff --git a/src/duckdb/src/include/duckdb/function/window/window_index_tree.hpp b/src/duckdb/src/include/duckdb/function/window/window_index_tree.hpp index 058b9929f..9422c1a7a 100644 --- a/src/duckdb/src/include/duckdb/function/window/window_index_tree.hpp +++ b/src/duckdb/src/include/duckdb/function/window/window_index_tree.hpp @@ -19,7 +19,7 @@ class WindowIndexTreeLocalState : public WindowMergeSortTreeLocalState { WindowIndexTreeLocalState(ExecutionContext &context, WindowIndexTree &index_tree); //! Process sorted leaf data - void BuildLeaves() override; + void BuildLeaves(Context &context) override; //! The index tree we are building WindowIndexTree &index_tree; diff --git a/src/duckdb/src/include/duckdb/function/window/window_match_recognize.hpp b/src/duckdb/src/include/duckdb/function/window/window_match_recognize.hpp index a81bf89c6..afdfe686d 100644 --- a/src/duckdb/src/include/duckdb/function/window/window_match_recognize.hpp +++ b/src/duckdb/src/include/duckdb/function/window/window_match_recognize.hpp @@ -15,7 +15,7 @@ namespace duckdb { struct WindowMatchRecognizeExecutor { static unique_ptr Bind(BindWindowFunctionInput &input); - static void Serialize(Serializer &serializer, const optional_ptr bind_data, + static void Serialize(Serializer &serializer, const optional_ptr bind_data, const BoundWindowFunction &function); static unique_ptr Deserialize(Deserializer &deserializer, BoundWindowFunction &function); static void GetBounds(WindowBoundsSet &required, const BoundWindowExpression &wexpr); diff --git a/src/duckdb/src/include/duckdb/function/window/window_merge_sort_tree.hpp b/src/duckdb/src/include/duckdb/function/window/window_merge_sort_tree.hpp index ac63f8e1c..644b58026 100644 --- a/src/duckdb/src/include/duckdb/function/window/window_merge_sort_tree.hpp +++ b/src/duckdb/src/include/duckdb/function/window/window_merge_sort_tree.hpp @@ -29,7 +29,7 @@ class WindowMergeSortTreeLocalState : public LocalSinkState { //! Sort the data void Finalize(ExecutionContext &context, InterruptState &interrupt); //! Process sorted leaf data - virtual void BuildLeaves() = 0; + virtual void BuildLeaves(Context &context) = 0; //! The index tree we are building WindowMergeSortTree &window_tree; @@ -78,6 +78,8 @@ class WindowMergeSortTree { vector scan_cols; //! The sort key columns vector key_cols; + //! DISTINCT FROM comparison of the sort keys + unique_ptr key_distinct_from; //! The sort specification unique_ptr sort; //! The sorted data diff --git a/src/duckdb/src/include/duckdb/function/window/window_naive_aggregator.hpp b/src/duckdb/src/include/duckdb/function/window/window_naive_aggregator.hpp index 90d4a52be..f53262053 100644 --- a/src/duckdb/src/include/duckdb/function/window/window_naive_aggregator.hpp +++ b/src/duckdb/src/include/duckdb/function/window/window_naive_aggregator.hpp @@ -17,7 +17,8 @@ class WindowAggregateExecutor; // Used for validation class WindowNaiveAggregator : public WindowAggregator { public: - WindowNaiveAggregator(const WindowAggregateExecutor &executor, WindowSharedExpressions &shared); + WindowNaiveAggregator(const WindowAggregateExecutor &executor, WindowSharedExpressions &shared, + ClientContext &client); ~WindowNaiveAggregator() override; unique_ptr GetLocalState(ExecutionContext &context, const GlobalSinkState &gstate) const override; @@ -28,6 +29,8 @@ class WindowNaiveAggregator : public WindowAggregator { //! The parent executor const WindowAggregateExecutor &executor; + //! Whether two rows have the same arguments, over [left arguments..., right arguments...] (can be nullptr) + unique_ptr args_equal; //! The column indices of any ORDER BY argument expressions vector arg_order_idx; }; diff --git a/src/duckdb/src/include/duckdb/function/window_function.hpp b/src/duckdb/src/include/duckdb/function/window_function.hpp index 9655a31d2..98bcdbc81 100644 --- a/src/duckdb/src/include/duckdb/function/window_function.hpp +++ b/src/duckdb/src/include/duckdb/function/window_function.hpp @@ -140,7 +140,7 @@ typedef void (*window_stream_function_t)(ExecutionContext &context, DataChunk &i idx_t delayed_capacity, Vector &result, WindowExecutorStreamingState &lstate); //! Serialization of the binding data (if any) -typedef void (*window_serialize_t)(Serializer &serializer, const optional_ptr bind_data, +typedef void (*window_serialize_t)(Serializer &serializer, const optional_ptr bind_data, const BoundWindowFunction &function); typedef unique_ptr (*window_deserialize_t)(Deserializer &deserializer, BoundWindowFunction &function); @@ -301,7 +301,7 @@ class BaseWindowFunction { function_info = std::move(info); } template - auto SetExtraFunctionInfo(ARGS &&... args) -> void { + auto SetExtraFunctionInfo(ARGS &&...args) -> void { function_info = make_shared_ptr(std::forward(args)...); } auto GetFunctionInfo() const -> shared_ptr { diff --git a/src/duckdb/src/include/duckdb/main/attached_database.hpp b/src/duckdb/src/include/duckdb/main/attached_database.hpp index 7287d53b0..f8b1ffc37 100644 --- a/src/duckdb/src/include/duckdb/main/attached_database.hpp +++ b/src/duckdb/src/include/duckdb/main/attached_database.hpp @@ -213,6 +213,13 @@ class AttachedDatabase : public CatalogEntry, public enable_shared_from_this &attached_database, ClientContext &context); + //! A database marked as detached closes with the action recorded by MarkDetached instead. + static void InvokeCloseIfLastReference(shared_ptr &attached_database, + DatabaseCloseAction close_action); + //! The close action a detach issued by this context uses. + static DatabaseCloseAction GetDetachCloseAction(ClientContext &context); + //! Mark as detached: whoever releases the last reference closes the database with close_action. + void MarkDetached(DatabaseCloseAction close_action); //! Obtain a reference unless closing the database has already started. static shared_ptr TryGetReference(const weak_ptr &attached_database); @@ -232,6 +239,8 @@ class AttachedDatabase : public CatalogEntry, public enable_shared_from_this close_lock; optional_idx vacuum_rebuild_threshold; unordered_map attach_options; diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp index c667d34ba..a85411631 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp @@ -94,7 +94,7 @@ inline void SetStringOut(const char **out, idx_t *out_length, const Identifier & //! reads as all-empty entries. class string_view_array { public: - string_view_array(const char **ptrs, const idx_t *lengths, idx_t count) + string_view_array(const char *const *ptrs, const idx_t *lengths, idx_t count) : ptrs(ptrs), lengths(lengths), count(count) { } @@ -106,7 +106,7 @@ class string_view_array { std::string_view operator[](idx_t i) const; private: - const char **ptrs; + const char *const *ptrs; const idx_t *lengths; idx_t count; }; @@ -346,6 +346,8 @@ class CV2FileSystem { class CV2Instance { public: CV2Instance(CV2Environment &env, DBConfig &startup_config); + //! A handle to a database shared through the environment's instance cache, see instance_open_shared. + CV2Instance(CV2Environment &env, shared_ptr shared_database); //! Attaches the database at `path` under `name` (derived from the path when empty), like ATTACH, optionally as //! the default for new connections. @@ -507,6 +509,11 @@ void SetScalarFunctionProperty(FunctionProperties &props, DUCKDB_V2_FUNCTION_PRO DUCKDB_V2_FUNCTION_PROPERTY_VALUE value); void SetAggregateFunctionProperty(AggregateFunctionProperties &props, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, DUCKDB_V2_FUNCTION_PROPERTY_VALUE value); +//! Set / get a generic, named function property; shared by the scalar and aggregate entry points +void SetGenericFunctionProperty(FunctionProperties &props, const char *name, idx_t name_length, const Value &value); +//! Returns an owned copy of the property value, or nullptr if the property is not set +auto GetGenericFunctionProperty(const FunctionProperties &props, const char *name, idx_t name_length) + -> duckdb_v2_value_handle; using CV2FunctionSignature = duckdb::FunctionSignature; @@ -888,6 +895,17 @@ inline void InvokeTextSink(duckdb_v2_text_sink_fn sink, std::string_view text, v } } +//! Runs a callback taking an error slot, and throws what it reports. +template +void InvokeWithErrorSlot(FUNC &&fn) { + CV2ErrorInfo info; + auto handle = Convert(&info); + fn(&handle); + if (info.HasError()) { + info.ThrowAsException(); + } +} + //---------------------------------------------------------------------------------------------------------------------- // Caller-supplied output buffers //---------------------------------------------------------------------------------------------------------------------- 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 f0fc3cf26..7b0844662 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 @@ -94,11 +94,11 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_error_info_set_text) (duckdb_v2_error_info_handle info, const char *text, idx_t text_length); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_id) - (duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char **param_names, + (duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char *const *param_names, const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_name) - (duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char **param_names, + (duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char *const *param_names, const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_text) @@ -113,8 +113,8 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_instance_create) (duckdb_v2_environment_handle env, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_create_with_options) - (duckdb_v2_environment_handle env, const char **option_names, const idx_t *option_names_lengths, - const char **option_values, const idx_t *option_values_lengths, idx_t option_count, + (duckdb_v2_environment_handle env, const char *const *option_names, const idx_t *option_names_lengths, + const char *const *option_values, const idx_t *option_values_lengths, idx_t option_count, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_instance_destroy)(duckdb_v2_instance_handle *instance); DUCKDB_V2_ERROR(*duckdb_v2_instance_detach) @@ -186,7 +186,7 @@ typedef struct { (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, duckdb_v2_schema_handle *out_schema, duckdb_v2_schema_handle *out_parameters, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_execute) - (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_statement_iterator_destroy)(duckdb_v2_statement_iterator_handle *iterator); @@ -249,7 +249,7 @@ typedef struct { (duckdb_v2_factory_handle factory, int16_t in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_struct) - (duckdb_v2_factory_handle factory, const char **names, const idx_t *names_lengths, + (duckdb_v2_factory_handle factory, const char *const *names, const idx_t *names_lengths, const duckdb_v2_value_handle *children, idx_t field_count, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_time) @@ -726,7 +726,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_instance_register_replacement_scan) (duckdb_v2_instance_handle instance, duckdb_v2_replacement_scan_handle scan, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_create) - (const char **parts, const idx_t *parts_lengths, idx_t part_count, duckdb_v2_qname_handle *name, + (const char *const *parts, const idx_t *parts_lengths, idx_t part_count, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_qname_destroy)(duckdb_v2_qname_handle *name); DUCKDB_V2_ERROR(*duckdb_v2_qname_equals) @@ -762,7 +762,7 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_collection) (duckdb_v2_replacement_scan_info_handle info, duckdb_v2_column_data_collection_handle collection, - const char **column_names, const idx_t *column_names_lengths, idx_t column_count, + const char *const *column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_function_name) (duckdb_v2_replacement_scan_info_handle info, duckdb_v2_qname_handle name, duckdb_v2_error_info_handle *err); @@ -774,7 +774,7 @@ typedef struct { (duckdb_v2_arrow_exporter_handle exporter, duckdb_v2_data_chunk_handle *chunk, bool consume, bool flush, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_arrow_exporter_create) - (duckdb_v2_context_handle context, const duckdb_v2_logical_type_handle *types, const char **names, + (duckdb_v2_context_handle context, const duckdb_v2_logical_type_handle *types, const char *const *names, const idx_t *names_lengths, idx_t count, idx_t batch_size, duckdb_v2_arrow_exporter_handle *out_exporter, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_arrow_exporter_destroy)(duckdb_v2_arrow_exporter_handle *exporter); @@ -786,7 +786,7 @@ typedef struct { (duckdb_v2_arrow_importer_handle importer, struct ArrowArray *array, bool consume, bool flush, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_arrow_importer_create) - (duckdb_v2_context_handle context, struct ArrowSchema *schema, idx_t batch_size, + (duckdb_v2_context_handle context, const struct ArrowSchema *schema, idx_t batch_size, duckdb_v2_arrow_importer_handle *out_importer, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_arrow_importer_destroy)(duckdb_v2_arrow_importer_handle *importer); DUCKDB_V2_ERROR(*duckdb_v2_arrow_importer_get_schema) @@ -998,9 +998,9 @@ typedef struct { duckdb_v2_prepared_statement_handle *out_prepared, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_prepared_statement_destroy)(duckdb_v2_prepared_statement_handle *prepared); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_execute) - (duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, - const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, - duckdb_v2_error_info_handle *err); + (duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_reuses_plan) (duckdb_v2_prepared_statement_handle prepared, bool *out_reuses, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_table_description_destroy)(duckdb_v2_table_description_handle *desc); @@ -1208,11 +1208,11 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_arrow_result_wait) (duckdb_v2_arrow_result_handle result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_execute_arrow) - (duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, - const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, - duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); + (duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_execute_arrow) - (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_set_stats_callback) @@ -1494,8 +1494,8 @@ typedef struct { (duckdb_v2_query_metrics_node_handle node, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_add_collection) (duckdb_v2_sql_statement_handle statement, const char *name, idx_t name_length, - duckdb_v2_column_data_collection_handle collection, const char **column_names, const idx_t *column_names_lengths, - idx_t column_count, duckdb_v2_error_info_handle *err); + duckdb_v2_column_data_collection_handle collection, const char *const *column_names, + const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_add_virtual_column) (duckdb_v2_table_function_handle function, DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_bind_data) @@ -1525,6 +1525,56 @@ typedef struct { (duckdb_v2_stats_handle stats, duckdb_v2_value_handle *value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_stats_set_value) (duckdb_v2_stats_handle stats, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_get_generic_property) + (duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, + duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_set_generic_property) + (duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_get_generic_property) + (duckdb_v2_scalar_function_handle function, const char *name, idx_t name_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_set_generic_property) + (duckdb_v2_scalar_function_handle function, const char *name, idx_t name_length, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); + DUCKDB_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_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_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) + (duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, const char *key, idx_t key_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_object_cache_entry_destroy)(duckdb_v2_object_cache_entry_handle *entry); + DUCKDB_V2_ERROR(*duckdb_v2_object_cache_entry_get_data) + (duckdb_v2_object_cache_entry_handle entry, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_object_cache_get) + (duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, const char *key, idx_t key_length, + duckdb_v2_object_cache_entry_handle *entry, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_object_cache_get_or_create) + (duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, const char *key, idx_t key_length, + duckdb_v2_object_cache_create_callback_fn create, void *create_user_data, + duckdb_v2_object_cache_entry_handle *entry, duckdb_v2_error_info_handle *err); + 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_table_function_set_to_string_callback) + (duckdb_v2_table_function_handle function, duckdb_v2_table_function_to_string_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_to_string_get_bind_data) + (duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_to_string_get_user_data) + (duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_to_string_set) + (duckdb_v2_table_function_to_string_info_handle info, const char *key, idx_t key_length, const char *value, + idx_t value_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_instance_open_shared) + (duckdb_v2_environment_handle env, const char *path, idx_t path_length, const char *const *option_names, + const idx_t *option_names_lengths, const char *const *option_values, const idx_t *option_values_lengths, + idx_t option_count, duckdb_v2_instance_init_callback_fn init, void *init_user_data, + duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); } duckdb_ext_api_v2; //===--------------------------------------------------------------------===// @@ -2219,6 +2269,24 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_stats_assign = duckdb_v2_stats_assign; result.duckdb_v2_stats_get_value = duckdb_v2_stats_get_value; result.duckdb_v2_stats_set_value = duckdb_v2_stats_set_value; + result.duckdb_v2_aggregate_function_get_generic_property = duckdb_v2_aggregate_function_get_generic_property; + result.duckdb_v2_aggregate_function_set_generic_property = duckdb_v2_aggregate_function_set_generic_property; + 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_context_get_object_cache = duckdb_v2_context_get_object_cache; + 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; + result.duckdb_v2_object_cache_entry_get_data = duckdb_v2_object_cache_entry_get_data; + 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_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; + result.duckdb_v2_table_function_to_string_set = duckdb_v2_table_function_to_string_set; + result.duckdb_v2_instance_open_shared = duckdb_v2_instance_open_shared; return result; } diff --git a/src/duckdb/src/include/duckdb/main/client_config.hpp b/src/duckdb/src/include/duckdb/main/client_config.hpp index c1229100e..117aa6db3 100644 --- a/src/duckdb/src/include/duckdb/main/client_config.hpp +++ b/src/duckdb/src/include/duckdb/main/client_config.hpp @@ -57,9 +57,6 @@ struct ClientConfig { //! Held by pointer so that copying a ClientConfig stays possible; a ReplacementScan owns its data uniquely. vector> replacement_scans; - //! The maximum amount of memory to keep buffered in a streaming query result. Default: 10mb. - idx_t max_streaming_buffer_size = idx_t(10) * 1024 * 1024; - //! The maximum memory for query intermediates (sorts, hash tables) per connection (in bytes). Default: Global //! memory limit. optional_idx operator_memory_limit; @@ -98,9 +95,6 @@ struct ClientConfig { bool GetUserVariable(const Identifier &name, Value &result); bool GetUserVariable(const string &name, Value &result); void ResetUserVariable(const String &name); - -public: - void SetDefaultStreamingBufferSize(); }; struct ScopedConfigSetting { diff --git a/src/duckdb/src/include/duckdb/main/client_context.hpp b/src/duckdb/src/include/duckdb/main/client_context.hpp index b3225e048..4ee25e5d4 100644 --- a/src/duckdb/src/include/duckdb/main/client_context.hpp +++ b/src/duckdb/src/include/duckdb/main/client_context.hpp @@ -50,7 +50,6 @@ class PreparedStatement; class PreparedStatementData; class StatementIterator; struct PreprocessedStatement; -class Relation; class BufferedFileWriter; class QueryProfiler; class ClientContextLock; @@ -167,10 +166,10 @@ class ClientContext : public enable_shared_from_this { DUCKDB_API void SuppressInterrupts(); DUCKDB_API void CancelTransaction(); + //! InterruptCheck that only reads the clock for the timeout every 256th call, for hot loops + DUCKDB_API void FastInterruptCheck() const; //! Check for interrupt or timeout, throws InterruptException if triggered DUCKDB_API void InterruptCheck() const; - //! InterruptCheck that reads the clock on every call, for waits that block between checks - DUCKDB_API void BlockingInterruptCheck() const; //! Enable query profiling DUCKDB_API void EnableProfiling(); @@ -225,19 +224,6 @@ class ClientContext : public enable_shared_from_this { //! Appends a ColumnDataCollection to the described table. DUCKDB_API void Append(TableDescription &description, ColumnDataCollection &collection); - //! Try to bind a relation in the current client context; either throws an exception or fills the result_columns - //! list with the set of returned columns - DUCKDB_API void TryBindRelation(Relation &relation, vector &result_columns); - - //! Internal function for try bind relation. It does not require a client-context lock. - DUCKDB_API void InternalTryBindRelation(Relation &relation, vector &result_columns); - - //! Non-blocking. Submits a relation and returns its handle - DUCKDB_API unique_ptr Submit(const shared_ptr &relation, - const QueryParameters &query_parameters); - //! Blocking. Runs a relation to completion and returns its handle - DUCKDB_API unique_ptr Execute(const shared_ptr &relation); - //! Prepare a query. A statement that expands into several is kept as written and expanded at each execution, so //! its metadata is known only from the result DUCKDB_API unique_ptr Prepare(const string &query); @@ -341,6 +327,9 @@ class ClientContext : public enable_shared_from_this { DUCKDB_API LogicalType ParseLogicalType(const string &type); private: + //! Rolls back the active transaction (if any) without throwing, while the context is still fully alive + void RollbackActiveTransaction(); + friend class Parser; friend class ParseIterator; ParserOptions GetParserOptions(); @@ -466,9 +455,6 @@ class ClientContext : public enable_shared_from_this { QueryResultState FailQueryInternal(ClientContextLock &lock, BaseQueryResult &result, ErrorData error); void UpdateProgressInternal(QueryResultState state); - unique_ptr SubmitInternal(ClientContextLock &, const shared_ptr &relation, - const QueryParameters &query_parameters); - template unique_ptr ErrorResult(ErrorData error, const string &query = string()); diff --git a/src/duckdb/src/include/duckdb/main/client_context_state.hpp b/src/duckdb/src/include/duckdb/main/client_context_state.hpp index 0a704bcd6..7e74d8883 100644 --- a/src/duckdb/src/include/duckdb/main/client_context_state.hpp +++ b/src/duckdb/src/include/duckdb/main/client_context_state.hpp @@ -104,7 +104,7 @@ class ClientContextState { class RegisteredStateManager { public: template - shared_ptr GetOrCreate(const string &key, ARGS &&... args) { + shared_ptr GetOrCreate(const string &key, ARGS &&...args) { lock_guard l(lock); auto lookup = registered_state.find(key); if (lookup != registered_state.end()) { diff --git a/src/duckdb/src/include/duckdb/main/client_context_wrapper.hpp b/src/duckdb/src/include/duckdb/main/client_context_wrapper.hpp deleted file mode 100644 index 41c102255..000000000 --- a/src/duckdb/src/include/duckdb/main/client_context_wrapper.hpp +++ /dev/null @@ -1,32 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/client_context_wrapper.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/shared_ptr.hpp" -#include "duckdb/parser/column_definition.hpp" - -namespace duckdb { - -class ClientContext; - -class Relation; - -class ClientContextWrapper { -public: - virtual ~ClientContextWrapper() = default; - explicit ClientContextWrapper(const shared_ptr &context); - shared_ptr GetContext(); - shared_ptr TryGetContext(); - virtual void TryBindRelation(Relation &relation, vector &columns); - -private: - weak_ptr client_context; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/config.hpp b/src/duckdb/src/include/duckdb/main/config.hpp index 1c8804d43..8da914318 100644 --- a/src/duckdb/src/include/duckdb/main/config.hpp +++ b/src/duckdb/src/include/duckdb/main/config.hpp @@ -29,7 +29,6 @@ #include "duckdb/function/cast/default_casts.hpp" #include "duckdb/function/replacement_scan.hpp" #include "duckdb/storage/compression/bitpacking.hpp" -#include "duckdb/function/encoding_function.hpp" #include "duckdb/main/extension/linked_extension_registry.hpp" #include "duckdb/main/setting_info.hpp" #include "duckdb/execution/index/index_type_set.hpp" @@ -105,10 +104,6 @@ struct DBConfigOptions { #endif //! The maximum size of the 'temp_directory' folder when set (in bytes). Default: 90% of available disk space. idx_t maximum_swap_space = DConstants::INVALID_INDEX; - //! The maximum amount of CPU threads used by the database system. Default: all available. - idx_t maximum_threads = DConstants::INVALID_INDEX; - //! The maximum amount of async threads used by the database system. Default: all available. - idx_t async_threads = DConstants::INVALID_INDEX; //! HTTP client limit derived from thread counts unless configured idx_t http_client_pool_capacity = DConstants::INVALID_INDEX; //! Whether or not to create and use a temporary directory to store intermediates that do not fit in memory @@ -128,8 +123,6 @@ struct DBConfigOptions { identifier_map_t user_options; //! The set of unrecognized (other) options identifier_map_t unrecognized_options; - //! HTTP proxy host (defaults to the HTTP_PROXY environment variable when unset) - string http_proxy; //! The default block header size for new duckdb database files. idx_t default_block_header_size = DEFAULT_BLOCK_HEADER_STORAGE_SIZE; //! Paths that are explicitly allowed, even if enable_external_access is false @@ -171,7 +164,7 @@ class ReplacementScanList { } template - void emplace_back(ARGS &&... args) { // NOLINT + void emplace_back(ARGS &&...args) { // NOLINT auto scan = make_shared_ptr(std::forward(args)...); lock_guard guard(lock); scans.push_back(std::move(scan)); @@ -205,7 +198,7 @@ struct DBConfig { ReplacementScanList replacement_scans; //! The FileSystem to use, can be overwritten to allow for injecting custom file systems for testing purposes (e.g. - //! RamFS or something similar) + //! RamFS or something similar). Never null: defaults to a VirtualFileSystem. unique_ptr file_system; //! Secret manager unique_ptr secret_manager; @@ -301,12 +294,6 @@ struct DBConfig { //! Returns a list of disabled compression methods DUCKDB_API vector GetDisabledCompressionMethods() const; - //! Returns the encode function matching the encoding name. - DUCKDB_API optional_ptr GetEncodeFunction(const string &name) const; - DUCKDB_API void RegisterEncodeFunction(const EncodingFunction &function) const; - //! Returns the encode function names. - DUCKDB_API vector> GetLoadedEncodedFunctions() const; - //! Returns the encode function matching the encoding name. DUCKDB_API ArrowTypeExtension GetArrowExtension(ArrowExtensionMetadata info) const; DUCKDB_API ArrowTypeExtension GetArrowExtension(const LogicalType &type) const; DUCKDB_API bool HasArrowExtension(const LogicalType &type) const; @@ -333,6 +320,11 @@ struct DBConfig { static idx_t GetSystemMaxAsyncThreads(FileSystem &fs); static idx_t GetSystemAvailableMemory(FileSystem &fs); static optional_idx ParseMemoryLimitSlurm(const string &arg); + idx_t GetDefaultMaxMemory() const; + //! The number of threads used when the threads setting is not set + idx_t GetDefaultThreads() const; + //! The number of async threads used when the async_threads setting is not set + idx_t GetDefaultAsyncThreads() const; void SetDefaultMaxMemory(); void SetDefaultTempDirectory(); @@ -345,7 +337,7 @@ struct DBConfig { //! Returns the value of a setting set by the user currently SettingLookupResult TryGetCurrentUserSetting(idx_t setting_index, Value &result) const; //! Returns the default value of an option - static SettingLookupResult TryGetDefaultValue(optional_ptr option, Value &result); + SettingLookupResult TryGetDefaultValue(optional_ptr option, Value &result) const; SettingLookupResult TryGetDefaultValue(const Identifier &key, optional_ptr option, Value &result) const; @@ -392,8 +384,11 @@ struct DBConfig { mutable mutex disabled_optimizers_lock; //! Whether disabled_optimizers is non-empty atomic has_disabled_optimizers {false}; + //! Cache of GetDefaultThreads, which reads the cgroup CPU limit + mutable atomic default_threads {0}; + //! Cache of GetDefaultMaxMemory, which reads the cgroup memory limit through the file system + mutable atomic default_max_memory {0}; unique_ptr compression_functions; - unique_ptr encoding_functions; unique_ptr arrow_extensions; unique_ptr type_manager; unique_ptr collation_bindings; diff --git a/src/duckdb/src/include/duckdb/main/connection.hpp b/src/duckdb/src/include/duckdb/main/connection.hpp index 76275d707..ee59f1ffd 100644 --- a/src/duckdb/src/include/duckdb/main/connection.hpp +++ b/src/duckdb/src/include/duckdb/main/connection.hpp @@ -13,25 +13,22 @@ #include "duckdb/main/profiler/profiler_print_format.hpp" #include "duckdb/common/serializer/buffered_file_writer.hpp" #include "duckdb/common/winapi.hpp" +#include "duckdb/main/client_context.hpp" #include "duckdb/main/prepared_statement.hpp" #include "duckdb/main/query_result.hpp" #include "duckdb/main/query_result_stream.hpp" -#include "duckdb/main/relation.hpp" #include "duckdb/main/table_description.hpp" #include "duckdb/parser/sql_statement.hpp" namespace duckdb { class ColumnDataCollection; -class ClientContext; class DatabaseInstance; class DuckDB; class LogicalOperator; class ResultFormat; -class SelectStatement; struct CSVReaderOptions; -struct TableFunctionInfo; typedef void (*warning_callback_t)(std::string); @@ -146,46 +143,6 @@ class Connection { //! Appends a ColumnDataCollection to the described table. DUCKDB_API void Append(TableDescription &description, ColumnDataCollection &collection); - //! Returns a relation that produces a table from this connection - DUCKDB_API shared_ptr Table(const Identifier &tname); - DUCKDB_API shared_ptr Table(const Identifier &schema_name, const Identifier &table_name); - DUCKDB_API shared_ptr Table(const Identifier &catalog_name, const Identifier &schema_name, - const Identifier &table_name); - //! Returns a relation that produces a view from this connection - DUCKDB_API shared_ptr View(const Identifier &tname); - DUCKDB_API shared_ptr View(const Identifier &schema_name, const Identifier &table_name); - //! Returns a relation that calls a specified table function - DUCKDB_API shared_ptr TableFunction(const string &tname); - DUCKDB_API shared_ptr TableFunction(const string &tname, const vector &values, - const named_parameter_map_t &named_parameters); - DUCKDB_API shared_ptr TableFunction(const string &tname, const vector &values); - //! Calls a table function with process-local input for this invocation - DUCKDB_API shared_ptr TableFunction(const string &tname, const vector &values, - const named_parameter_map_t &named_parameters, - shared_ptr bind_info); - //! Returns a relation that produces values - DUCKDB_API shared_ptr Values(const vector> &values); - DUCKDB_API shared_ptr Values(vector>> &&values); - DUCKDB_API shared_ptr Values(const vector> &values, const vector &column_names, - const string &alias = "values"); - DUCKDB_API shared_ptr Values(const string &values); - DUCKDB_API shared_ptr Values(const string &values, const vector &column_names, - const string &alias = "values"); - - //! Reads CSV file - DUCKDB_API shared_ptr ReadCSV(const string &csv_file); - DUCKDB_API shared_ptr ReadCSV(const vector &csv_input, named_parameter_map_t &&options); - DUCKDB_API shared_ptr ReadCSV(const string &csv_input, named_parameter_map_t &&options); - DUCKDB_API shared_ptr ReadCSV(const string &csv_file, const vector &columns); - - //! Reads Parquet file - DUCKDB_API shared_ptr ReadParquet(const string &parquet_file, bool binary_as_string); - //! Returns a relation from a query - DUCKDB_API shared_ptr RelationFromQuery(const string &query, const string &alias = "queryrelation", - const string &error = "Expected a single SELECT statement"); - DUCKDB_API shared_ptr RelationFromQuery(unique_ptr select_stmt, - const string &alias = "queryrelation", const string &query = ""); - DUCKDB_API void BeginTransaction(); DUCKDB_API void Commit(); DUCKDB_API void Rollback(); diff --git a/src/duckdb/src/include/duckdb/main/context.hpp b/src/duckdb/src/include/duckdb/main/context.hpp index b9a7849b0..9253c82e2 100644 --- a/src/duckdb/src/include/duckdb/main/context.hpp +++ b/src/duckdb/src/include/duckdb/main/context.hpp @@ -54,7 +54,10 @@ class Context { //! Null-safe variants for optional services DUCKDB_API static optional_ptr TryGetClientContext(optional_ptr services); DUCKDB_API static optional_ptr TryGetQueryProfiler(optional_ptr services); - //! Checks whether the query was interrupted (or timed out) and throws if so - no-op without a client + //! Checks whether the query was interrupted (or timed out, checked only every 256th call) and throws if so - no-op + //! without a client + DUCKDB_API void FastInterruptCheck() const; + //! Checks whether the query was interrupted or timed out and throws if so - no-op without a client DUCKDB_API void InterruptCheck() const; //! Whether or not these are the services of a client DUCKDB_API bool IsClient() const; diff --git a/src/duckdb/src/include/duckdb/main/database_file_opener.hpp b/src/duckdb/src/include/duckdb/main/database_file_opener.hpp index 08caecc27..99a0fb1ef 100644 --- a/src/duckdb/src/include/duckdb/main/database_file_opener.hpp +++ b/src/duckdb/src/include/duckdb/main/database_file_opener.hpp @@ -82,7 +82,6 @@ class LocalDatabaseFileSystem : public OpenerFileSystem { private: DatabaseInstance &db; - unique_ptr owned_file_system; FileSystem &local_fs; mutable DatabaseFileOpener database_opener; }; diff --git a/src/duckdb/src/include/duckdb/main/db_instance_cache.hpp b/src/duckdb/src/include/duckdb/main/db_instance_cache.hpp index 89f3a519f..c5bebbdae 100644 --- a/src/duckdb/src/include/duckdb/main/db_instance_cache.hpp +++ b/src/duckdb/src/include/duckdb/main/db_instance_cache.hpp @@ -29,6 +29,9 @@ struct DatabaseCacheEntry { enum class CacheBehavior { AUTOMATIC, ALWAYS_CACHE, NEVER_CACHE }; +//! Whether a cached instance, running with `existing`, can be shared by a request for `requested` +using db_config_match_t = std::function; + class DBInstanceCache { public: DBInstanceCache(); @@ -41,12 +44,15 @@ class DBInstanceCache { shared_ptr CreateInstance(const string &database, DBConfig &config_dict, bool cache_instance = true, const std::function &on_create = nullptr); - //! Either returns an existing entry, or creates and caches a new DB Instance + //! Either returns an existing entry, or creates and caches a new DB Instance. `on_create` runs before another call + //! can share a new instance; if it throws, the instance is dropped. `is_same_config` replaces the default config + //! comparison when given. shared_ptr GetOrCreateInstance(const string &database, DBConfig &config_dict, bool cache_instance, const std::function &on_create = nullptr); shared_ptr GetOrCreateInstance(const string &database, DBConfig &config_dict, CacheBehavior cache_behavior = CacheBehavior::AUTOMATIC, - const std::function &on_create = nullptr); + const std::function &on_create = nullptr, + const db_config_match_t &is_same_config = nullptr); //! Creates an uncached instance with no database attached (see DuckDB::CreateEmpty). Databases attached to it //! later go through this cache's path manager, so opening one file twice is detected across every instance @@ -63,7 +69,8 @@ class DBInstanceCache { private: shared_ptr GetInstanceInternal(const string &database, const DBConfig &config, - std::unique_lock &db_instances_lock); + std::unique_lock &db_instances_lock, + const db_config_match_t &is_same_config = nullptr); shared_ptr CreateInstanceInternal(const string &database, DBConfig &config_dict, bool cache_instance, std::unique_lock db_instances_lock, const std::function &on_create); diff --git a/src/duckdb/src/include/duckdb/main/extension/extension_loader.hpp b/src/duckdb/src/include/duckdb/main/extension/extension_loader.hpp index 78f51c751..a5aeed17b 100644 --- a/src/duckdb/src/include/duckdb/main/extension/extension_loader.hpp +++ b/src/duckdb/src/include/duckdb/main/extension/extension_loader.hpp @@ -23,7 +23,6 @@ class TableFunctionCatalogEntry; class DatabaseInstance; struct CreateMacroInfo; -struct CreateCollationInfo; struct CreateAggregateFunctionInfo; struct CreateScalarFunctionInfo; struct CreateTableFunctionInfo; @@ -103,9 +102,6 @@ class ExtensionLoader { //! Register a new macro function - throw an exception if the function already exists DUCKDB_API void RegisterFunction(CreateMacroInfo &info); - //! Register a new collation - DUCKDB_API void RegisterCollation(CreateCollationInfo &info); - //! Register a new coordinate system DUCKDB_API void RegisterCoordinateSystem(CreateCoordinateSystemInfo &info); diff --git a/src/duckdb/src/include/duckdb/main/extension_entries.hpp b/src/duckdb/src/include/duckdb/main/extension_entries.hpp index 04cfbd2ae..1bc467703 100644 --- a/src/duckdb/src/include/duckdb/main/extension_entries.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_entries.hpp @@ -37,6 +37,7 @@ struct ExtensionFunctionOverloadEntry { char extension[48]; CatalogType type; char signature[96]; + char parameters[96]; }; static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { @@ -148,147 +149,6 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"cloudformation_describe_stack", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"cloudformation_describe_stacks", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"cloudformation_list_stacks", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, - {"collate_aa", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_af", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_am", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ar", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ar_sa", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_as", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_az", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_bal", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_be", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_bg", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_blo", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_bn", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_bo", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_br", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_bs", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ca", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ceb", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_chr", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_cs", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_cu", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_cy", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_da", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_de", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_de_at", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_dsb", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_dz", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ee", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_el", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_en", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_en_us", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_eo", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_es", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_et", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_fa", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_fa_af", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ff", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_fi", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_fil", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_fo", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_fr", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_fr_ca", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_fy", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ga", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_gl", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_gu", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ha", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_haw", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_he", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_he_il", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_hi", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_hr", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_hsb", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_hu", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_hy", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_id", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_id_id", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ig", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_is", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_it", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ja", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ka", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_kk", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_kl", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_km", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_kn", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ko", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_kok", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ku", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ky", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_lb", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_lij", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_lkt", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ln", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_lo", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_lt", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_lv", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_mk", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ml", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_mn", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_mr", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ms", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_mt", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_my", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_nb", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_nb_no", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ne", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_nl", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_nn", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_no", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_noaccent", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_nso", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_om", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_or", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_pa", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_pa_in", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_pl", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ps", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_pt", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ro", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ru", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sa", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_se", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sgs", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_si", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sk", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sl", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_smn", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sq", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sr", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sr_ba", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sr_me", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sr_rs", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ssy", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_st", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sv", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_sw", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ta", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_te", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_th", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_tk", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_tn", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_to", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_tr", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ug", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_uk", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_ur", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_uz", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_vi", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_vo", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_wae", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_wo", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_xh", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_yi", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_yo", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_zh", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_zh_cn", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_zh_hk", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_zh_mo", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_zh_sg", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_zh_tw", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"collate_zu", "icu", CatalogType::SCALAR_FUNCTION_ENTRY}, {"corr", "core_functions", CatalogType::AGGREGATE_FUNCTION_ENTRY}, {"cos", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"cosh", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, @@ -1078,291 +938,369 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { }; // END_OF_EXTENSION_FUNCTIONS static constexpr ExtensionFunctionOverloadEntry EXTENSION_FUNCTION_OVERLOADS[] = { - {"age", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>INTERVAL"}, - {"age", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP,TIMESTAMP]>INTERVAL"}, - {"age", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>INTERVAL"}, - {"age", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ,TIMESTAMPTZ]>INTERVAL"}, - {"century", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"century", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"century", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"century", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"century", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"date_diff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE,DATE]>BIGINT"}, - {"date_diff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME,TIME]>BIGINT"}, - {"date_diff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP,TIMESTAMP]>BIGINT"}, - {"date_diff", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ,TIMESTAMPTZ]>BIGINT"}, - {"date_diff", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS,TIMESTAMPTZ_NS]>BIGINT"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',DATE]>STRUCT"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',INTERVAL]>STRUCT"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME]>STRUCT"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP]>STRUCT"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP_NS]>STRUCT"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMETZ]>STRUCT"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME_NS]>STRUCT"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>DOUBLE"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,INTERVAL]>DOUBLE"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME]>DOUBLE"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>DOUBLE"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP_NS]>DOUBLE"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMETZ]>DOUBLE"}, - {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME_NS]>DOUBLE"}, - {"date_part", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMPTZ]>STRUCT"}, - {"date_part", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMPTZ_NS]>STRUCT"}, - {"date_part", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ]>DOUBLE"}, - {"date_part", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS]>DOUBLE"}, - {"date_sub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE,DATE]>BIGINT"}, - {"date_sub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME,TIME]>BIGINT"}, - {"date_sub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP,TIMESTAMP]>BIGINT"}, - {"date_sub", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ,TIMESTAMPTZ]>BIGINT"}, - {"date_trunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>TIMESTAMP"}, - {"date_trunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,INTERVAL]>INTERVAL"}, - {"date_trunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>TIMESTAMP"}, - {"date_trunc", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ]>TIMESTAMPTZ"}, - {"date_trunc", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS]>TIMESTAMPTZ"}, - {"datediff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE,DATE]>BIGINT"}, - {"datediff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME,TIME]>BIGINT"}, - {"datediff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP,TIMESTAMP]>BIGINT"}, - {"datediff", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ,TIMESTAMPTZ]>BIGINT"}, - {"datediff", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS,TIMESTAMPTZ_NS]>BIGINT"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',DATE]>STRUCT"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',INTERVAL]>STRUCT"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME]>STRUCT"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP]>STRUCT"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP_NS]>STRUCT"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMETZ]>STRUCT"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME_NS]>STRUCT"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>DOUBLE"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,INTERVAL]>DOUBLE"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME]>DOUBLE"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>DOUBLE"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP_NS]>DOUBLE"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMETZ]>DOUBLE"}, - {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME_NS]>DOUBLE"}, - {"datepart", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMPTZ]>STRUCT"}, - {"datepart", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMPTZ_NS]>STRUCT"}, - {"datepart", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ]>DOUBLE"}, - {"datepart", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS]>DOUBLE"}, - {"datesub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE,DATE]>BIGINT"}, - {"datesub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME,TIME]>BIGINT"}, - {"datesub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP,TIMESTAMP]>BIGINT"}, - {"datesub", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ,TIMESTAMPTZ]>BIGINT"}, - {"datetrunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>TIMESTAMP"}, - {"datetrunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,INTERVAL]>INTERVAL"}, - {"datetrunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>TIMESTAMP"}, - {"datetrunc", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ]>TIMESTAMPTZ"}, - {"datetrunc", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS]>TIMESTAMPTZ"}, - {"day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"day", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"day", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"dayname", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>VARCHAR"}, - {"dayname", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>VARCHAR"}, - {"dayname", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>VARCHAR"}, - {"dayname", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>VARCHAR"}, - {"dayofmonth", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"dayofmonth", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"dayofmonth", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"dayofmonth", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"dayofmonth", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"dayofweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"dayofweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"dayofweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"dayofweek", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"dayofweek", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"dayofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"dayofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"dayofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"dayofyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"dayofyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"decade", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"decade", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"decade", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"decade", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"decade", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>DOUBLE"}, - {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>DOUBLE"}, - {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>DOUBLE"}, - {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>DOUBLE"}, - {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>DOUBLE"}, - {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>DOUBLE"}, - {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>DOUBLE"}, - {"epoch", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>DOUBLE"}, - {"epoch", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>DOUBLE"}, - {"era", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"era", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"era", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"era", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"era", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"generate_series", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT]>BIGINT[]"}, - {"generate_series", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT,BIGINT]>BIGINT[]"}, - {"generate_series", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT,BIGINT,BIGINT]>BIGINT[]"}, + {"age", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>INTERVAL", "[timestamp]"}, + {"age", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP,TIMESTAMP]>INTERVAL", + "[timestamp1,timestamp2]"}, + {"age", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>INTERVAL", "[timestamp]"}, + {"age", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ,TIMESTAMPTZ]>INTERVAL", "[timestamp1,timestamp2]"}, + {"century", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"century", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"century", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"century", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"century", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"century", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"date_diff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE,DATE]>BIGINT", + "[part,startdate,enddate]"}, + {"date_diff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME,TIME]>BIGINT", + "[part,startdate,enddate]"}, + {"date_diff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP,TIMESTAMP]>BIGINT", + "[part,startdate,enddate]"}, + {"date_diff", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ,TIMESTAMPTZ]>BIGINT", + "[part,startdate,enddate]"}, + {"date_diff", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS,TIMESTAMPTZ_NS]>BIGINT", + "[part,startdate,enddate]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',DATE]>STRUCT", "[part_list,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',INTERVAL]>STRUCT", + "[part_list,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME]>STRUCT", "[part_list,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP]>STRUCT", + "[part_list,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP_NS]>STRUCT", + "[part_list,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMETZ]>STRUCT", + "[part_list,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME_NS]>STRUCT", + "[part_list,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>DOUBLE", "[part,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,INTERVAL]>DOUBLE", "[part,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME]>DOUBLE", "[part,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>DOUBLE", "[part,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP_NS]>DOUBLE", "[part,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMETZ]>DOUBLE", "[part,ts]"}, + {"date_part", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME_NS]>DOUBLE", "[part,ts]"}, + {"date_part", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMPTZ]>STRUCT", "[part_list,ts]"}, + {"date_part", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMPTZ_NS]>STRUCT", "[part_list,ts]"}, + {"date_part", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ]>DOUBLE", "[part,ts]"}, + {"date_part", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS]>DOUBLE", "[part,ts]"}, + {"date_sub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE,DATE]>BIGINT", + "[part,startdate,enddate]"}, + {"date_sub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME,TIME]>BIGINT", + "[part,startdate,enddate]"}, + {"date_sub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP,TIMESTAMP]>BIGINT", + "[part,startdate,enddate]"}, + {"date_sub", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ,TIMESTAMPTZ]>BIGINT", + "[part,startdate,enddate]"}, + {"date_trunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>TIMESTAMP", + "[part,timestamp]"}, + {"date_trunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,INTERVAL]>INTERVAL", + "[part,timestamp]"}, + {"date_trunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>TIMESTAMP", + "[part,timestamp]"}, + {"date_trunc", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ]>TIMESTAMPTZ", "[part,timestamp]"}, + {"date_trunc", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS]>TIMESTAMPTZ", + "[part,timestamp]"}, + {"datediff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE,DATE]>BIGINT", + "[part,startdate,enddate]"}, + {"datediff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME,TIME]>BIGINT", + "[part,startdate,enddate]"}, + {"datediff", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP,TIMESTAMP]>BIGINT", + "[part,startdate,enddate]"}, + {"datediff", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ,TIMESTAMPTZ]>BIGINT", + "[part,startdate,enddate]"}, + {"datediff", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS,TIMESTAMPTZ_NS]>BIGINT", + "[part,startdate,enddate]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',DATE]>STRUCT", "[part_list,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',INTERVAL]>STRUCT", + "[part_list,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME]>STRUCT", "[part_list,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP]>STRUCT", + "[part_list,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMP_NS]>STRUCT", + "[part_list,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMETZ]>STRUCT", "[part_list,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIME_NS]>STRUCT", + "[part_list,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>DOUBLE", "[part,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,INTERVAL]>DOUBLE", "[part,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME]>DOUBLE", "[part,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>DOUBLE", "[part,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP_NS]>DOUBLE", "[part,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMETZ]>DOUBLE", "[part,ts]"}, + {"datepart", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME_NS]>DOUBLE", "[part,ts]"}, + {"datepart", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMPTZ]>STRUCT", "[part_list,ts]"}, + {"datepart", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "['VARCHAR[]',TIMESTAMPTZ_NS]>STRUCT", "[part_list,ts]"}, + {"datepart", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ]>DOUBLE", "[part,ts]"}, + {"datepart", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS]>DOUBLE", "[part,ts]"}, + {"datesub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE,DATE]>BIGINT", + "[part,startdate,enddate]"}, + {"datesub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIME,TIME]>BIGINT", + "[part,startdate,enddate]"}, + {"datesub", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP,TIMESTAMP]>BIGINT", + "[part,startdate,enddate]"}, + {"datesub", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ,TIMESTAMPTZ]>BIGINT", + "[part,startdate,enddate]"}, + {"datetrunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>TIMESTAMP", "[part,timestamp]"}, + {"datetrunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,INTERVAL]>INTERVAL", + "[part,timestamp]"}, + {"datetrunc", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>TIMESTAMP", + "[part,timestamp]"}, + {"datetrunc", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ]>TIMESTAMPTZ", "[part,timestamp]"}, + {"datetrunc", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS]>TIMESTAMPTZ", + "[part,timestamp]"}, + {"day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"day", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"day", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"dayname", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>VARCHAR", "[ts]"}, + {"dayname", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>VARCHAR", "[ts]"}, + {"dayname", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>VARCHAR", "[ts]"}, + {"dayname", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>VARCHAR", "[ts]"}, + {"dayofmonth", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"dayofmonth", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"dayofmonth", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"dayofmonth", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"dayofmonth", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"dayofmonth", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"dayofweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"dayofweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"dayofweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"dayofweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"dayofweek", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"dayofweek", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"dayofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"dayofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"dayofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"dayofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"dayofyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"dayofyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"decade", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"decade", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"decade", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"decade", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"decade", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"decade", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>DOUBLE", "[temporal]"}, + {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>DOUBLE", "[temporal]"}, + {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>DOUBLE", "[temporal]"}, + {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>DOUBLE", "[temporal]"}, + {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>DOUBLE", "[temporal]"}, + {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>DOUBLE", "[temporal]"}, + {"epoch", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>DOUBLE", "[temporal]"}, + {"epoch", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>DOUBLE", "[ts]"}, + {"epoch", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>DOUBLE", "[ts]"}, + {"era", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"era", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"era", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"era", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"era", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"era", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"generate_series", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT]>BIGINT[]", "[stop]"}, + {"generate_series", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT,BIGINT]>BIGINT[]", + "[start,stop]"}, + {"generate_series", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT,BIGINT,BIGINT]>BIGINT[]", + "[start,stop,step]"}, {"generate_series", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, - "[TIMESTAMP,TIMESTAMP,INTERVAL]>TIMESTAMP[]"}, - {"generate_series", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ,TIMESTAMPTZ,INTERVAL]>TIMESTAMPTZ[]"}, - {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, - {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, - {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, - {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, - {"hour", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"hour", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"isodow", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"isodow", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"isodow", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"isodow", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"isodow", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"isoyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"isoyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"isoyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"isoyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"isoyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"julian", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>DOUBLE"}, - {"julian", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>DOUBLE"}, - {"julian", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>DOUBLE"}, - {"julian", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>DOUBLE"}, - {"last_day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>DATE"}, - {"last_day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>DATE"}, - {"last_day", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>DATE"}, - {"last_day", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>DATE"}, - {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, - {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, - {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, - {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, - {"microsecond", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"microsecond", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"millennium", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"millennium", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"millennium", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"millennium", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"millennium", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, - {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, - {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, - {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, - {"millisecond", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"millisecond", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, - {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, - {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, - {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, - {"minute", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"minute", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"month", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"month", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"month", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"month", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"month", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"monthname", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>VARCHAR"}, - {"monthname", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>VARCHAR"}, - {"monthname", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>VARCHAR"}, - {"monthname", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>VARCHAR"}, - {"quarter", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"quarter", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"quarter", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"quarter", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"quarter", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"range", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT]>BIGINT[]"}, - {"range", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT,BIGINT]>BIGINT[]"}, - {"range", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT,BIGINT,BIGINT]>BIGINT[]"}, - {"range", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP,TIMESTAMP,INTERVAL]>TIMESTAMP[]"}, - {"range", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ,TIMESTAMPTZ,INTERVAL]>TIMESTAMPTZ[]"}, - {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, - {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, - {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, - {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, - {"second", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"second", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,DATE]>DATE"}, - {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,DATE,DATE]>DATE"}, - {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,DATE,INTERVAL]>DATE"}, - {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIME]>TIME"}, - {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIME,INTERVAL]>TIME"}, - {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIME,TIME]>TIME"}, - {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMP]>TIMESTAMP"}, - {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMP,INTERVAL]>TIMESTAMP"}, - {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMP,TIMESTAMP]>TIMESTAMP"}, - {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ]>TIMESTAMPTZ"}, - {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ,INTERVAL]>TIMESTAMPTZ"}, - {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ,TIMESTAMPTZ]>TIMESTAMPTZ"}, - {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ,VARCHAR]>TIMESTAMPTZ"}, - {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS]>TIMESTAMPTZ"}, - {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS,INTERVAL]>TIMESTAMPTZ"}, - {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS,TIMESTAMPTZ]>TIMESTAMPTZ"}, - {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS,VARCHAR]>TIMESTAMPTZ"}, - {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMETZ]>TIMETZ"}, - {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, - {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, - {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, - {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, - {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>TIMESTAMPTZ"}, - {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>TIMESTAMPTZ"}, - {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ]>TIMESTAMP"}, - {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS]>TIMESTAMP_NS"}, - {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP_NS]>TIMESTAMPTZ_NS"}, - {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMETZ]>TIMETZ"}, - {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, - {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, - {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, - {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, - {"timezone_hour", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"timezone_hour", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT"}, - {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT"}, - {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT"}, - {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT"}, - {"timezone_minute", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"timezone_minute", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"week", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"week", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"week", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"week", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"week", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"weekday", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"weekday", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"weekday", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"weekday", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"weekday", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"weekofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"weekofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"weekofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"weekofyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"weekofyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"year", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"year", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"year", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"year", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"year", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, - {"yearweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT"}, - {"yearweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT"}, - {"yearweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT"}, - {"yearweek", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT"}, - {"yearweek", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT"}, + "[TIMESTAMP,TIMESTAMP,INTERVAL]>TIMESTAMP[]", "[start,stop,step]"}, + {"generate_series", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ,TIMESTAMPTZ,INTERVAL]>TIMESTAMPTZ[]", + "[start,stop,step]"}, + {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT", "[ts]"}, + {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT", "[ts]"}, + {"hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT", "[ts]"}, + {"hour", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"hour", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"isodow", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"isodow", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"isodow", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"isodow", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"isodow", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"isodow", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"isoyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"isoyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"isoyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"isoyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"isoyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"isoyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"julian", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>DOUBLE", "[ts]"}, + {"julian", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>DOUBLE", "[ts]"}, + {"julian", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>DOUBLE", "[ts]"}, + {"julian", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>DOUBLE", "[ts]"}, + {"julian", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>DOUBLE", "[ts]"}, + {"last_day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>DATE", "[ts]"}, + {"last_day", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>DATE", "[ts]"}, + {"last_day", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>DATE", "[ts]"}, + {"last_day", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>DATE", "[ts]"}, + {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT", "[ts]"}, + {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT", "[ts]"}, + {"microsecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT", "[ts]"}, + {"microsecond", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"microsecond", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"millennium", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"millennium", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"millennium", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"millennium", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"millennium", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"millennium", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT", "[ts]"}, + {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT", "[ts]"}, + {"millisecond", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT", "[ts]"}, + {"millisecond", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"millisecond", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT", "[ts]"}, + {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT", "[ts]"}, + {"minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT", "[ts]"}, + {"minute", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"minute", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"month", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"month", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"month", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"month", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"month", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"month", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"monthname", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>VARCHAR", "[ts]"}, + {"monthname", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>VARCHAR", "[ts]"}, + {"monthname", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>VARCHAR", "[ts]"}, + {"monthname", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>VARCHAR", "[ts]"}, + {"quarter", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"quarter", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"quarter", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"quarter", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"quarter", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"quarter", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"range", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT]>BIGINT[]", "[stop]"}, + {"range", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT,BIGINT]>BIGINT[]", "[start,stop]"}, + {"range", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[BIGINT,BIGINT,BIGINT]>BIGINT[]", + "[start,stop,step]"}, + {"range", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP,TIMESTAMP,INTERVAL]>TIMESTAMP[]", + "[start,stop,step]"}, + {"range", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ,TIMESTAMPTZ,INTERVAL]>TIMESTAMPTZ[]", + "[start,stop,step]"}, + {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT", "[ts]"}, + {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT", "[ts]"}, + {"second", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT", "[ts]"}, + {"second", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"second", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,DATE]>DATE", + "[bucket_width,timestamp]"}, + {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,DATE,DATE]>DATE", + "[bucket_width,timestamp,origin]"}, + {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,DATE,INTERVAL]>DATE", + "[bucket_width,timestamp,offset]"}, + {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIME]>TIME", + "[bucket_width,timestamp]"}, + {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIME,INTERVAL]>TIME", + "[bucket_width,timestamp,offset]"}, + {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIME,TIME]>TIME", + "[bucket_width,timestamp,origin]"}, + {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMP]>TIMESTAMP", + "[bucket_width,timestamp]"}, + {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMP,INTERVAL]>TIMESTAMP", + "[bucket_width,timestamp,offset]"}, + {"time_bucket", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMP,TIMESTAMP]>TIMESTAMP", + "[bucket_width,timestamp,origin]"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ]>TIMESTAMPTZ", + "[bucket_width,timestamp]"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ,INTERVAL]>TIMESTAMPTZ", + "[bucket_width,timestamp,offset]"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ,TIMESTAMPTZ]>TIMESTAMPTZ", + "[bucket_width,timestamp,origin]"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ,VARCHAR]>TIMESTAMPTZ", + "[bucket_width,timestamp,timezone]"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS]>TIMESTAMPTZ", + "[bucket_width,timestamp]"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS,INTERVAL]>TIMESTAMPTZ", + "[bucket_width,timestamp,offset]"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS,TIMESTAMPTZ]>TIMESTAMPTZ", + "[bucket_width,timestamp,origin]"}, + {"time_bucket", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMESTAMPTZ_NS,VARCHAR]>TIMESTAMPTZ", + "[bucket_width,timestamp,timezone]"}, + {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL,TIMETZ]>TIMETZ", "[offset,time_tz]"}, + {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT", "[ts]"}, + {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT", "[ts]"}, + {"timezone", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT", "[ts]"}, + {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,DATE]>TIMESTAMPTZ", "[timezone,date]"}, + {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP]>TIMESTAMPTZ", "[timezone,timestamp]"}, + {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ]>TIMESTAMP", "[timezone,timestamp]"}, + {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMPTZ_NS]>TIMESTAMP_NS", + "[timezone,timestamp]"}, + {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMESTAMP_NS]>TIMESTAMPTZ_NS", + "[timezone,timestamp]"}, + {"timezone", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[VARCHAR,TIMETZ]>TIMETZ", "[timezone,timestamp]"}, + {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT", "[ts]"}, + {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT", "[ts]"}, + {"timezone_hour", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT", "[ts]"}, + {"timezone_hour", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"timezone_hour", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME]>BIGINT", "[ts]"}, + {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMETZ]>BIGINT", "[ts]"}, + {"timezone_minute", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIME_NS]>BIGINT", "[ts]"}, + {"timezone_minute", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"timezone_minute", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"week", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"week", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"week", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"week", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"week", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"week", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"weekday", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"weekday", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"weekday", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"weekday", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"weekday", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"weekday", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"weekofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"weekofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"weekofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"weekofyear", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"weekofyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"weekofyear", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"year", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"year", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"year", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"year", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"year", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"year", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, + {"yearweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[DATE]>BIGINT", "[ts]"}, + {"yearweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[INTERVAL]>BIGINT", "[ts]"}, + {"yearweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP]>BIGINT", "[ts]"}, + {"yearweek", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMP_NS]>BIGINT", "[ts]"}, + {"yearweek", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ]>BIGINT", "[ts]"}, + {"yearweek", "icu", CatalogType::SCALAR_FUNCTION_ENTRY, "[TIMESTAMPTZ_NS]>BIGINT", "[ts]"}, }; // END_OF_EXTENSION_FUNCTION_OVERLOADS static constexpr ExtensionEntry EXTENSION_SETTINGS[] = { diff --git a/src/duckdb/src/include/duckdb/main/extension_helper.hpp b/src/duckdb/src/include/duckdb/main/extension_helper.hpp index 6a7747763..0e220a9c2 100644 --- a/src/duckdb/src/include/duckdb/main/extension_helper.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_helper.hpp @@ -63,6 +63,12 @@ enum class ExtensionUpdateResultTag : uint8_t { STATICALLY_LOADED = 4, // This means the .info file written during installation was missing or malformed MISSING_INSTALL_INFO = 5, + // The user-provided repository the extension was installed from no longer exists + REPOSITORY_NOT_FOUND = 6, + // The user-provided repository the extension was installed from is not trusted (allow_extension_repositories) + REPOSITORY_NOT_TRUSTED = 7, + // The file of the user-provided repository the extension was installed from could not be read + REPOSITORY_UNREADABLE = 8, // The extension was re-downloaded from the repository, but due to a lack of version information // its impossible to tell if the extension is actually updated @@ -94,11 +100,16 @@ struct ExtensionInstallOptions { bool use_etags = false; //! Throw an error when installing an extension with a different origin than the one that is installed bool throw_on_origin_mismatch = false; + //! Install into this extension directory instead of the primary one + string extension_directory; }; struct InstalledExtensionDirectory { string path; + //! The user-provided repository of a per-repository folder, empty for the flat folder string repository; + //! The extension directory the folder is in + string extension_directory; }; class ExtensionHelper { diff --git a/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp b/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp index 5f5945e5f..26abe8eb6 100644 --- a/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp @@ -112,7 +112,7 @@ class ExtensionRepositoryManager { ResolveRepositoryFromHost(DatabaseInstance &db, optional_ptr context, const string &name); //! Throws unless adding a repository is currently allowed (opt-in and configuration lock) - static void CheckCanCreate(DatabaseInstance &db, bool from_host); + static void CheckCanCreate(DatabaseInstance &db, const string &name, bool from_host); //! Throws if the configuration is locked, freezing the trust store static void CheckNotLocked(DatabaseInstance &db); static string GetRepositoryPath(DatabaseInstance &db, FileSystem &fs, const string &name); diff --git a/src/duckdb/src/include/duckdb/main/http/http_transport_manager.hpp b/src/duckdb/src/include/duckdb/main/http/http_transport_manager.hpp index e9b430d55..a993e35f5 100644 --- a/src/duckdb/src/include/duckdb/main/http/http_transport_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/http/http_transport_manager.hpp @@ -60,7 +60,7 @@ class HTTPTransportManager { //! Retire excess idle clients and discard excess active clients on release DUCKDB_API void SetCapacity(idx_t capacity) DUCKDB_EXCLUDES(lock); DUCKDB_API idx_t GetCapacity() const DUCKDB_EXCLUDES(lock); - DUCKDB_API static idx_t AutomaticCapacity(const DBConfig &config); + DUCKDB_API static idx_t AutomaticCapacity(const DBConfig &config, optional_idx async_threads = optional_idx()); private: explicit HTTPTransportManager(const shared_ptr &initial_http_util); diff --git a/src/duckdb/src/include/duckdb/main/profiler_extension.hpp b/src/duckdb/src/include/duckdb/main/profiler_extension.hpp index d22a83cd7..e851d2a0a 100644 --- a/src/duckdb/src/include/duckdb/main/profiler_extension.hpp +++ b/src/duckdb/src/include/duckdb/main/profiler_extension.hpp @@ -18,7 +18,7 @@ struct DBConfig; class ClientContext; class TreeRenderer; -//! Factory that creates and configures a TreeRenderer for a given client context +//! Factory that creates a TreeRenderer for a given client context; it is configured from the renderer settings after using create_tree_renderer_t = std::function(ClientContext &context)>; //! A ProfilerExtension registers a pluggable tree renderer for a profiler / EXPLAIN output format diff --git a/src/duckdb/src/include/duckdb/main/relation.hpp b/src/duckdb/src/include/duckdb/main/relation.hpp deleted file mode 100644 index d96510150..000000000 --- a/src/duckdb/src/include/duckdb/main/relation.hpp +++ /dev/null @@ -1,241 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/common.hpp" -#include "duckdb/common/enums/join_type.hpp" -#include "duckdb/common/enums/relation_type.hpp" -#include "duckdb/common/winapi.hpp" -#include "duckdb/common/enums/joinref_type.hpp" -#include "duckdb/main/query_result.hpp" -#include "duckdb/parser/column_definition.hpp" -#include "duckdb/common/named_parameter_map.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/main/client_context_wrapper.hpp" -#include "duckdb/main/external_dependencies.hpp" -#include "duckdb/parser/statement/explain_statement.hpp" -#include "duckdb/parser/parsed_expression.hpp" -#include "duckdb/parser/result_modifier.hpp" -#include "duckdb/common/unique_ptr.hpp" -#include "duckdb/common/vector.hpp" -#include "duckdb/common/helper.hpp" - -namespace duckdb { -struct BoundStatement; - -class Binder; -class LogicalOperator; -class QueryNode; -class TableRef; - -static string CreateRelationAlias(RelationType type, const string &alias) { - if (!alias.empty()) { - return alias; - } - return StringUtil::Format("%s_%s", EnumUtil::ToString(type), StringUtil::GenerateRandomName()); -} - -class RelationContextWrapper : public ClientContextWrapper { -public: - ~RelationContextWrapper() override = default; - explicit RelationContextWrapper(const shared_ptr &context) : ClientContextWrapper(context) {}; - - explicit RelationContextWrapper(const ClientContextWrapper &context) : ClientContextWrapper(context) {}; - - void TryBindRelation(Relation &relation, vector &columns) override { - GetContext()->TryBindRelation(relation, columns); - } - -private: - weak_ptr client_context; -}; - -class Relation : public enable_shared_from_this { -public: - Relation(const shared_ptr &context_p, const RelationType type) : type(type) { - context = make_shared_ptr(context_p); - } - Relation(const shared_ptr &context, RelationType type, const string &alias_p = "") - : context(context), type(type), alias(CreateRelationAlias(type, alias_p)) { - } - - Relation(const shared_ptr &context, RelationType type, const string &alias_p = "") - : context(context), type(type), alias(CreateRelationAlias(type, alias_p)) { - } - - virtual ~Relation() = default; - - shared_ptr context; - RelationType type; - const string alias; - vector> external_dependencies; - -public: - DUCKDB_API virtual const vector &Columns() = 0; - DUCKDB_API virtual unique_ptr GetQueryNode() = 0; - DUCKDB_API virtual string GetQuery(); - DUCKDB_API virtual BoundStatement Bind(Binder &binder); - DUCKDB_API virtual Identifier GetAlias(); - - //! Blocking. Runs the relation to completion and returns its handle; throws on error - DUCKDB_API unique_ptr ExecuteOrThrow(); - //! Blocking. Runs the relation to completion and returns its handle - DUCKDB_API unique_ptr Execute(); - DUCKDB_API string ToString(); - DUCKDB_API virtual string ToString(idx_t depth) = 0; - - DUCKDB_API void Print(); - DUCKDB_API void Head(idx_t limit = 10); - - DUCKDB_API shared_ptr CreateView(const Identifier &name, bool replace = true, bool temporary = false); - DUCKDB_API shared_ptr CreateView(const Identifier &schema_name, const Identifier &name, - bool replace = true, bool temporary = false); - //! Blocking. Runs a query to completion and returns its handle; the second form exposes the relation as a view - DUCKDB_API unique_ptr Query(const string &sql) const; - DUCKDB_API unique_ptr Query(const Identifier &name, const string &sql); - - //! Explain the query plan of this relation - DUCKDB_API unique_ptr Explain(ExplainType type = ExplainType::EXPLAIN_STANDARD, - const ProfilerPrintFormat &format = ProfilerPrintFormat::Default()); - - DUCKDB_API virtual unique_ptr GetTableRef(); - virtual bool IsReadOnly() { - return true; - } - DUCKDB_API void TryBindRelation(vector &columns); - -public: - // PROJECT - DUCKDB_API shared_ptr Project(const string &select_list); - DUCKDB_API shared_ptr Project(const string &expression, const string &alias); - DUCKDB_API shared_ptr Project(const string &select_list, const vector &aliases); - DUCKDB_API shared_ptr Project(const vector &expressions); - DUCKDB_API shared_ptr Project(const vector &expressions, const vector &aliases); - DUCKDB_API shared_ptr Project(vector> expressions, - const vector &aliases); - - // FILTER - DUCKDB_API shared_ptr Filter(const string &expression); - DUCKDB_API shared_ptr Filter(unique_ptr expression); - DUCKDB_API shared_ptr Filter(const vector &expressions); - - // LIMIT - DUCKDB_API shared_ptr Limit(int64_t n, int64_t offset = 0); - - // ORDER - DUCKDB_API shared_ptr Order(const string &expression); - DUCKDB_API shared_ptr Order(const vector &expressions); - DUCKDB_API shared_ptr Order(vector expressions); - - // JOIN operation - DUCKDB_API shared_ptr Join(const shared_ptr &other, const string &condition, - JoinType type = JoinType::INNER, JoinRefType ref_type = JoinRefType::REGULAR); - shared_ptr Join(const shared_ptr &other, vector> condition, - JoinType type = JoinType::INNER, JoinRefType ref_type = JoinRefType::REGULAR); - - // CROSS PRODUCT operation - DUCKDB_API shared_ptr CrossProduct(const shared_ptr &other, - JoinRefType join_ref_type = JoinRefType::CROSS); - - // SET operations - DUCKDB_API shared_ptr Union(const shared_ptr &other); - DUCKDB_API shared_ptr Except(const shared_ptr &other); - DUCKDB_API shared_ptr Intersect(const shared_ptr &other); - - // DISTINCT operation - DUCKDB_API shared_ptr Distinct(); - - // AGGREGATES - DUCKDB_API shared_ptr Aggregate(const string &aggregate_list); - DUCKDB_API shared_ptr Aggregate(const vector &aggregates); - DUCKDB_API shared_ptr Aggregate(vector> expressions); - DUCKDB_API shared_ptr Aggregate(const string &aggregate_list, const string &group_list); - DUCKDB_API shared_ptr Aggregate(const vector &aggregates, const vector &groups); - DUCKDB_API shared_ptr Aggregate(vector> expressions, - const string &group_list); - - // ALIAS - DUCKDB_API shared_ptr Alias(const string &alias); - - //! Insert the data from this relation into a table - DUCKDB_API shared_ptr InsertRel(const Identifier &schema_name, const Identifier &table_name); - DUCKDB_API shared_ptr InsertRel(const Identifier &catalog_name, const Identifier &schema_name, - const Identifier &table_name); - DUCKDB_API void Insert(const Identifier &table_name); - DUCKDB_API void Insert(const Identifier &schema_name, const Identifier &table_name); - DUCKDB_API void Insert(const Identifier &catalog_name, const Identifier &schema_name, const Identifier &table_name); - //! Insert a row (i.e.,list of values) into a table - DUCKDB_API virtual void Insert(const vector> &values); - DUCKDB_API virtual void Insert(vector>> &&expressions); - //! Create a table and insert the data from this relation into that table - DUCKDB_API shared_ptr CreateRel(const Identifier &schema_name, const Identifier &table_name, - bool temporary = false, - OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT); - DUCKDB_API shared_ptr CreateRel(const Identifier &catalog_name, const Identifier &schema_name, - const Identifier &table_name, bool temporary = false, - OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT); - DUCKDB_API void Create(const Identifier &table_name, bool temporary = false, - OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT); - DUCKDB_API void Create(const Identifier &schema_name, const Identifier &table_name, bool temporary = false, - OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT); - DUCKDB_API void Create(const Identifier &catalog_name, const Identifier &schema_name, const Identifier &table_name, - bool temporary = false, OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT); - - //! Write a relation to a CSV file - DUCKDB_API shared_ptr - WriteCSVRel(const string &csv_file, identifier_map_t> options = identifier_map_t>()); - DUCKDB_API void WriteCSV(const string &csv_file, - identifier_map_t> options = identifier_map_t>()); - //! Write a relation to a Parquet file - DUCKDB_API shared_ptr - WriteParquetRel(const string &parquet_file, - identifier_map_t> options = identifier_map_t>()); - DUCKDB_API void WriteParquet(const string &parquet_file, - identifier_map_t> options = identifier_map_t>()); - - //! Update a table, can only be used on a TableRelation - DUCKDB_API virtual void Update(const string &update, const string &condition = string()); - DUCKDB_API virtual void Update(vector column_names, vector> &&update, - unique_ptr condition = nullptr); - //! Delete from a table, can only be used on a TableRelation - DUCKDB_API virtual void Delete(const string &condition = string()); - //! Create a relation from calling a table in/out function on the input relation - //! Create a relation from calling a table in/out function on the input relation - DUCKDB_API shared_ptr TableFunction(const std::string &fname, const vector &values); - DUCKDB_API shared_ptr TableFunction(const std::string &fname, const vector &values, - const named_parameter_map_t &named_parameters); - -public: - //! Whether or not the relation inherits column bindings from its child or not, only relevant for binding - virtual bool InheritsColumnBindings() { - return false; - } - virtual Relation *ChildRelation() { - return nullptr; - } - void AddExternalDependency(shared_ptr dependency); - DUCKDB_API vector> GetAllDependencies(); - -protected: - DUCKDB_API static string RenderWhitespace(idx_t depth); - -public: - template - TARGET &Cast() { - DynamicCastCheck(this); - return reinterpret_cast(*this); - } - template - const TARGET &Cast() const { - DynamicCastCheck(this); - return reinterpret_cast(*this); - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/aggregate_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/aggregate_relation.hpp deleted file mode 100644 index 215fe2535..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/aggregate_relation.hpp +++ /dev/null @@ -1,38 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/aggregate_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/parser/parsed_expression.hpp" -#include "duckdb/parser/group_by_node.hpp" - -namespace duckdb { - -class AggregateRelation : public Relation { -public: - DUCKDB_API AggregateRelation(shared_ptr child, vector> expressions); - DUCKDB_API AggregateRelation(shared_ptr child, vector> expressions, - GroupByNode groups); - DUCKDB_API AggregateRelation(shared_ptr child, vector> expressions, - vector> groups); - - vector> expressions; - GroupByNode groups; - vector columns; - shared_ptr child; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/create_table_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/create_table_relation.hpp deleted file mode 100644 index 1f2b6fd97..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/create_table_relation.hpp +++ /dev/null @@ -1,41 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/create_table_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class CreateTableRelation : public Relation { -public: - CreateTableRelation(shared_ptr child, Identifier schema_name, Identifier table_name, bool temporary, - OnCreateConflict on_conflict); - CreateTableRelation(shared_ptr child, Identifier catalog_name, Identifier schema_name, - Identifier table_name, bool temporary, OnCreateConflict on_conflict); - - shared_ptr child; - Identifier catalog_name; - Identifier schema_name; - Identifier table_name; - vector columns; - bool temporary; - OnCreateConflict on_conflict; - -public: - BoundStatement Bind(Binder &binder) override; - unique_ptr GetQueryNode() override; - string GetQuery() override; - const vector &Columns() override; - string ToString(idx_t depth) override; - bool IsReadOnly() override { - return false; - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/create_view_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/create_view_relation.hpp deleted file mode 100644 index 69baad0df..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/create_view_relation.hpp +++ /dev/null @@ -1,39 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/create_view_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class CreateViewRelation : public Relation { -public: - CreateViewRelation(shared_ptr child, Identifier view_name, bool replace, bool temporary); - CreateViewRelation(shared_ptr child, Identifier schema_name, Identifier view_name, bool replace, - bool temporary); - - shared_ptr child; - Identifier schema_name; - Identifier view_name; - bool replace; - bool temporary; - vector columns; - -public: - BoundStatement Bind(Binder &binder) override; - unique_ptr GetQueryNode() override; - string GetQuery() override; - const vector &Columns() override; - string ToString(idx_t depth) override; - bool IsReadOnly() override { - return false; - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/cross_product_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/cross_product_relation.hpp deleted file mode 100644 index 82fc828b6..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/cross_product_relation.hpp +++ /dev/null @@ -1,35 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/cross_product_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/common/enums/joinref_type.hpp" - -namespace duckdb { - -class CrossProductRelation : public Relation { -public: - DUCKDB_API CrossProductRelation(shared_ptr left, shared_ptr right, - JoinRefType join_ref_type = JoinRefType::CROSS); - - shared_ptr left; - shared_ptr right; - JoinRefType ref_type; - vector columns; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - - unique_ptr GetTableRef() override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/delete_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/delete_relation.hpp deleted file mode 100644 index 851900c62..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/delete_relation.hpp +++ /dev/null @@ -1,38 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/delete_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/parser/parsed_expression.hpp" - -namespace duckdb { - -class DeleteRelation : public Relation { -public: - DeleteRelation(shared_ptr &context, unique_ptr condition, - Identifier catalog_name, Identifier schema_name, Identifier table_name); - - vector columns; - unique_ptr condition; - Identifier catalog_name; - Identifier schema_name; - Identifier table_name; - -public: - BoundStatement Bind(Binder &binder) override; - unique_ptr GetQueryNode() override; - string GetQuery() override; - const vector &Columns() override; - string ToString(idx_t depth) override; - bool IsReadOnly() override { - return false; - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/delim_get_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/delim_get_relation.hpp deleted file mode 100644 index e78446527..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/delim_get_relation.hpp +++ /dev/null @@ -1,30 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/delim_get_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class DelimGetRelation : public Relation { -public: - DUCKDB_API DelimGetRelation(const shared_ptr &context, vector chunk_types); - - vector chunk_types; - vector columns; - -public: - unique_ptr GetQueryNode() override; - unique_ptr GetTableRef() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/distinct_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/distinct_relation.hpp deleted file mode 100644 index 98677c7ce..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/distinct_relation.hpp +++ /dev/null @@ -1,37 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/distinct_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class DistinctRelation : public Relation { -public: - explicit DistinctRelation(shared_ptr child); - - shared_ptr child; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; - -public: - bool InheritsColumnBindings() override { - return true; - } - Relation *ChildRelation() override { - return child.get(); - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/explain_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/explain_relation.hpp deleted file mode 100644 index c2d35fb7a..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/explain_relation.hpp +++ /dev/null @@ -1,36 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/explain_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class ExplainRelation : public Relation { -public: - explicit ExplainRelation(shared_ptr child, ExplainType type = ExplainType::EXPLAIN_STANDARD, - const ProfilerPrintFormat &format = ProfilerPrintFormat::Default()); - - shared_ptr child; - vector columns; - ExplainType type; - ProfilerPrintFormat format; - -public: - BoundStatement Bind(Binder &binder) override; - unique_ptr GetQueryNode() override; - string GetQuery() override; - const vector &Columns() override; - string ToString(idx_t depth) override; - bool IsReadOnly() override { - return false; - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/filter_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/filter_relation.hpp deleted file mode 100644 index a9ccc981f..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/filter_relation.hpp +++ /dev/null @@ -1,39 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/filter_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/parser/parsed_expression.hpp" - -namespace duckdb { - -class FilterRelation : public Relation { -public: - DUCKDB_API FilterRelation(shared_ptr child, unique_ptr condition); - - unique_ptr condition; - shared_ptr child; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; - -public: - bool InheritsColumnBindings() override { - return true; - } - Relation *ChildRelation() override { - return child.get(); - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/insert_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/insert_relation.hpp deleted file mode 100644 index 6e7782fae..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/insert_relation.hpp +++ /dev/null @@ -1,37 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/insert_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class InsertRelation : public Relation { -public: - InsertRelation(shared_ptr child, Identifier schema_name, Identifier table_name); - InsertRelation(shared_ptr child, Identifier catalog_name, Identifier schema_name, Identifier table_name); - - shared_ptr child; - Identifier catalog_name; - Identifier schema_name; - Identifier table_name; - vector columns; - -public: - BoundStatement Bind(Binder &binder) override; - unique_ptr GetQueryNode() override; - string GetQuery() override; - const vector &Columns() override; - string ToString(idx_t depth) override; - bool IsReadOnly() override { - return false; - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/join_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/join_relation.hpp deleted file mode 100644 index ded9aeaeb..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/join_relation.hpp +++ /dev/null @@ -1,44 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/join_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/common/enums/joinref_type.hpp" - -namespace duckdb { - -class JoinRelation : public Relation { -public: - DUCKDB_API JoinRelation(shared_ptr left, shared_ptr right, - unique_ptr condition, JoinType type, - JoinRefType join_ref_type = JoinRefType::REGULAR); - DUCKDB_API JoinRelation(shared_ptr left, shared_ptr right, vector using_columns, - JoinType type, JoinRefType join_ref_type = JoinRefType::REGULAR); - - shared_ptr left; - shared_ptr right; - unique_ptr condition; - vector using_columns; - JoinType join_type; - JoinRefType join_ref_type; - vector columns; - - vector> duplicate_eliminated_columns; - bool delim_flipped = false; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - - unique_ptr GetTableRef() override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/limit_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/limit_relation.hpp deleted file mode 100644 index 7536e25a0..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/limit_relation.hpp +++ /dev/null @@ -1,39 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/limit_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class LimitRelation : public Relation { -public: - DUCKDB_API LimitRelation(shared_ptr child, int64_t limit, int64_t offset); - - int64_t limit; - int64_t offset; - shared_ptr child; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; - -public: - bool InheritsColumnBindings() override { - return true; - } - Relation *ChildRelation() override { - return child.get(); - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/materialized_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/materialized_relation.hpp deleted file mode 100644 index 7c8dc2425..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/materialized_relation.hpp +++ /dev/null @@ -1,32 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/materialized_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/parser/parsed_expression.hpp" - -namespace duckdb { - -class MaterializedRelation : public Relation { -public: - MaterializedRelation(const shared_ptr &context, unique_ptr &&collection, - vector names, const Identifier &alias = "materialized"); - vector columns; - string alias; - shared_ptr collection; - -public: - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; - unique_ptr GetTableRef() override; - unique_ptr GetQueryNode() override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/order_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/order_relation.hpp deleted file mode 100644 index 7d560d8d8..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/order_relation.hpp +++ /dev/null @@ -1,41 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/order_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/parser/parsed_expression.hpp" -#include "duckdb/parser/result_modifier.hpp" - -namespace duckdb { - -class OrderRelation : public Relation { -public: - DUCKDB_API OrderRelation(shared_ptr child, vector orders); - - vector orders; - shared_ptr child; - vector columns; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; - -public: - bool InheritsColumnBindings() override { - return true; - } - Relation *ChildRelation() override { - return child.get(); - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/projection_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/projection_relation.hpp deleted file mode 100644 index 648e2d8cd..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/projection_relation.hpp +++ /dev/null @@ -1,33 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/projection_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/parser/parsed_expression.hpp" - -namespace duckdb { - -class ProjectionRelation : public Relation { -public: - DUCKDB_API ProjectionRelation(shared_ptr child, vector> expressions, - vector aliases); - - vector> expressions; - vector columns; - shared_ptr child; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/query_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/query_relation.hpp deleted file mode 100644 index 4c6cd2a3d..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/query_relation.hpp +++ /dev/null @@ -1,43 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/query_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/parser/query_node.hpp" - -namespace duckdb { -class SelectStatement; - -class QueryRelation : public Relation { -public: - QueryRelation(const shared_ptr &context, unique_ptr select_stmt, string alias, - const string &query = ""); - ~QueryRelation() override; - - unique_ptr select_stmt; - string query; - string alias; - vector columns; - -public: - static unique_ptr ParseStatement(ClientContext &context, const string &query, const string &error); - unique_ptr GetQueryNode() override; - string GetQuery() override; - unique_ptr GetTableRef() override; - BoundStatement Bind(Binder &binder) override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; - -private: - unique_ptr GetSelectStatement(); -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/read_csv_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/read_csv_relation.hpp deleted file mode 100644 index 561435b90..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/read_csv_relation.hpp +++ /dev/null @@ -1,32 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/read_csv_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/execution/operator/csv_scanner/csv_reader_options.hpp" -#include "duckdb/main/relation/table_function_relation.hpp" -#include "duckdb/common/shared_ptr.hpp" -#include "duckdb/common/case_insensitive_map.hpp" - -namespace duckdb { - -class ReadCSVRelation : public TableFunctionRelation { -public: - ReadCSVRelation(const shared_ptr &context, const vector &csv_files, - named_parameter_map_t &&options, string alias = string()); - - string alias; - -protected: - void InitializeAlias(const vector &input); - -public: - Identifier GetAlias() override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/read_json_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/read_json_relation.hpp deleted file mode 100644 index f292bedb8..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/read_json_relation.hpp +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include "duckdb/main/relation/table_function_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/common/named_parameter_map.hpp" -#include "duckdb/parser/column_definition.hpp" -#include "duckdb/common/string.hpp" -#include "duckdb/common/vector.hpp" - -namespace duckdb { - -class ReadJSONRelation : public TableFunctionRelation { -public: - ReadJSONRelation(const shared_ptr &context, string json_file, named_parameter_map_t options, - bool auto_detect, string alias = ""); - ReadJSONRelation(const shared_ptr &context, vector &json_file, named_parameter_map_t options, - bool auto_detect, string alias = ""); - ~ReadJSONRelation() override; - string json_file; - string alias; - -public: - Identifier GetAlias() override; - -private: - void InitializeAlias(const vector &input); -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/setop_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/setop_relation.hpp deleted file mode 100644 index 66dbc2ac8..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/setop_relation.hpp +++ /dev/null @@ -1,35 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/setop_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/common/enums/set_operation_type.hpp" - -namespace duckdb { - -class SetOpRelation : public Relation { -public: - SetOpRelation(shared_ptr left, shared_ptr right, SetOperationType setop_type, - bool setop_all = false); - - shared_ptr left; - shared_ptr right; - SetOperationType setop_type; - vector columns; - bool setop_all; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/subquery_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/subquery_relation.hpp deleted file mode 100644 index 0c9c9e50d..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/subquery_relation.hpp +++ /dev/null @@ -1,35 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/subquery_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class SubqueryRelation : public Relation { -public: - SubqueryRelation(shared_ptr child, const string &alias); - shared_ptr child; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - -public: - bool InheritsColumnBindings() override { - return child->InheritsColumnBindings(); - } - Relation *ChildRelation() override { - return child->ChildRelation(); - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/table_function_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/table_function_relation.hpp deleted file mode 100644 index 11a7949d5..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/table_function_relation.hpp +++ /dev/null @@ -1,56 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/table_function_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { -struct TableFunctionInfo; - -class TableFunctionRelation : public Relation { -public: - TableFunctionRelation(const shared_ptr &context, string name, vector parameters, - named_parameter_map_t named_parameters, shared_ptr input_relation_p = nullptr, - bool auto_init = true, shared_ptr bind_info = nullptr); - TableFunctionRelation(const shared_ptr &context, string name, vector parameters, - named_parameter_map_t named_parameters, shared_ptr input_relation_p = nullptr, - bool auto_init = true, shared_ptr bind_info = nullptr); - TableFunctionRelation(const shared_ptr &context, string name, vector parameters, - shared_ptr input_relation_p = nullptr, bool auto_init = true, - shared_ptr bind_info = nullptr); - ~TableFunctionRelation() override { - } - - Identifier name; - vector parameters; - named_parameter_map_t named_parameters; - vector columns; - shared_ptr input_relation; - shared_ptr bind_info; - -public: - unique_ptr GetQueryNode() override; - unique_ptr GetTableRef() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; - void AddNamedParameter(const string &name, Value argument); - void RemoveNamedParameterIfExists(const string &name); - void SetNamedParameters(named_parameter_map_t &&named_parameters); - -private: - void InitializeColumns(); - -private: - //! Whether or not to auto initialize the columns on construction - bool auto_initialize; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/table_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/table_relation.hpp deleted file mode 100644 index d736d765c..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/table_relation.hpp +++ /dev/null @@ -1,40 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/table_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/main/table_description.hpp" - -namespace duckdb { - -class TableRelation : public Relation { -public: - TableRelation(const shared_ptr &context, unique_ptr description); - TableRelation(const shared_ptr &context, unique_ptr description); - - unique_ptr description; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; - - unique_ptr GetTableRef() override; - - void Insert(const vector> &values) override; - void Insert(vector>> &&expressions) override; - void Update(const string &update, const string &condition = string()) override; - void Update(vector column_names, vector> &&update, - unique_ptr condition = nullptr) override; - void Delete(const string &condition = string()) override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/update_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/update_relation.hpp deleted file mode 100644 index b51dcc1c1..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/update_relation.hpp +++ /dev/null @@ -1,41 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/update_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/parser/parsed_expression.hpp" - -namespace duckdb { - -class UpdateRelation : public Relation { -public: - UpdateRelation(shared_ptr &context, unique_ptr condition, - Identifier catalog_name, Identifier schema_name, Identifier table_name, - vector update_columns, vector> expressions); - - vector columns; - unique_ptr condition; - Identifier catalog_name; - Identifier schema_name; - Identifier table_name; - vector update_columns; - vector> expressions; - -public: - BoundStatement Bind(Binder &binder) override; - unique_ptr GetQueryNode() override; - string GetQuery() override; - const vector &Columns() override; - string ToString(idx_t depth) override; - bool IsReadOnly() override { - return false; - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/value_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/value_relation.hpp deleted file mode 100644 index 7289bf3ac..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/value_relation.hpp +++ /dev/null @@ -1,45 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/value_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" -#include "duckdb/parser/parsed_expression.hpp" - -namespace duckdb { - -class ValueRelation : public Relation { -public: - ValueRelation(const shared_ptr &context, const vector> &values, vector names, - string alias = "values"); - ValueRelation(const shared_ptr &context, vector>> &&expressions, - vector names, string alias = "values"); - ValueRelation(const shared_ptr &context, const vector> &values, - vector names, string alias = "values"); - ValueRelation(const shared_ptr &context, - vector>> &&expressions, vector names, - string alias = "values"); - ValueRelation(const shared_ptr &context, const string &values, vector names, - string alias = "values"); - - vector>> expressions; - vector names; - vector columns; - string alias; - -public: - unique_ptr GetQueryNode() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; - - unique_ptr GetTableRef() override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/view_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/view_relation.hpp deleted file mode 100644 index c4a9163b2..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/view_relation.hpp +++ /dev/null @@ -1,35 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/view_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class ViewRelation : public Relation { -public: - ViewRelation(const shared_ptr &context, Identifier schema_name, Identifier view_name); - ViewRelation(const shared_ptr &context, Identifier schema_name, Identifier view_name); - ViewRelation(const shared_ptr &context, unique_ptr ref, const string &view_name); - - Identifier schema_name; - Identifier view_name; - vector columns; - unique_ptr premade_tableref; - -public: - unique_ptr GetQueryNode() override; - unique_ptr GetTableRef() override; - - const vector &Columns() override; - string ToString(idx_t depth) override; - Identifier GetAlias() override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/write_csv_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/write_csv_relation.hpp deleted file mode 100644 index 14b5cc097..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/write_csv_relation.hpp +++ /dev/null @@ -1,35 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/write_csv_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class WriteCSVRelation : public Relation { -public: - WriteCSVRelation(shared_ptr child, string csv_file, identifier_map_t> options); - - shared_ptr child; - string csv_file; - vector columns; - identifier_map_t> options; - -public: - BoundStatement Bind(Binder &binder) override; - unique_ptr GetQueryNode() override; - string GetQuery() override; - const vector &Columns() override; - string ToString(idx_t depth) override; - bool IsReadOnly() override { - return false; - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/relation/write_parquet_relation.hpp b/src/duckdb/src/include/duckdb/main/relation/write_parquet_relation.hpp deleted file mode 100644 index 104a415bf..000000000 --- a/src/duckdb/src/include/duckdb/main/relation/write_parquet_relation.hpp +++ /dev/null @@ -1,35 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/main/relation/write_parquet_relation.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/main/relation.hpp" - -namespace duckdb { - -class WriteParquetRelation : public Relation { -public: - WriteParquetRelation(shared_ptr child, string parquet_file, identifier_map_t> options); - - shared_ptr child; - string parquet_file; - vector columns; - identifier_map_t> options; - -public: - BoundStatement Bind(Binder &binder) override; - unique_ptr GetQueryNode() override; - string GetQuery() override; - const vector &Columns() override; - string ToString(idx_t depth) override; - bool IsReadOnly() override { - return false; - } -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/setting_info.hpp b/src/duckdb/src/include/duckdb/main/setting_info.hpp index 1c50d2a6e..6b7831fa8 100644 --- a/src/duckdb/src/include/duckdb/main/setting_info.hpp +++ b/src/duckdb/src/include/duckdb/main/setting_info.hpp @@ -86,6 +86,7 @@ typedef void (*reset_global_function_t)(DatabaseInstance *db, DBConfig &config); typedef void (*reset_local_function_t)(ClientContext &context); typedef Value (*get_setting_function_t)(const ClientContext &context); typedef Value (*get_default_value_function_t)(); +typedef Value (*get_default_function_t)(const DBConfig &config); struct ConfigurationOption { const char *name; @@ -104,6 +105,16 @@ struct ConfigurationOption { bool is_deprecated = false; //! The typed default value of a generic setting get_default_value_function_t get_default_value = nullptr; + //! Computes the default of a generic setting whose default is not a constant + get_default_function_t default_function = nullptr; + +public: + //! Whether the option is a generic setting, stored in the user settings + bool IsGeneric() const { + return default_value || default_function; + } + //! The default of a generic setting + DUCKDB_API Value GetDefaultValue(const DBConfig &config) const; }; struct ConfigurationAlias { diff --git a/src/duckdb/src/include/duckdb/main/settings.hpp b/src/duckdb/src/include/duckdb/main/settings.hpp index 06103698e..e03077c2c 100644 --- a/src/duckdb/src/include/duckdb/main/settings.hpp +++ b/src/duckdb/src/include/duckdb/main/settings.hpp @@ -34,7 +34,7 @@ struct Settings { if (TryGetSettingInternal(source, OP::SettingIndex, result) && !result.IsNull()) { return FromValue(result); } - return FromDefault(OP::DefaultValue); + return GetDefault(source, 0); } template @@ -54,6 +54,18 @@ struct Settings { } private: + //! The default of a setting with a default function + template + static auto GetDefault(const SOURCE &source, int) + -> decltype(OP::GetDefaultValue(std::declval()), typename OP::RETURN_TYPE()) { + return FromValue(OP::GetDefaultValue(GetConfigInternal(source))); + } + //! The default of a setting with a constant default + template + static typename OP::RETURN_TYPE GetDefault(const SOURCE &, long) { + return FromDefault(OP::DefaultValue); + } + //! Converts the value of a setting to its return type template static typename std::enable_if::value, T>::type FromValue(const Value &value) { @@ -212,6 +224,10 @@ struct Settings { static bool TryGetSettingInternal(const DBConfig &config, idx_t setting_index, Value &result); static bool TryGetSettingInternal(const ClientContext &context, idx_t setting_index, Value &result); static bool TryGetSettingInternal(const Context &context, idx_t setting_index, Value &result); + static const DBConfig &GetConfigInternal(const DatabaseInstance &db); + static const DBConfig &GetConfigInternal(const DBConfig &config); + static const DBConfig &GetConfigInternal(const ClientContext &context); + static const DBConfig &GetConfigInternal(const Context &context); static void SetSettingInternal(DatabaseInstance &db, idx_t setting_index, SetScope scope, Value target_value); static void SetSettingInternal(DBConfig &config, idx_t setting_index, SetScope scope, Value target_value); @@ -520,9 +536,10 @@ struct AsyncThreadsSetting { static constexpr const char *InputType = "BIGINT"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; - static void SetGlobal(DatabaseInstance *db, DBConfig &config, const Value ¶meter); - static void ResetGlobal(DatabaseInstance *db, DBConfig &config); - static Value GetSetting(const ClientContext &context); + static Value GetDefaultValue(const DBConfig &config); + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct AutoCheckpointSkipWalThresholdSetting { @@ -855,6 +872,19 @@ struct ForceBitpackingModeSetting { static void OnSet(SettingCallbackInfo &info, Value &input); }; +struct DebugForceBloomFilterReplicationSetting { + using RETURN_TYPE = bool; + static constexpr const char *Name = "debug_force_bloom_filter_replication"; + static constexpr const char *Description = + "Force join Bloom filter copies regardless of machine size or allocation locality."; + static constexpr const char *InputType = "BOOLEAN"; + static constexpr bool IsDebug = true; + static constexpr bool IsDeprecated = false; + static constexpr const char *DefaultValue = "false"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_DEFAULT; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); +}; + struct DebugForceCheckpointSetting { using RETURN_TYPE = bool; static constexpr const char *Name = "debug_force_checkpoint"; @@ -1928,9 +1958,10 @@ struct HTTPProxySetting { static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; - static void SetGlobal(DatabaseInstance *db, DBConfig &config, const Value ¶meter); - static void ResetGlobal(DatabaseInstance *db, DBConfig &config); - static Value GetSetting(const ClientContext &context); + static Value GetDefaultValue(const DBConfig &config); + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct HTTPProxyPasswordSetting { @@ -2276,9 +2307,10 @@ struct MaxMemorySetting { static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; - static void SetGlobal(DatabaseInstance *db, DBConfig &config, const Value ¶meter); - static void ResetGlobal(DatabaseInstance *db, DBConfig &config); - static Value GetSetting(const ClientContext &context); + static Value GetDefaultValue(const DBConfig &config); + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct MaxStreamingBufferSizeSetting { @@ -2291,9 +2323,10 @@ struct MaxStreamingBufferSizeSetting { static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; - static void SetLocal(ClientContext &context, const Value ¶meter); - static void ResetLocal(ClientContext &context); - static Value GetSetting(const ClientContext &context); + static constexpr const char *DefaultValue = "10.0 MiB"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct MaxTempDirectorySizeSetting { @@ -2784,9 +2817,10 @@ struct StorageCompatibilityVersionSetting { static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; - static void SetGlobal(DatabaseInstance *db, DBConfig &config, const Value ¶meter); - static void ResetGlobal(DatabaseInstance *db, DBConfig &config); - static Value GetSetting(const ClientContext &context); + static constexpr const char *DefaultValue = "latest"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct TableFunctionIdentifierConversionSetting { @@ -2835,9 +2869,10 @@ struct ThreadsSetting { static constexpr const char *InputType = "BIGINT"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; - static void SetGlobal(DatabaseInstance *db, DBConfig &config, const Value ¶meter); - static void ResetGlobal(DatabaseInstance *db, DBConfig &config); - static Value GetSetting(const ClientContext &context); + static Value GetDefaultValue(const DBConfig &config); + static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_ONLY; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); }; struct TrackedMetricsSetting { diff --git a/src/duckdb/src/include/duckdb/main/user_settings.hpp b/src/duckdb/src/include/duckdb/main/user_settings.hpp index 73ac3ae24..f07e39d3d 100644 --- a/src/duckdb/src/include/duckdb/main/user_settings.hpp +++ b/src/duckdb/src/include/duckdb/main/user_settings.hpp @@ -36,7 +36,6 @@ struct UserSettingsMap { vector settings; }; -#ifndef __MINGW32__ struct GlobalUserSettings; struct CachedGlobalSettings { @@ -50,7 +49,29 @@ struct CachedGlobalSettings { identifier_map_t extension_setting_indexes; hugeint_t uuid; }; -#endif + +//! The settings cache of a worker thread. While it is initialized, the thread reads settings through it instead of +//! through the thread_local cache, whose first use registers a destructor that glibc cannot fail to allocate without +//! ending the process +class WorkerSettingsCache { +public: + WorkerSettingsCache(); + ~WorkerSettingsCache(); + WorkerSettingsCache(const WorkerSettingsCache &) = delete; + WorkerSettingsCache &operator=(const WorkerSettingsCache &) = delete; + WorkerSettingsCache(WorkerSettingsCache &&) = delete; + WorkerSettingsCache &operator=(WorkerSettingsCache &&) = delete; + +public: + bool IsInitialized() const; + //! Create the cache, this allocates + void Initialize(); + +private: + unique_ptr cache; + //! The cache the thread read through before, restored when this one goes away + optional_ptr previous; +}; struct GlobalUserSettings { public: diff --git a/src/duckdb/src/include/duckdb/optimizer/aggregate_function_rewriter.hpp b/src/duckdb/src/include/duckdb/optimizer/aggregate_function_rewriter.hpp index 0acb74669..3ddb8fa15 100644 --- a/src/duckdb/src/include/duckdb/optimizer/aggregate_function_rewriter.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/aggregate_function_rewriter.hpp @@ -17,12 +17,17 @@ class Optimizer; //! Rewrites aggregate functions. Currently registered rules: //! AVG(x) -> SUM(x) / COUNT(x) //! SUM(x + C) -> SUM(x) + C * COUNT(x) +//! LIST(x ORDER BY x) -> LIST_SORT(LIST(x)) +//! F(CASE WHEN c THEN x END) -> F(x) FILTER (WHERE c), as a separate pass (RewriteCaseToFilter) class AggregateFunctionRewriter { public: explicit AggregateFunctionRewriter(Optimizer &optimizer); ~AggregateFunctionRewriter(); void Optimize(unique_ptr &op); + //! Rewrites f(CASE WHEN c THEN x END) -> f(x) FILTER (WHERE c). The table statistics are only consulted if + //! use_statistics is set: they have to describe the rows that the plan scans + void RewriteCaseToFilter(unique_ptr &op, bool use_statistics); private: Optimizer &optimizer; diff --git a/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp b/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp index 3abc00692..4ec9b4bf0 100644 --- a/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp @@ -10,30 +10,30 @@ #include "duckdb/planner/logical_operator_visitor.hpp" +#include "duckdb/optimizer/distinctness.hpp" #include "duckdb/planner/column_binding_map.hpp" namespace duckdb { struct BoundOrderByNode; +//! Simplifies the keys of orderings and of window partitions / orderings using the unique column combinations of +//! their input. The unique column combinations themselves are inferred by Distinctness. class ApplyFunctionalDependencies : public LogicalOperatorVisitor { public: - explicit ApplyFunctionalDependencies(bool read_only = false) : read_only(read_only) { + ApplyFunctionalDependencies() : distinctness(DistinctnessPropagation::UNARY_OPERATORS) { } + //! The unique column combinations of the output of an operator static vector GetUniqueColumnCombinations(LogicalOperator &op) { - ApplyFunctionalDependencies visitor(true); - visitor.VisitOperator(op); - return visitor.result; + Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS); + return distinctness.GetUniqueSets(op); } void VisitOperator(LogicalOperator &op) override; void VisitExpression(unique_ptr *expression) override; private: - void VisitLogicalGet(LogicalGet &get); - void VisitLogicalAggregate(LogicalAggregate &aggr); - void VisitLogicalProjection(LogicalProjection &projection); void VisitLogicalOrder(LogicalOrder &order); void VisitWindowExpression(BoundWindowExpression &wexpr) const; @@ -41,7 +41,10 @@ class ApplyFunctionalDependencies : public LogicalOperatorVisitor { void VisitPartitioning(vector> &partitions) const; void VisitOrderBys(vector &orders) const; - const bool read_only; + //! The order keys and window partitions that this visitor rewrites are not read by the inference of unique sets, + //! and no operator is replaced, so the cached unique sets stay valid during the visit + Distinctness distinctness; + //! The unique column combinations of the input of the operator that is being simplified vector result; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/column_binding_replacer.hpp b/src/duckdb/src/include/duckdb/optimizer/column_binding_replacer.hpp index 8d59b2b09..54fb21109 100644 --- a/src/duckdb/src/include/duckdb/optimizer/column_binding_replacer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/column_binding_replacer.hpp @@ -37,6 +37,8 @@ struct ReplacementBinding { class BindingReplacementGraph { public: ColumnBinding Resolve(ColumnBinding binding) const; + //! Resolve a binding and any type replacement through the graph. + ReplacementBinding ResolveReplacement(ColumnBinding binding) const; //! Find the direct replacement edge for a binding, if any optional_ptr Find(ColumnBinding old_binding) const; bool TryAdd(const ReplacementBinding &replacement); @@ -59,7 +61,6 @@ class BindingReplacementGraph { } private: - ReplacementBinding ResolveReplacement(ColumnBinding binding) const; vector replacement_bindings; //! Index into replacement_bindings by old_binding (unique by construction) column_binding_map_t binding_slots; @@ -69,6 +70,8 @@ class BindingReplacementGraph { class ColumnBindingReplacer : public LogicalOperatorVisitor { public: ColumnBindingReplacer(); + //! Borrow a graph for transitive lookups without copying its replacement edges. + explicit ColumnBindingReplacer(const BindingReplacementGraph &replacements); public: //! Update each operator of the plan, recursing directly into children without resolving projection maps @@ -98,6 +101,7 @@ class ColumnBindingReplacer : public LogicalOperatorVisitor { vector replacement_bindings; private: + optional_ptr replacement_graph; column_binding_map_t replacement_index; bool use_index = false; }; @@ -105,6 +109,8 @@ class ColumnBindingReplacer : public LogicalOperatorVisitor { //! Like ColumnBindingReplacer, but also updates correlated-column metadata and nested subquery plans. class CorrelatedColumnBindingReplacer : public ColumnBindingReplacer { public: + using ColumnBindingReplacer::ColumnBindingReplacer; + void VisitOperatorBindings(LogicalOperator &op) override; protected: diff --git a/src/duckdb/src/include/duckdb/optimizer/constant_or_null_simplification.hpp b/src/duckdb/src/include/duckdb/optimizer/constant_or_null_simplification.hpp index f4d535b0e..4d61544c1 100644 --- a/src/duckdb/src/include/duckdb/optimizer/constant_or_null_simplification.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/constant_or_null_simplification.hpp @@ -21,10 +21,12 @@ class ConstantOrNullSimplification { unique_ptr Optimize(unique_ptr op); private: - unique_ptr OptimizeInternal(unique_ptr op, bool plan_has_side_effects); + void OptimizeInternal(unique_ptr &op, bool plan_has_side_effects, + NotNullExpressionAnalyzer &analyzer); unique_ptr SimplifyExpression(LogicalOperator &input, unique_ptr expr, NotNullExpressionAnalyzer &analyzer, bool allow_folding); - unique_ptr OptimizeFilter(unique_ptr op, bool plan_has_side_effects); + void OptimizeFilter(unique_ptr &op, bool plan_has_side_effects, + NotNullExpressionAnalyzer &analyzer); private: ClientContext &context; diff --git a/src/duckdb/src/include/duckdb/optimizer/cte_filter_pusher.hpp b/src/duckdb/src/include/duckdb/optimizer/cte_filter_pusher.hpp index aeb2c7311..e528b4155 100644 --- a/src/duckdb/src/include/duckdb/optimizer/cte_filter_pusher.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/cte_filter_pusher.hpp @@ -38,6 +38,10 @@ class CTEFilterPusher { private: //! Find all materialized CTEs and their refs void FindCandidates(LogicalOperator &op); + //! Filters the reference of a materialized CTE on the left side of a SEMI join (or of a MARK join below a filter on + //! its mark) by what the filters on the right side imply for the join keys, when that makes every reference of the + //! CTE a filtered one + void GenerateSemiJoinFilters(LogicalOperator &op); bool CanPushFilter(const MaterializedCTEInfo &info); bool HasValidDependency(const MaterializedCTEInfo &info); //! Creates an OR filter and pushes it into a materialized CTE diff --git a/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp b/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp new file mode 100644 index 000000000..52497ab0a --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp @@ -0,0 +1,83 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/distinctness.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/reference_map.hpp" +#include "duckdb/common/unique_ptr.hpp" +#include "duckdb/common/vector.hpp" +#include "duckdb/planner/column_binding_map.hpp" + +namespace duckdb { + +class ClientContext; +class Expression; +class LogicalAggregate; +class LogicalComparisonJoin; +class LogicalGet; +class LogicalOperator; +class LogicalProjection; + +//! The operators that unique sets are forwarded through +enum class DistinctnessPropagation : uint8_t { + //! Filters, limits, orderings, windows and projections + UNARY_OPERATORS, + //! Additionally samples, the left side of SEMI / ANTI / MARK / SINGLE joins, and a side of an INNER join (the + //! left side of a LEFT join) whose other side is itself distinct on its equality keys + UNARY_OPERATORS_AND_JOINS +}; + +//! Structural proofs that the output of an operator has at most one row per value of a set of columns, where NULLs +//! count as one value (like for DISTINCT and GROUP BY). This is the one place where unique sets are inferred. +//! The sources are the groups of an aggregate with a single grouping set and the PRIMARY KEY / UNIQUE NOT NULL +//! constraints of a scanned table. They are forwarded through operators that never duplicate rows (see +//! DistinctnessPropagation). Statistics (distinct counts) are estimates and are never used. +//! The unique sets of an operator are computed once and cached by the identity of the operator, so that a +//! bottom-up pass over a plan stays linear. An instance is therefore only valid for the analysis of a stable plan: +//! once a pass replaces or removes an operator that has been asked about (or one below it), or changes what the +//! unique sets are derived from (the scanned columns, groups and grouping sets, projection expressions, join types +//! and join conditions), the instance must not be used anymore. Rewrites of anything else (e.g. order keys, window +//! partitions) and of operators above everything that has been asked about keep it valid. +class Distinctness { +public: + //! The maximum number of unique sets that a join forwards + static constexpr idx_t MAX_UNIQUE_SETS = 32; + +public: + //! A context allows cast proofs that account for registered overrides. + explicit Distinctness(DistinctnessPropagation propagation, optional_ptr context = nullptr) + : propagation(propagation), context(context) { + } + + //! Whether the output of the operator has at most one row per value of the keys + bool IsDistinctOn(LogicalOperator &op, const column_binding_set_t &keys); + //! Checks expression keys, including aliases and built-in injective casts. + bool IsDistinctOn(LogicalOperator &op, const vector> &keys); + //! The sets of columns the output of the operator is distinct on (cached) + const vector &GetUniqueSets(LogicalOperator &op); + //! Gets the equality keys (= or IS NOT DISTINCT FROM) of the left (child_idx 0) or right (child_idx 1) side of a + //! join. Returns false if there is no equality, or if the key of an equality is not a plain column reference + static bool GetJoinEqualityKeys(const LogicalComparisonJoin &join, idx_t child_idx, column_binding_set_t &keys); + +private: + bool IsDistinctOnProjectedKeys(LogicalOperator &op, const column_binding_set_t &keys); + vector ComputeUniqueSets(LogicalOperator &op); + static vector ComputeScanUniqueSets(LogicalGet &get); + static vector ComputeAggregateUniqueSets(LogicalAggregate &aggr); + vector ComputeProjectionUniqueSets(LogicalProjection &projection); + vector ComputeJoinUniqueSets(LogicalComparisonJoin &join); + bool IsDistinctOnJoinKeys(LogicalComparisonJoin &join, idx_t child_idx); + +private: + const DistinctnessPropagation propagation; + const optional_ptr context; + reference_map_t> unique_sets; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp index f777a7eba..6c31f0bec 100644 --- a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp @@ -28,6 +28,7 @@ class DuplicateEliminatedDomainOptimizer : public LogicalOperatorVisitor { bool TryOptimizeDomain(unique_ptr &op, idx_t aggregate_side, idx_t condition_index); bool TryOptimizeRuntimeDomain(unique_ptr &op, LogicalAggregate &aggregate, idx_t aggregate_side, idx_t demand_index, ExpressionType comparison); + bool TryPullUpOuterDomainJoin(unique_ptr &op); private: Optimizer &optimizer; diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp index 6e7a5ffe8..ce71b51d3 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_pullup.hpp @@ -14,17 +14,20 @@ #include "duckdb/common/vector.hpp" namespace duckdb { +class ClientContext; class FilterPullup { public: - explicit FilterPullup(bool pullup = false, bool add_column = false) - : can_pullup(pullup), can_add_column(add_column) { + //! The context is needed for the collations an EXCEPT / INTERSECT compares its columns with + explicit FilterPullup(optional_ptr context = nullptr, bool pullup = false, bool add_column = false) + : context(context), can_pullup(pullup), can_add_column(add_column) { } //! Perform filter pullup unique_ptr Rewrite(unique_ptr op); private: + optional_ptr context; vector> filters_expr_pullup; // only pull up filters when there is a fork diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp index c14531db0..644a0ca4a 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp @@ -22,7 +22,7 @@ class FilterPushdown { public: enum class ProjectionMode : uint8_t { ALLOW_COMPUTED_EXPRESSIONS, PRESERVE_COMPUTED_EXPRESSIONS }; - explicit FilterPushdown(Optimizer &optimizer, bool convert_mark_joins = true, + explicit FilterPushdown(Optimizer &optimizer, ProjectionMode projection_mode = ProjectionMode::ALLOW_COMPUTED_EXPRESSIONS); //! Perform filter pushdown @@ -30,8 +30,6 @@ class FilterPushdown { //! Return a reference to the client context (from the optimizer) ClientContext &GetContext(); - void CheckMarkToSemi(LogicalOperator &op, const unordered_set &table_bindings); - //! Whether a filter carrying a barrier may be pushed through this operator - i.e. whether the operator is //! guaranteed not to remove any rows. A barred expression must never be evaluated on rows that an operator below //! it filters out. @@ -62,7 +60,6 @@ class FilterPushdown { private: Optimizer &optimizer; FilterCombiner combiner; - bool convert_mark_joins; ProjectionMode projection_mode; vector> filters; diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_statistics.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_statistics.hpp index ccfd380d0..cce14d702 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_statistics.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_statistics.hpp @@ -24,6 +24,8 @@ class FilterStatisticsOptimizer { private: bool HasMultiBindingFilter(const LogicalOperator &op) const; bool ContainsDelimJoin(const LogicalOperator &op) const; + //! Whether a filter or join condition of the plan reads a scanned column that holds only NULLs + bool ComparesAllNullColumn(LogicalOperator &plan) const; private: Optimizer &optimizer; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp b/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp index 90252ef57..138ad22c9 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp @@ -8,82 +8,113 @@ #pragma once -#include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/helper.hpp" +#include "duckdb/common/shared_ptr.hpp" #include "duckdb/common/typedefs.hpp" #include "duckdb/common/unique_ptr.hpp" #include "duckdb/common/unordered_map.hpp" #include "duckdb/common/unordered_set.hpp" -#include "duckdb/planner/column_binding.hpp" -#include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression.hpp" #include "duckdb/planner/logical_operator.hpp" #include "duckdb/planner/logical_operator_visitor.hpp" namespace duckdb { class JoinElimination; -class PipelineInfo; - -struct DistinctGroupRef { - column_binding_set_t distinct_group; - unordered_set ref_column_ids; -}; class PipelineInfo { public: - unique_ptr root = nullptr; + //! The tables the operators above (and the conditions of the joins above) reference unordered_set ref_table_ids; - unordered_map distinct_groups; + //! The operators above return the same result when rows of this pipeline are repeated: an aggregate for which + //! LogicalAggregate::IgnoresDuplicates holds (DISTINCT, GROUP BY without aggregates, min / max, DISTINCT + //! aggregates) or the right side of a SEMI / ANTI join, with nothing in between that sees how often a row occurs. + //! It only passes through projections, filters, UNNEST and joins without a volatile expression; every other + //! operator (LIMIT, window, set operation, ...) ends it + bool ignores_duplicates = false; - // pushdown filter condition(ex in table scan operator), - // if have outer table columns then cannot elimination + //! Found in this pipeline: a pushed-down filter condition (e.g. in a table scan operator) bool has_filter = false; - optional_ptr join_parent = nullptr; - idx_t join_index = 0; - public: + //! The state a pipeline below starts with: what is inherited from the operators above, nothing that was found. + //! Whether the pipeline below ignores duplicates is decided by the operator that starts it PipelineInfo CreateChild() { auto result = PipelineInfo(); result.ref_table_ids = ref_table_ids; - result.distinct_groups = distinct_groups; return result; } }; +//! What a removed subtree would no longer do, beyond returning rows: evaluate a volatile expression (nextval, random), +//! modify data, or run a table function that declares itself VOLATILE. A reference to a materialized CTE counts with +//! everything in the definition of that CTE: once the reference is gone, the columns only it read are pruned from the +//! definition, expressions included. +class RemovedSubtreeEffects { +public: + //! Registers the CTEs that are defined in the plan + explicit RemovedSubtreeEffects(LogicalOperator &plan); + + //! Whether removing the subtree would skip an effect + bool HasEffect(LogicalOperator &subtree); + +private: + void CollectDefinitions(LogicalOperator &op); + //! Whether the definition of a materialized CTE has an effect; computed once per CTE + bool DefinitionHasEffect(TableIndex cte_index); + + //! The materialized CTEs of the plan (the CTE operators; the definition is their first child) + unordered_map> materialized_ctes; + //! The recursive CTEs of the plan: a reference to one reads the working table of a recursion that is part of the + //! plan around the reference + unordered_set recursive_ctes; + unordered_map definition_has_effect; +}; + class JoinElimination : public LogicalOperatorVisitor { public: explicit JoinElimination() { } - void OptimizeChildren(LogicalOperator &op, optional_ptr parent, idx_t idx); - // with specific condition we can eliminate a (left/right, semi, inner) join. - // exemplify left/right join eliminaion condition: - // 1. output can only have outer table columns - // 2. join result cannot filter by inner table columns(ex. in where clause/ having clause ...) - // 3. must ensure each outer row can match at most one inner table row, such as: - // 1) inner table join condition is unique(ex. 1. join conditions have inner table's primary key 2. inner table - // join condition columns contains a whole distinct group) 2) join result columns contains a whole distinct group + // A LEFT / RIGHT join is replaced by its outer side when + // 1. nothing above the join reads a column of its inner side (the output, filters, the conditions of the joins + // above only read the outer side), + // 2. neither the join condition nor the inner side has a volatile expression (nextval, random): they would not + // be evaluated any more. The inner side must not have any other effect either (RemovedSubtreeEffects), and + // 3. the join cannot change how often an outer row occurs in a way that is visible. There are two separate proofs: + // a) the operators above ignore duplicates (PipelineInfo::ignores_duplicates): the join only repeats outer rows + // b) every outer row matches at most one inner row: the inner side is distinct on the columns its equality + // conditions compare (Distinctness: a DISTINCT / GROUP BY, a PRIMARY KEY). This holds whatever is above the + // join. A SINGLE join is only removed by this proof: it raises an error on a second match. unique_ptr Optimize(unique_ptr op); - void OptimizeInternal(unique_ptr op); + //! Whether Optimize removed a join + bool RemovedJoin() const; unique_ptr VisitReplace(BoundColumnRefExpression &expr, unique_ptr *expr_ptr) override; unique_ptr CreateChildren() { auto result = make_uniq(); result->pipe_info = pipe_info.CreateChild(); + result->effects = effects; return result; } private: - unique_ptr TryEliminateJoin(); - // void ExtractDistinctReferences(vector &expressions, idx_t target_table_index); - bool ContainDistinctGroup(vector &exprs); + //! Analyses the operators of this pipeline from `op` down. A join is replaced in place, through `op`, by its outer + //! side when it can be removed; `replaceable`: whether `op` itself may be replaced (false for the root of the + //! plan and for the children of operators that may read their columns by position) + void OptimizeOperator(unique_ptr &op, bool replaceable); + //! Analyses child `child_idx` of `op` with `child_optimizer` and keeps the projection map `op` has for that child + //! valid when a join was removed below + void OptimizeChild(LogicalOperator &op, idx_t child_idx, JoinElimination &child_optimizer, bool replaceable); + //! Analyses the join `op` of this pipeline and both of its sides, and removes it when it can + void OptimizeJoin(unique_ptr &op); + void OptimizeJoinChild(LogicalOperator &join, idx_t child_idx, JoinElimination &child); + //! Replaces the join `op` by its outer side when it can; returns whether it did + bool TryEliminateJoin(unique_ptr &op, JoinElimination &left_child, JoinElimination &right_child); PipelineInfo pipe_info; - - optional_ptr children_root; - vector> children; - - unique_ptr left_child; - unique_ptr right_child; + //! Shared by the optimizers of all pipelines of one plan + shared_ptr effects; + //! The number of joins removed in this pipeline and the pipelines below it + idx_t removed_joins = 0; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp index f91e1160f..ee85b054f 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp @@ -62,8 +62,8 @@ struct JoinOrderOperator { vector costing_predicate_indices; //! LEFT ON residuals not covered by a costing predicate or an equivalent equality key. vector> residual_predicates; - //! Whether the complete conditions must be applied by this operator occurrence. This is decided before conflict - //! rule simplification, which can erase conflicts already absorbed by the syntactic eligibility set. + //! Whether this occurrence must apply its complete conditions together. + //! Independent predicates must satisfy each filtering dependency or lie outside its subtree. bool must_apply_as_operator = false; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_simplification.hpp b/src/duckdb/src/include/duckdb/optimizer/join_simplification.hpp new file mode 100644 index 000000000..66be1849e --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_simplification.hpp @@ -0,0 +1,147 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_simplification.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/enums/expression_type.hpp" +#include "duckdb/common/table_index.hpp" +#include "duckdb/common/unordered_set.hpp" +#include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/logical_operator.hpp" + +namespace duckdb { + +class ClientContext; +class Expression; +struct JoinCondition; +class JoinToSemiJoin; +class LogicalAggregate; +class LogicalComparisonJoin; +class LogicalFilter; +class LogicalJoin; +class LogicalOrder; +class LogicalProjection; +class LogicalTopN; + +//! The two points of the optimizer pipeline at which joins are simplified +enum class JoinSimplificationPhase : uint8_t { + //! On the plan as bound, before filter pushdown: an INNER join against a relation that only filters another one + //! becomes a SEMI join (JoinToSemiJoin). The predicates still sit where the query put them, in filters above + //! cross products and in join conditions, which is what that rewrite collects + BEFORE_FILTER_PUSHDOWN, + //! After filter pushdown, before join ordering: outer joins whose NULL-extended rows are filtered become LEFT, + //! RIGHT, INNER or ANTI joins. The filters have reached the joins they constrain by then + AFTER_FILTER_PUSHDOWN +}; + +//! Simplifies joins from what the operators above them need: one traversal that carries, down the plan, the columns +//! that have to stay available, the columns whose NULLs are filtered or required, whether repeated rows matter and +//! which tables are read. Each phase applies the rewrites that belong to it: +//! - outer joins are simplified if NULL-extended rows are filtered in a way that changes the join semantics; +//! - INNER joins against relations that only filter become SEMI joins if repeated rows do not matter. +class JoinSimplification { +public: + JoinSimplification(ClientContext &context, JoinSimplificationPhase phase); + ~JoinSimplification(); + +public: + void Optimize(unique_ptr &plan); + +private: + //! What is known about the operators above the operator being visited, apart from the column sets below. + //! Unlike those, it differs between the children of one operator + struct ParentInfo { + //! Whether the operators above give the same result over the rows of this operator with or without repeats + bool ignores_duplicates = false; + //! Whether `read_tables` is known: every operator above reads the columns of this one through expressions + bool reads_known = false; + //! The tables the operators above read through expressions, up to the closest projection or aggregate + unordered_set read_tables; + //! Whether the parent is a node of the same region of filters, cross products and INNER joins + bool in_region = false; + }; + + //! A context below an operator that does not pass the column sets on + JoinSimplification(JoinSimplification &parent, column_binding_set_t required_columns); + + void VisitOperator(unique_ptr &op_ptr); + //! Visit child `child_index` of `op` with the column sets of this context / of a new context that requires + //! `required_columns`. A projection map `op` holds for the child follows the child's bindings, which a rewrite + //! below may change + void VisitChild(LogicalOperator &op, idx_t child_index, ParentInfo info); + void VisitChildInNewContext(LogicalOperator &op, idx_t child_index, column_binding_set_t required_columns, + ParentInfo info); + //! The ParentInfo of the children of `op`, which passes its rows on (a filter, a join): it reads what the + //! operators above read and what its own expressions read + ParentInfo PassThroughInfo(const LogicalOperator &op, bool ignores_duplicates) const; + //! The ParentInfo below an operator that hides what is above it + static ParentInfo UnknownInfo(); + bool SimplifiesOuterJoins() const { + return phase == JoinSimplificationPhase::AFTER_FILTER_PUSHDOWN; + } + + //! Extract and propagate column references through expressions and join conditions + void AddColumnReferences(const Expression &expr, column_binding_set_t &bindings); + void AddRequiredColumns(const Expression &expr); + void AddRequiredColumns(const JoinCondition &condition); + void AddRequiredColumns(const vector &conditions); + bool GetColumnBinding(const Expression &expr, ColumnBinding &binding); + bool GetNullPreservingColumnBinding(const Expression &expr, ColumnBinding &binding); + + //! Track predicates that require columns to be NULL or reject NULL values + void HandleExpression(const Expression &expr); + void HandleFilterExpression(const Expression &expr); + bool HandleIsNullExpression(const Expression &expr); + bool IsNullFilter(const Expression &expr, ColumnBinding &binding); + void InitializeRequiredColumns(LogicalOperator &op); + bool FiltersNulls(ExpressionType comparison_type); + + //! Rewrite joins based on the NULL constraints collected from operators above them + bool TryConvertLeftToAntiJoin(LogicalComparisonJoin &join); + bool HasNullRequiredColumns(const vector &bindings); + bool HasRequiredColumns(const vector &bindings); + void MarkEliminatedNullColumns(const vector &bindings); + void EraseNullRequiredColumns(LogicalOperator &child); + vector GetRightBindings(LogicalJoin &join); + void SimplifyOuterJoinType(LogicalComparisonJoin &join); + + //! Visit operators while preserving only the constraints that can safely pass through each operator type + void VisitComparisonJoin(LogicalComparisonJoin &join, unique_ptr &op_ptr); + void VisitInnerOrSemiJoin(LogicalComparisonJoin &join, LogicalOperator &op); + void VisitOuterJoin(LogicalComparisonJoin &join, unique_ptr &op_ptr); + void VisitProjection(LogicalProjection &projection, LogicalOperator &op); + void VisitFilter(LogicalFilter &filter, LogicalOperator &op); + void VisitOrder(LogicalOrder &order, LogicalOperator &op); + void VisitTopN(LogicalTopN &top_n, LogicalOperator &op); + void VisitAggregate(LogicalAggregate &aggregate, LogicalOperator &op); + void VisitUnsupportedOperator(LogicalOperator &op); + //! The children of a join that the column sets do not pass through: `left` / `right` say whether the side + //! may see repeated rows of its child without a change of the result + void VisitJoinChildren(LogicalOperator &op, bool left_ignores_duplicates, bool right_ignores_duplicates, + bool keep_context); + +private: + JoinSimplificationPhase phase; + //! The region rewrite of the first phase; shared by the contexts of one traversal + optional_ptr join_to_semi_join; + unique_ptr owned_join_to_semi_join; + //! What is known about the operators above the operator being visited + ParentInfo parent; + + //! Columns that have their NULL values filtered + column_binding_set_t null_filtered_columns; + //! Columns that are required to be NULL + column_binding_set_t null_required_columns; + //! Columns that are known to be NULL after rewriting a LEFT join to an ANTI join + column_binding_set_t eliminated_null_columns; + //! Columns that must remain available to operators above the current point in the plan + column_binding_set_t required_columns; + bool initialized_required_columns = false; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_to_semi_join.hpp b/src/duckdb/src/include/duckdb/optimizer/join_to_semi_join.hpp new file mode 100644 index 000000000..ada604b4c --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_to_semi_join.hpp @@ -0,0 +1,50 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_to_semi_join.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/table_index.hpp" +#include "duckdb/common/unique_ptr.hpp" +#include "duckdb/common/unordered_set.hpp" + +namespace duckdb { + +class ClientContext; +class JoinRegionRewriter; +class LogicalOperator; + +//! The region rewrite of JoinSimplification: in a region of filters, cross products and INNER joins, turns the join +//! against a relation that is only read by predicates comparing it with one other relation into a SEMI join on that +//! relation, when the rows the join repeats do not matter. Collects the region and relocates its predicates. +//! See join_to_semi_join.cpp for the conditions. +class JoinToSemiJoin { +public: + explicit JoinToSemiJoin(ClientContext &context); + ~JoinToSemiJoin(); + + //! Looks at the CTEs of the plan; to be called once, before the traversal + void Initialize(LogicalOperator &plan); + //! A node of a join region: a filter, a cross product or a plain INNER join + static bool IsRegionNode(const LogicalOperator &op); + //! Applies one rewrite to the region rooted at `op` and returns whether it did. `ignores_duplicates`: the + //! operators above give the same result over the rows of the region with or without repeats; `read_tables`: the + //! tables they read through expressions + bool RewriteRegion(unique_ptr &op, bool ignores_duplicates, + const unordered_set &read_tables); + //! To be called for a materialized CTE before its references are visited + void VisitMaterializedCTE(const LogicalOperator &op); + + //! The tables the expressions of `op` read + static void AddReadTables(const LogicalOperator &op, unordered_set &tables); + static bool HasVolatileExpression(const LogicalOperator &op); + +private: + unique_ptr rewriter; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp b/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp new file mode 100644 index 000000000..4d9120cbe --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp @@ -0,0 +1,35 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/mark_join_simplifier.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/planner/logical_operator.hpp" + +namespace duckdb { + +class BindingReplacementGraph; +class NotNullExpressionAnalyzer; +class Optimizer; + +//! Convert filtered MARK joins while preserving their output schema. +class MarkJoinSimplifier { +public: + explicit MarkJoinSimplifier(Optimizer &optimizer); + void Optimize(unique_ptr &plan); + +private: + void Rewrite(unique_ptr &op, NotNullExpressionAnalyzer &nullability, + BindingReplacementGraph &replacements); + bool TrySimplify(unique_ptr &op, NotNullExpressionAnalyzer &nullability, + BindingReplacementGraph &replacements); + +private: + Optimizer &optimizer; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/outer_join_simplification.hpp b/src/duckdb/src/include/duckdb/optimizer/outer_join_simplification.hpp deleted file mode 100644 index 05bb42d73..000000000 --- a/src/duckdb/src/include/duckdb/optimizer/outer_join_simplification.hpp +++ /dev/null @@ -1,86 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/optimizer/outer_join_simplification.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/enums/expression_type.hpp" -#include "duckdb/planner/column_binding_map.hpp" -#include "duckdb/planner/logical_operator_visitor.hpp" - -namespace duckdb { - -class Expression; -struct JoinCondition; -class LogicalAggregate; -class LogicalComparisonJoin; -class LogicalFilter; -class LogicalJoin; -class LogicalOrder; -class LogicalProjection; -class LogicalTopN; - -//! Simplifies outer joins if NULL-extended rows are filtered in a way that changes the join semantics -class OuterJoinSimplification : public LogicalOperatorVisitor { -public: - OuterJoinSimplification(); - -public: - void VisitOperator(LogicalOperator &op) override; - -private: - explicit OuterJoinSimplification(column_binding_set_t required_columns); - - //! Extract and propagate column references through expressions and join conditions - void AddColumnReferences(const Expression &expr, column_binding_set_t &bindings); - void AddRequiredColumns(const Expression &expr); - void AddRequiredColumns(const JoinCondition &condition); - void AddRequiredColumns(const vector &conditions); - bool GetColumnBinding(const Expression &expr, ColumnBinding &binding); - bool GetNullPreservingColumnBinding(const Expression &expr, ColumnBinding &binding); - - //! Track predicates that require columns to be NULL or reject NULL values - void HandleExpression(const Expression &expr); - void HandleFilterExpression(const Expression &expr); - bool HandleIsNullExpression(const Expression &expr); - bool IsNullFilter(const Expression &expr, ColumnBinding &binding); - void InitializeRequiredColumns(LogicalOperator &op); - bool FiltersNulls(ExpressionType comparison_type); - - //! Rewrite joins based on the NULL constraints collected from operators above them - bool TryConvertLeftToAntiJoin(LogicalComparisonJoin &join); - bool HasNullRequiredColumns(const vector &bindings); - bool HasRequiredColumns(const vector &bindings); - void MarkEliminatedNullColumns(const vector &bindings); - void EraseNullRequiredColumns(LogicalOperator &child); - vector GetRightBindings(LogicalJoin &join); - void SimplifyOuterJoinType(LogicalComparisonJoin &join); - - //! Visit operators while preserving only the constraints that can safely pass through each operator type - void VisitComparisonJoin(LogicalComparisonJoin &join, LogicalOperator &op); - void VisitInnerOrSemiJoin(LogicalComparisonJoin &join, LogicalOperator &op); - void VisitOuterJoin(LogicalComparisonJoin &join, LogicalOperator &op); - void VisitProjection(LogicalProjection &projection, LogicalOperator &op); - void VisitFilter(LogicalFilter &filter, LogicalOperator &op); - void VisitOrder(LogicalOrder &order, LogicalOperator &op); - void VisitTopN(LogicalTopN &top_n, LogicalOperator &op); - void VisitAggregate(LogicalAggregate &aggregate, LogicalOperator &op); - void VisitUnsupportedOperator(LogicalOperator &op); - -private: - //! Columns that have their NULL values filtered - column_binding_set_t null_filtered_columns; - //! Columns that are required to be NULL - column_binding_set_t null_required_columns; - //! Columns that are known to be NULL after rewriting a LEFT join to an ANTI join - column_binding_set_t eliminated_null_columns; - //! Columns that must remain available to operators above the current point in the plan - column_binding_set_t required_columns; - bool initialized_required_columns = false; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/projection_pullup.hpp b/src/duckdb/src/include/duckdb/optimizer/projection_pullup.hpp index 0fd25904d..efee5c900 100644 --- a/src/duckdb/src/include/duckdb/optimizer/projection_pullup.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/projection_pullup.hpp @@ -25,10 +25,10 @@ class ProjectionPullup : public LogicalOperatorVisitor { optional_ptr FindParent(LogicalOperator &target, LogicalOperator ¤t); void PopParents(const LogicalOperator &op); void InsertProjectionBelowOp(unique_ptr &op, unique_ptr &child, bool stop_at_op); - void CanPullThrough(column_binding_map_t> &projection_map, bool keep_throwing_filters_above, + void CanPullThrough(column_binding_map_t> &projection_map, const LogicalProjection &proj, bool &can_pull_through); - void PullUpColrefProjection(unique_ptr &op, LogicalProjection &proj, - vector &proj_bindings); + void RemoveProjection(unique_ptr &op, LogicalProjection &proj, + vector &proj_bindings); void PullUpNonColrefProjection(unique_ptr &op, LogicalProjection &proj, vector &proj_bindings, idx_t pull_up_to_here); }; diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp index d99845d99..e4b4e2976 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp @@ -30,6 +30,10 @@ class RelationStatsExtractor { RelationStatsExtractor(ClientContext &context, shared_ptr source_stats); public: + ClientContext &GetContext() const { + return context; + } + optional_ptr Extract(LogicalOperator &op); optional_ptr GetCTEDefinition(const LogicalCTERef &cte_ref) const; idx_t ExtractedOperatorCount() const; diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp index 3ec7d3c2d..3c139105a 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp @@ -45,6 +45,11 @@ struct SemiAntiJoinCardinalityEstimate { bool used_domain_evidence; }; +struct TupleDomainRestrictionEstimate { + double rows; + double groups; +}; + class RelationStatisticsHelper { public: static constexpr double DEFAULT_SELECTIVITY = 0.2; @@ -104,6 +109,11 @@ class RelationStatisticsHelper { JoinType join_type, const vector &domains, bool has_residual); static SemiAntiJoinCardinalityEstimate EstimateSemiAntiJoinCardinality(LogicalComparisonJoin &join, const RelationStats &left, const RelationStats &right); + //! Estimate rows and groups for a matched tuple restriction with column-reference conditions. + static optional EstimateTupleDomainRestriction(LogicalComparisonJoin &restriction, + const RelationStats &input, + const RelationStats &keys, + RelationStatsExtractor &extractor); static optional_idx EstimateDirectFilterDomain(const Expression &expression, optional target_binding, idx_t maximum_domain); diff --git a/src/duckdb/src/include/duckdb/optimizer/remote_pushdown_optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/remote_pushdown_optimizer.hpp index 772681d60..e7dcb53a7 100644 --- a/src/duckdb/src/include/duckdb/optimizer/remote_pushdown_optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/remote_pushdown_optimizer.hpp @@ -134,8 +134,12 @@ class RemotePushdownOptimizer { CatalogPushdownResult VerifyStatementSupport(const SQLStatement &statement, CatalogPushdownResult target); //! Resolve a (possibly nested) qualified name into the catalog it lives in and its schema path. This runs the //! same catalog/schema ambiguity resolution the binder does, and - unlike Catalog()/Schema() - keeps every - //! level of a nested schema path. The catalog is empty when the name is not catalog-qualified - void ResolveQualification(const QualifiedName &name, Identifier &catalog_name, vector &schema_path); + //! level of a nested schema path. The catalog is empty when the name is not catalog-qualified. Returns false + //! when the name is a nested schema path its catalog doesn't support, so it can't name anything there and must + //! not be pushed down. + [[nodiscard]] bool ResolveQualification(const QualifiedName &name, Identifier &catalog_name, + vector &schema_path, + CatalogType type = CatalogType::TABLE_ENTRY); //! Look an entry up in a catalog, defaulting to the main schema when the name carries no schema optional_ptr LookupEntry(const Identifier &catalog_name, const EntryLookupInfo &lookup, const vector &schema_path); diff --git a/src/duckdb/src/include/duckdb/optimizer/remove_redundant_distinct.hpp b/src/duckdb/src/include/duckdb/optimizer/remove_redundant_distinct.hpp new file mode 100644 index 000000000..f812ed159 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/remove_redundant_distinct.hpp @@ -0,0 +1,34 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/remove_redundant_distinct.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/unique_ptr.hpp" +#include "duckdb/optimizer/distinctness.hpp" + +namespace duckdb { + +class LogicalOperator; + +//! Removes duplicate eliminations whose input is already distinct. A duplicate elimination is an aggregate that only +//! has groups (DISTINCT, GROUP BY without aggregate functions). If its input has at most one row per value of the +//! groups, it is replaced by a projection of the groups. +class RemoveRedundantDistinct { +public: + RemoveRedundantDistinct() : distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS) { + } + + void VisitOperator(unique_ptr &op); + +private: + //! The operators are visited bottom-up, so the unique sets of an operator are only computed (and cached) after + //! the operator and everything below it has been visited: an aggregate is replaced before it is asked about + Distinctness distinctness; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/remove_unused_columns.hpp b/src/duckdb/src/include/duckdb/optimizer/remove_unused_columns.hpp index 6be475719..b70d28b79 100644 --- a/src/duckdb/src/include/duckdb/optimizer/remove_unused_columns.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/remove_unused_columns.hpp @@ -188,6 +188,15 @@ class RemoveUnusedColumns : public BaseColumnPruner { optional_ptr> TryGetCTEMap(); }; +class ColumnReferenceExtractor : public BaseColumnPruner { +public: + static column_binding_map_t GetReferences(unique_ptr *expression) { + ColumnReferenceExtractor extractor; + extractor.VisitExpression(expression); + return extractor.column_references; + } +}; + class CTERefPruner : public LogicalOperatorVisitor { public: CTERefPruner(const TableIndex table_index, const unordered_set &referenced_columns); diff --git a/src/duckdb/src/include/duckdb/optimizer/row_group_pruner.hpp b/src/duckdb/src/include/duckdb/optimizer/row_group_pruner.hpp index c72ab6f0f..dcb362b00 100644 --- a/src/duckdb/src/include/duckdb/optimizer/row_group_pruner.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/row_group_pruner.hpp @@ -35,12 +35,13 @@ class RowGroupPruner { void GetLimitAndOffset(const LogicalLimit &logical_limit, optional_idx &row_limit, optional_idx &row_offset) const; optional_ptr FindLogicalOrder(const LogicalLimit &logical_limit) const; optional_ptr FindLogicalGet(const LogicalOrder &logical_order, ColumnIndex &column_index) const; - // row_limit, row_offset, primary_order, logical_get, logical_limit + // row_limit, row_offset, primary_order, logical_get, logical_limit, has_secondary_order unique_ptr CreateRowGroupReordererOptions(optional_idx row_limit, optional_idx row_offset, const BoundOrderByNode &primary_order, const LogicalGet &logical_get, const StorageIndex &storage_index, - LogicalLimit &logical_limit) const; + LogicalLimit &logical_limit, + bool has_secondary_order) const; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/set_operation_aggregate.hpp b/src/duckdb/src/include/duckdb/optimizer/set_operation_aggregate.hpp new file mode 100644 index 000000000..85c60eefd --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/set_operation_aggregate.hpp @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/set_operation_aggregate.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/optimizer.hpp" + +namespace duckdb { + +class LogicalSetOperation; + +//! Chooses how an EXCEPT ALL / INTERSECT ALL runs, after the filters have been moved around the set operation: as one +//! GROUP BY all columns over the UNION ALL of both children that counts the rows per side and emits every group as +//! often as the set operation asks for, or, where rows that compare equal can differ, as a SEMI / ANTI join of the +//! numbered rows. See set_operation_aggregate.cpp. +class SetOperationAggregate { +public: + //! Without use_aggregate every set operation becomes the join + SetOperationAggregate(Optimizer &optimizer, bool use_aggregate); + + unique_ptr Optimize(unique_ptr op); + +private: + bool CanUseAggregate(LogicalSetOperation &setop); + bool FewGroupsOfManyRows(LogicalSetOperation &setop); + bool OneSideMuchSmaller(LogicalSetOperation &setop); + unique_ptr CreateAggregate(LogicalSetOperation &setop); + unique_ptr AddSideMarkers(unique_ptr child, bool is_left); + + Optimizer &optimizer; + bool use_aggregate; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp index 76a07b725..a9b8ce01c 100644 --- a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/common.hpp" +#include "duckdb/common/column_index.hpp" #include "duckdb/common/enums/filter_propagate_result.hpp" #include "duckdb/common/table_index.hpp" #include "duckdb/common/types/value.hpp" @@ -80,6 +81,11 @@ class StatisticsPropagator { //! Statistics callback for monotone functions that return NULL for infinite arguments DUCKDB_API static unique_ptr PropagateFiniteMonotoneBounds(ClientContext &context, FunctionStatisticsInput &input); + //! The statistics of a column emitted by a scan, or nullptr if the scan has none for it + static unique_ptr GetColumnStatistics(ClientContext &context, LogicalGet &get, + const ColumnIndex &column_index); + //! Whether the statistics prove that an expression is NULL in every row of a non-empty input + static bool HasNoValidValue(optional_ptr stats); //! Compare two sets of statistics and return whether the comparison is always true or false static FilterPropagateResult PropagateComparison(const BaseStatistics &left, const BaseStatistics &right, ExpressionType comparison); @@ -185,6 +191,8 @@ class StatisticsPropagator { void TryExecuteAggregates(LogicalAggregate &op, unique_ptr &node_ptr); void ReplaceWithEmptyResult(unique_ptr &node); + //! Whether an expression can be removed from the plan without an observable effect + static bool IsRemovable(const Expression &expr); bool ExpressionIsConstant(Expression &expr, const Value &val); bool ExpressionIsConstantOrNull(Expression &expr, const Value &val); diff --git a/src/duckdb/src/include/duckdb/optimizer/window_fusion.hpp b/src/duckdb/src/include/duckdb/optimizer/window_fusion.hpp new file mode 100644 index 000000000..2d3715df4 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/window_fusion.hpp @@ -0,0 +1,34 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/window_fusion.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" +#include "duckdb/storage/statistics/base_statistics.hpp" + +namespace duckdb { + +class ClientContext; + +class WindowFusion : public LogicalOperatorVisitor { +public: + WindowFusion(ClientContext &client, optional_ptr>> stats); + + unique_ptr Optimize(unique_ptr op); + + static optional_idx CanOptimize(LogicalOperator &op); + +private: + unique_ptr OptimizeInternal(unique_ptr op); + + ClientContext &client; + optional_ptr>> stats; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parallel/parallel_destroy_task.hpp b/src/duckdb/src/include/duckdb/parallel/parallel_destroy_task.hpp index 95f44fe27..d1bfb6bb9 100644 --- a/src/duckdb/src/include/duckdb/parallel/parallel_destroy_task.hpp +++ b/src/duckdb/src/include/duckdb/parallel/parallel_destroy_task.hpp @@ -14,27 +14,46 @@ namespace duckdb { template class ParallelDestroyTask : public BaseExecutorTask { - using VALUE_TYPE = typename ITERABLE::value_type; + using ITERATOR = typename ITERABLE::iterator; public: - ParallelDestroyTask(TaskExecutor &executor, VALUE_TYPE &&elem_p) - : BaseExecutorTask(executor), elem(std::move(elem_p)) { + ParallelDestroyTask(TaskExecutor &executor, ITERATOR begin_p, ITERATOR end_p) + : BaseExecutorTask(executor), begin(begin_p), end(end_p) { } void ExecuteTask() override { - elem.reset(); + for (auto entry = begin; entry != end; ++entry) { + entry->reset(); + } + } + + void Cancel() override { + // Finish releasing the range before the executor reports this task as complete. + ExecuteTask(); } static void Schedule(TaskScheduler &scheduler, ITERABLE &elements) { + Schedule(scheduler, elements.begin(), elements.end(), elements.size()); + } + + //! The caller keeps the range stable until this call joins all scheduled tasks. + static void Schedule(TaskScheduler &scheduler, ITERATOR begin, ITERATOR end, idx_t max_tasks) { + if (begin == end) { + return; + } + D_ASSERT(max_tasks > 0); // This is used in destructors and is therefore not allowed to throw // Similar approach to AttachedDatabase::Close(), just swallow the exception try { TaskExecutor executor(scheduler); + const idx_t count = end - begin; + const auto task_count = MinValue(count, max_tasks); + const auto batch_size = (count + task_count - 1) / task_count; vector> tasks; - tasks.reserve(elements.size()); - for (auto &segment : elements) { - auto destroy_task = make_uniq(executor, std::move(segment)); - tasks.push_back(std::move(destroy_task)); + tasks.reserve(task_count); + for (idx_t offset = 0; offset < count; offset += batch_size) { + tasks.push_back(make_uniq(executor, begin + offset, + begin + MinValue(count, offset + batch_size))); } executor.ScheduleTasks(std::move(tasks)); executor.WorkOnTasks(); @@ -43,7 +62,8 @@ class ParallelDestroyTask : public BaseExecutorTask { } private: - VALUE_TYPE elem; + ITERATOR begin; + ITERATOR end; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parallel/pipeline.hpp b/src/duckdb/src/include/duckdb/parallel/pipeline.hpp index 4c53f1ca3..337b8cae1 100644 --- a/src/duckdb/src/include/duckdb/parallel/pipeline.hpp +++ b/src/duckdb/src/include/duckdb/parallel/pipeline.hpp @@ -11,6 +11,7 @@ #include "duckdb/common/atomic.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/set.hpp" +#include "duckdb/common/enums/pipeline_execution_order.hpp" #include "duckdb/execution/physical_operator.hpp" #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/common/reference_map.hpp" @@ -223,6 +224,8 @@ class Pipeline : public enable_shared_from_this { //! Returns whether any of the operators in the pipeline care about preserving order bool IsOrderDependent() const; + //! Execution order required by the pipeline, independent of operator caching. + PipelineExecutionOrder GetExecutionOrder() const; //! Marks this pipeline as fed externally instead of by scheduled source tasks void SetExternalInput(const vector> &producer_pipelines); bool IsExternalInput() const { diff --git a/src/duckdb/src/include/duckdb/parallel/scan_affinity_queue.hpp b/src/duckdb/src/include/duckdb/parallel/scan_affinity_queue.hpp new file mode 100644 index 000000000..211f27f22 --- /dev/null +++ b/src/duckdb/src/include/duckdb/parallel/scan_affinity_queue.hpp @@ -0,0 +1,62 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/parallel/scan_affinity_queue.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/atomic.hpp" +#include "duckdb/common/common.hpp" +#include "duckdb/common/deque.hpp" +#include "duckdb/common/mutex.hpp" +#include "duckdb/common/optional_idx.hpp" +#include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/vector.hpp" + +namespace duckdb { +class ScanAffinityQueueTestHelper; +struct ScanReadAheadJob; + +//! Schedules ready scan jobs by an optional shard hint, independently of their reader +class ScanAffinityQueue { + friend class ScanAffinityQueueTestHelper; + +public: + explicit ScanAffinityQueue(idx_t shard_count); + ~ScanAffinityQueue(); + + //! Publish ready work with an optional placement hint. + void Push(idx_t producer_shard, optional_idx affinity, unique_ptr job); + + //! Prefer nearby cached work, then unknown placement. Empty hints are advisory only. + bool TryPop(idx_t local_shard, unique_ptr &job); + +private: + enum class ProbeMode { ADVISORY, AUTHORITATIVE }; + + struct AssignmentQueue { + deque> assignments; + //! Advisory count used to skip empty queues without taking their lock + atomic ready {0}; + }; + + struct alignas(128) Shard { + explicit Shard(idx_t probe_index); + + mutex lock; + AssignmentQueue affinity; + AssignmentQueue unknown; + const idx_t probe_index; + }; + + bool TryTakeAssignment(idx_t probe_index, ProbeMode mode, unique_ptr &job); + +private: + vector> shards; + vector> probe_slots; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parallel/scan_read_ahead.hpp b/src/duckdb/src/include/duckdb/parallel/scan_read_ahead.hpp index b74ddce4d..15de1ded2 100644 --- a/src/duckdb/src/include/duckdb/parallel/scan_read_ahead.hpp +++ b/src/duckdb/src/include/duckdb/parallel/scan_read_ahead.hpp @@ -22,18 +22,21 @@ #include "duckdb/parallel/async_result.hpp" #include "duckdb/parallel/interrupt.hpp" #include "duckdb/parallel/task_executor.hpp" +#include "duckdb/common/optional_idx.hpp" #include namespace duckdb { class ClientContext; struct TableFunctionInput; +class ScanReadAhead; +class ScanAffinityQueue; +struct ScanReadAheadJob; class ReadAheadJobCompletion { public: - explicit ReadAheadJobCompletion(shared_ptr executor_p) - : executor(std::move(executor_p)), pending_io_tasks(0) { - } + explicit ReadAheadJobCompletion(shared_ptr executor_p); + ~ReadAheadJobCompletion(); public: //! Arm the completion for one I/O task, only called before the job becomes visible to other threads @@ -48,16 +51,31 @@ class ReadAheadJobCompletion { void WaitForIO(); private: + friend class ScanReadAhead; + //! Affinity completion owns the job until publication; the job must not own this completion and form a cycle. + void OwnJob(ScanReadAhead &read_ahead, unique_ptr job); + +private: + friend class ReadAheadIOTask; //! Executor holding the scheduled I/O, waiters drain it inline shared_ptr executor; atomic pending_io_tasks; //! Holds the scan task parked on this job's I/O StateWithBlockableTasks parked_scan; + optional_ptr read_ahead; + unique_ptr ready_job; }; //! Base of the job types driven by ScanReadAhead struct ScanReadAheadJob { virtual ~ScanReadAheadJob(); + //! Called once after reads finish to resolve placement; may release discovery-only references. + virtual optional_idx ResolveAffinity() { + return optional_idx(); + } + virtual idx_t GetMemoryUsage() const { + return 0; + } //! Settle in-flight I/O void SettleIO() { @@ -68,19 +86,22 @@ struct ScanReadAheadJob { } //! Batch index of this job, drives ordered queue admission. - //! Producers must assign batch indexes densely from 0 in claim order + //! Ordered producers must assign batch indexes densely from 0 in claim order idx_t batch_index = 0; //! Completion of the job's scheduled I/O shared_ptr io_completion; - //! Total bytes of scheduled I/O for this job - idx_t io_bytes = 0; + //! Budget charge for this job's I/O and scan metadata + idx_t budget_charge = 0; -private: +protected: + //! Derived destructors must settle I/O before destroying any state referenced by pending reads. ScanReadAheadJob() = default; + +private: ScanReadAheadJob(const ScanReadAheadJob &) = delete; ScanReadAheadJob &operator=(const ScanReadAheadJob &) = delete; - template - friend struct ScanReadAheadJobWrapper; + friend class ScanReadAhead; + idx_t producer_shard = 0; }; //! Wraps job-specific state so in-flight I/O is settled before that state is destroyed @@ -132,37 +153,50 @@ class ReadAheadOpenFile { static idx_t Count(); }; -//! Outcome of ScanReadAhead::AcquireJob +//! Outcome of scan job acquisition enum class ScanReadAheadAcquire : uint8_t { ACQUIRED, //! a job with settled I/O is now held EXHAUSTED, //! every job has been produced and claimed, the scan is done - PARKED //! the scan task parked until the claimed job's I/O completes, the caller must yield + PARKED //! the scan task parked until work becomes ready, the caller must yield }; -//! Drives read-ahead for a scan, its purpose is to keep several scan jobs scheduled ahead of decoding. -//! Job state is held in a ScanReadAheadJobWrapper, callers claim jobs back with unique_ptr_cast. +enum class ScanReadAheadPolicy : uint8_t { ORDERED, AFFINITY }; + +//! Shares the I/O executor, budget and cancellation lifecycle between ordered and affinity scans. +//! Ordered consumers claim jobs before I/O completes and may park on the job's completion. +//! Affinity completions own unfinished jobs; consumers claim only ready jobs and park on scan progress. class ScanReadAhead { public: - ScanReadAhead(ClientContext &context, idx_t read_ahead_depth_p, - unique_ptr memory_governor_p); + ScanReadAhead(ClientContext &context, ScanReadAheadPolicy policy, idx_t read_ahead_depth, + unique_ptr memory_governor, bool prefetch_enabled = true, + idx_t shard_count = 1, idx_t scan_concurrency = 0); ~ScanReadAhead(); - //! Create the read-ahead driver from the read_ahead_depth setting, returns null when read-ahead is disabled. + //! Create a driver with a fixed scheduling policy; prefetch also requires async threads and read_ahead_depth. //! -1 means automatic mode, unlimited depth with the backlog bounded by a temp-memory reservation. - static unique_ptr Create(ClientContext &context); + //! Without prefetch, ordered scans need no driver; affinity scans retain their fixed assignment window. + static unique_ptr Create(ClientContext &context, ScanReadAheadPolicy policy, bool prefetch = true, + idx_t shard_count = 1, idx_t scan_concurrency = 0); + bool PrefetchEnabled() const { + return prefetch_enabled; + } public: //! Claims the next job and schedules its I/O, filling io_tasks when the I/O was detached to the pool. //! Returns null when there are no more jobs to produce. - //! The callback must assign the job's batch index, densely from 0 in claim order. + //! Ordered callbacks must assign the job's batch index, densely from 0 in claim order. using ProduceJobCallback = std::function(vector> &io_tasks)>; //! Settle the claimed job's scheduled I/O, blocking until it completed, and release its budget charge void WaitForJob(ScanReadAheadJob &job); //! Acquire the next job, producing and claiming as needed; on ACQUIRED the job's I/O has been settled. - //! On PARKED the caller must yield holding the claimed job and settle it with WaitForJob when it resumes. + //! On PARKED the caller retains a job to settle with WaitForJob after resumption. ScanReadAheadAcquire AcquireJob(ClientContext &context, TableFunctionInput &data_p, const ProduceJobCallback &claim_and_schedule, unique_ptr &job); + //! Acquire ready work by locality. On PARKED the caller holds no job and retries after resumption. + ScanReadAheadAcquire AcquireReadyJob(ClientContext &context, TableFunctionInput &input, + const ProduceJobCallback &produce, unique_ptr &job, + idx_t local_shard); //! Push an error onto the async executor void PushError(ErrorData error); @@ -182,28 +216,48 @@ class ScanReadAhead { void CancelAndDrain(); private: + static idx_t JobWindow(ScanReadAheadPolicy policy, idx_t read_ahead_depth, idx_t scan_concurrency); //! Settles the reservation taken by TryReserveSlot struct ProducerReservation { - explicit ProducerReservation(ScanReadAhead &read_ahead) : read_ahead(read_ahead) { + explicit ProducerReservation(ScanReadAhead &read_ahead, idx_t count) + : read_ahead(read_ahead), remaining(count) { } ~ProducerReservation() { - if (!committed) { - read_ahead.ReleaseSlot(); - read_ahead.pending_io_bytes -= MINIMUM_JOB_IO_CHARGE; + if (remaining) { + read_ahead.active_jobs.fetch_sub(remaining); + if (read_ahead.MinimumJobCharge()) { + read_ahead.pending_budget_charge -= remaining * read_ahead.MinimumJobCharge(); + } } --read_ahead.active_producers; - // a pushed job was signalled already, a released slot frees one thread and a done scan all of them - if (!committed || read_ahead.IsDone()) { + // Ready jobs can be consumed before their producer exits; its exit can then finish an affinity scan. + if (remaining || read_ahead.IsDone() || read_ahead.affinity) { read_ahead.SignalProgress(read_ahead.IsDone()); } } + void Commit() { + D_ASSERT(remaining > 0); + --remaining; + } ScanReadAhead &read_ahead; - bool committed = false; + idx_t remaining; }; //! Try to produce one job into the queue. bool TryProduceJob(const ProduceJobCallback &claim_and_schedule); + bool TryProduceBatch(const ProduceJobCallback &claim_and_schedule, idx_t local_shard); + idx_t ReserveBatch(); + idx_t MinimumJobCharge() const; + bool TryParkForProgress(TableFunctionInput &input, idx_t epoch); + void ResumeScan(const InterruptState &interrupt_state); + void ScheduleReadyJob(unique_ptr job, vector> io_tasks, + ProducerReservation &reservation); + //! Takes ownership of a completed job's reservation, publishing or retiring it exactly once. + void CompleteJob(unique_ptr job); + void RetireJob(idx_t budget_charge); + friend class ReadAheadJobCompletion; + friend class ReadAheadIOTask; //! Check if scan is done, i.e., no more jobs to do bool IsDone() const; //! Whether any thread holds a reserved slot it has not pushed a job for yet @@ -220,7 +274,9 @@ class ScanReadAhead { return !pending_jobs.empty(); } //! The number of jobs that may be in flight under the current budget - idx_t ReservationDepth() const; + idx_t ReservationDepth(idx_t pending_bytes) const; + //! Refresh the grant if the next job needs more room, and log the current budget. + void UpdateBudget(); //! Reserve an in-flight job slot for producing a job bool TryReserveSlot(); //! Schedule the job's I/O and admit the job to the queue @@ -238,15 +294,20 @@ class ScanReadAhead { idx_t ProgressEpoch() const; private: - //! Minimum budget charge per job, beyond its scheduled I/O a job carries scan-state overhead (decode buffers) - static constexpr idx_t MINIMUM_JOB_IO_CHARGE = 16ULL * 1024 * 1024; + //! Ordered jobs retain reader/decode state; charge at least this much, or their I/O size if larger. + static constexpr idx_t MINIMUM_ORDERED_JOB_CHARGE = 16ULL * 1024 * 1024; //! How long a thread yields for another thread to push a job before it waits for it static constexpr idx_t PRODUCER_YIELD_MICROS = 1000; + static constexpr idx_t AFFINITY_WINDOW = 256; + static constexpr idx_t PRODUCE_BATCH = 8; + //! Managed affinity jobs charge metadata plus I/O; cached work without a governor uses only the fixed window. + static constexpr idx_t MINIMUM_AFFINITY_JOB_CHARGE = 4096; private: ClientContext &context; - //! Maximum number of jobs scheduled ahead of decoding, unlimited in the -1 auto mode - const idx_t read_ahead_depth; + const bool prefetch_enabled; + //! Admission window, fixed together with the scheduling policy at construction. + const idx_t job_window; //! Async memory governor unique_ptr memory_governor; //! Maximum files opening or open ahead of decoding @@ -258,21 +319,25 @@ class ScanReadAhead { mutable mutex lock; deque> ready_queue; + const unique_ptr affinity; //! Jobs pushed out of order, held back until all earlier batch indexes are admitted to the queue map> pending_jobs; //! The batch index the queue admits next idx_t next_batch_index = 0; //! Jobs scheduled ahead of decoding - atomic active_jobs {0}; - //! Budget charge of the reserved producer slots and scheduled jobs, released per job in WaitForJob - atomic pending_io_bytes {0}; + PaddedAtomic active_jobs {0}; + //! Budget charge of the reserved producer slots and scheduled jobs + atomic pending_budget_charge {0}; atomic done {false}; //! Threads that reserved a slot but have not pushed their job yet atomic active_producers {0}; //! Incremented whenever a waiting thread could make progress atomic progress_epoch {0}; - //! Threads waiting for progress, only these need a notification + //! Registered task and thread waiters, only these need a notification atomic waiting_threads {0}; + vector parked_scans; + //! An executing read guarantees another progress signal even if the worker pools stop. + atomic running_reads {0}; condition_variable progress; //! Async I/O executor (async pool) shared_ptr executor; diff --git a/src/duckdb/src/include/duckdb/parallel/sharded_counter.hpp b/src/duckdb/src/include/duckdb/parallel/sharded_counter.hpp new file mode 100644 index 000000000..6b88eb3ca --- /dev/null +++ b/src/duckdb/src/include/duckdb/parallel/sharded_counter.hpp @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/parallel/sharded_counter.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/array.hpp" +#include "duckdb/common/atomic.hpp" +#include "duckdb/common/common.hpp" + +namespace duckdb { + +//! A counter that spreads concurrent updates across estimated CPU groups. +class ShardedCounter { +public: + void Add(idx_t count); + //! The total is exact once all writers have stopped. + idx_t GetTotal() const; + //! Requires all writers to have stopped. + void Reset(); + +private: + static constexpr idx_t SHARD_COUNT = 16; + static constexpr idx_t CPUS_PER_SHARD = 16; + + array, SHARD_COUNT> shards {}; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parallel/task_executor.hpp b/src/duckdb/src/include/duckdb/parallel/task_executor.hpp index fbe34febd..3c39608f4 100644 --- a/src/duckdb/src/include/duckdb/parallel/task_executor.hpp +++ b/src/duckdb/src/include/duckdb/parallel/task_executor.hpp @@ -44,9 +44,8 @@ class BaseExecutorTask { ExecuteTask(); return TaskExecutionResult::TASK_FINISHED; } - //! Called instead of ExecuteTask when the task is retired without running its work, because another task errored, - //! because the executor was cancelled, or because the task could not be queued at all. Exactly one of ExecuteTask - //! or Cancel runs for every task passed to TaskExecutor::ScheduleTask or ScheduleTasks. + //! Called when a task is retired without entering its next step, including task-start notification failure, + //! executor cancellation or error, or submission failure. Also settles work left by earlier incremental steps. //! Anything a waiter watches must change on every exit path, or that waiter never wakes up. Either settle it here //! as well as in ExecuteTask, or settle it in the destructor, which also covers a task that was constructed but //! never scheduled. A destructor settle runs after the executor has already counted the task as finished, so it diff --git a/src/duckdb/src/include/duckdb/parser/parsed_data/create_collation_info.hpp b/src/duckdb/src/include/duckdb/parser/parsed_data/create_collation_info.hpp deleted file mode 100644 index 78b66f57e..000000000 --- a/src/duckdb/src/include/duckdb/parser/parsed_data/create_collation_info.hpp +++ /dev/null @@ -1,41 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/parser/parsed_data/create_collation_info.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/parser/parsed_data/create_info.hpp" -#include "duckdb/function/scalar_function.hpp" - -#include "duckdb/common/identifier.hpp" -namespace duckdb { - -struct CreateCollationInfo : public CreateInfo { - DUCKDB_API CreateCollationInfo(Identifier name_p, ScalarFunction function_p, bool combinable_p, - bool not_required_for_equality_p); - - //! The name of the collation - const Identifier &GetCollationName() const { - return qualified_name.Name(); - } - void SetCollationName(Identifier name) { - qualified_name = qualified_name.WithName(std::move(name)); - } - //! The collation function to push in case collation is required - ScalarFunction function; - //! Whether or not the collation can be combined with other collations. - bool combinable; - //! Whether or not the collation is required for equality comparisons or not. For many collations a binary - //! comparison for equality comparisons is correct, allowing us to skip the collation in these cases which greatly - //! speeds up processing. - bool not_required_for_equality; - -public: - unique_ptr Copy() const override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parser/parser.hpp b/src/duckdb/src/include/duckdb/parser/parser.hpp index 23c361934..0c1d8950a 100644 --- a/src/duckdb/src/include/duckdb/parser/parser.hpp +++ b/src/duckdb/src/include/duckdb/parser/parser.hpp @@ -23,7 +23,6 @@ class ClientContext; struct CompiledGrammar; struct MatcherToken; class TokenIterator; -class GroupByNode; struct UnicodeSpace { UnicodeSpace(idx_t pos, idx_t bytes) : pos(pos), bytes(bytes) { } @@ -93,15 +92,8 @@ class Parser { DUCKDB_API unique_ptr ParseSingleExpression(const string &expression); //! Parses a single SELECT statement into its node DUCKDB_API unique_ptr ParseSelectNode(const string &query); - //! Parses a list of GROUP BY expressions - GroupByNode ParseGroupByList(const string &group_by); //! Parses a list as found in an ORDER BY expression (i.e. including optional ASCENDING/DESCENDING modifiers) vector ParseOrderList(const string &select_list); - //! Parses an update list (i.e. the list found in the SET clause of an UPDATE statement) - void ParseUpdateList(const string &update_list, vector &update_columns, - vector> &expressions); - //! Parses a VALUES list (i.e. the list of expressions after a VALUES clause) - vector>> ParseValuesList(const string &value_list); //! Parses a column list (i.e. as found in a CREATE TABLE statement) ColumnList ParseColumnList(const string &column_list); ColumnDefinition ParseColumnDefinition(const string &column_definition); diff --git a/src/duckdb/src/include/duckdb/parser/peg/grammar_literal_table.hpp b/src/duckdb/src/include/duckdb/parser/peg/grammar_literal_table.hpp index bf077ee12..829b96121 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/grammar_literal_table.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/grammar_literal_table.hpp @@ -8,6 +8,7 @@ #pragma once #include "duckdb/common/case_insensitive_map.hpp" +#include "duckdb/common/string_util.hpp" #include "duckdb/parser/peg/literal_info.hpp" namespace duckdb { @@ -25,21 +26,76 @@ class GrammarLiteralTable { return cache_id; } + //! Calls fun(info) for every literal in the table + template + void ForEachLiteral(FUN &&fun) const { + for (auto &entry : literals) { + fun(entry.second); + } + } + LiteralInfo Lookup(const string &text) const { - if (text.size() > max_literal_length) { + return Lookup(text.data(), text.size()); + } + //! Case-insensitive lookup of a text that need not be a string of its own + LiteralInfo Lookup(const char *data, idx_t size) const { + // most tokens that are not literals (numbers, strings, long identifiers) are rejected without hashing + if (size == 0 || size > max_literal_length || !first_bytes[static_cast(data[0])]) { + return LiteralInfo(); + } + if (size == 1) { + return single_byte[static_cast(data[0])]; + } + // most identifiers share neither their first two bytes nor their length with a literal + if (!((prefix_lengths[PrefixIndex(data[0], data[1])] >> LengthBit(size)) & 1)) { return LiteralInfo(); } - auto entry = literals.find(text); - return entry == literals.end() ? LiteralInfo() : entry->second; + auto hash = static_cast(StringUtil::CIHash(data, size)); + for (auto index = hash & slot_mask;; index = (index + 1) & slot_mask) { + auto &slot = slots[index]; + if (!slot.entry) { + return LiteralInfo(); + } + auto &text = texts[slot.entry - 1]; + if (slot.hash == hash && StringUtil::CIEquals(text.data(), text.size(), data, size)) { + return infos[slot.entry - 1]; + } + } } private: + static constexpr idx_t PREFIX_COUNT = 1024; + //! Slot of the first two bytes of a text: five case-insensitive bits of each + static idx_t PrefixIndex(char first, char second) { + return ((static_cast(first) & 31U) << 5U) | (static_cast(second) & 31U); + } + static idx_t LengthBit(idx_t size) { + return size < 31 ? size : 31; + } void Register(const string &text, keyword_categories_t categories = keyword_categories_t()); + void Index(); + +private: + struct Slot { + uint32_t hash = 0; + //! index into texts/infos plus one; zero marks an empty slot + uint32_t entry = 0; + }; private: const uint64_t cache_id; idx_t max_literal_length = 0; case_insensitive_map_t literals; + //! Bytes (case-folded) that start some literal, and the literals of exactly one byte + bool first_bytes[256] = {}; + //! Per two-byte prefix, the lengths of the literals that start with it + uint32_t prefix_lengths[PREFIX_COUNT] = {}; + LiteralInfo single_byte[256]; + //! Open addressing index over the literals for lookups by case-insensitive hash + vector texts; + vector infos; + vector slots; + uint32_t slot_mask = 0; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp index 922adee9d..a3731a61f 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp @@ -1407,13 +1407,15 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 84, 97, 114, 103, 101, 116, 79, 112, 116, 65, 108, 105, 97, 115, 32, 60, 45, 32, 66, 97, 115, 101, 84, 97, 98, 108, 101, 78, 97, 109, 101, 32, 84, 97, 114, 103, 101, 116, 65, 108, 105, 97, 115, 63, 10, 84, 97, 114, 103, 101, 116, 65, 108, 105, 97, 115, 32, 60, 45, 32, 39, 65, 83, 39, 63, 32, 67, 111, 108, 73, 100, 10, 68, 101, 108, 101, 116, 101, 85, 115, 105, 110, 103, 67, 108, 97, 117, 115, 101, 32, 60, 45, 32, 39, 85, 83, 73, 78, 71, 39, 32, 76, 105, 115, 116, 40, 84, 97, 98, 108, 101, 82, 101, 102, 41, 10, - 68, 101, 115, 99, 114, 105, 98, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 32, 47, 32, 83, 104, 111, 119, 84, 97, 98, 108, 101, 115, 32, 47, 32, 83, 104, 111, 119, 68, 101, 112, 114, 101, 99, 97, 116, 101, 100, 83, 101, 108, 101, 99, 116, 32, 47, 32, 68, 101, 115, 99, 114, 105, 98, 101, 83, 101, 108, 101, 99, 116, 32, 47, 32, 83, 104, 111, 119, 65, 108, 108, 84, 97, 98, 108, 101, 115, 32, 47, 32, 83, 104, 111, 119, 66, 121, 78, 97, 109, 101, 32, 47, 32, 68, 101, 115, 99, 114, 105, 98, 101, 66, 121, 78, 97, 109, 101, 10, - 35, 32, 34, 83, 72, 79, 87, 32, 91, 65, 76, 76, 93, 32, 69, 88, 84, 69, 82, 78, 65, 76, 32, 82, 69, 83, 79, 85, 82, 67, 69, 83, 34, 32, 105, 115, 32, 97, 32, 113, 117, 101, 114, 121, 32, 111, 118, 101, 114, 32, 100, 117, 99, 107, 100, 98, 95, 101, 120, 116, 101, 114, 110, 97, 108, 95, 114, 101, 115, 111, 117, 114, 99, 101, 115, 44, 32, 115, 111, 32, 105, 116, 32, 119, 111, 114, 107, 115, 32, 97, 115, 32, 97, 32, 115, 117, 98, 113, 117, 101, 114, 121, 32, 116, 111, 111, 46, 32, 73, 116, 32, 99, 111, 109, 101, 115, 10, - 35, 32, 102, 105, 114, 115, 116, 58, 32, 34, 83, 72, 79, 87, 32, 65, 76, 76, 34, 32, 97, 108, 111, 110, 101, 32, 105, 115, 32, 83, 104, 111, 119, 65, 108, 108, 84, 97, 98, 108, 101, 115, 44, 32, 97, 110, 100, 32, 34, 83, 72, 79, 87, 32, 60, 110, 97, 109, 101, 62, 34, 32, 105, 115, 32, 83, 104, 111, 119, 66, 121, 78, 97, 109, 101, 44, 32, 97, 110, 100, 32, 110, 101, 105, 116, 104, 101, 114, 32, 99, 97, 110, 32, 98, 101, 32, 114, 101, 116, 114, 105, 101, 100, 32, 111, 110, 99, 101, 32, 109, 97, 116, 99, 104, 101, 100, 46, 10, + 68, 101, 115, 99, 114, 105, 98, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 115, 32, 47, 32, 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 32, 47, 32, 83, 104, 111, 119, 84, 97, 98, 108, 101, 115, 32, 47, 32, 83, 104, 111, 119, 68, 101, 112, 114, 101, 99, 97, 116, 101, 100, 83, 101, 108, 101, 99, 116, 32, 47, 32, 68, 101, 115, 99, 114, 105, 98, 101, 83, 101, 108, 101, 99, 116, 32, 47, 32, 83, 104, 111, 119, 65, 108, 108, 84, 97, 98, 108, 101, 115, 32, 47, 32, 83, 104, 111, 119, 66, 121, 78, 97, 109, 101, 32, 47, 32, 68, 101, 115, 99, 114, 105, 98, 101, 66, 121, 78, 97, 109, 101, 10, + 35, 32, 34, 83, 72, 79, 87, 32, 91, 65, 76, 76, 93, 32, 69, 88, 84, 69, 82, 78, 65, 76, 32, 82, 69, 83, 79, 85, 82, 67, 69, 83, 34, 32, 105, 115, 32, 97, 32, 113, 117, 101, 114, 121, 32, 111, 118, 101, 114, 32, 100, 117, 99, 107, 100, 98, 95, 101, 120, 116, 101, 114, 110, 97, 108, 95, 114, 101, 115, 111, 117, 114, 99, 101, 115, 44, 32, 115, 111, 32, 105, 116, 32, 119, 111, 114, 107, 115, 32, 97, 115, 32, 97, 32, 115, 117, 98, 113, 117, 101, 114, 121, 32, 116, 111, 111, 46, 32, 73, 116, 32, 97, 110, 100, 10, + 35, 32, 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 115, 32, 99, 111, 109, 101, 32, 102, 105, 114, 115, 116, 58, 32, 34, 83, 72, 79, 87, 32, 65, 76, 76, 34, 32, 97, 108, 111, 110, 101, 32, 105, 115, 32, 83, 104, 111, 119, 65, 108, 108, 84, 97, 98, 108, 101, 115, 44, 32, 97, 110, 100, 32, 34, 83, 72, 79, 87, 32, 60, 110, 97, 109, 101, 62, 34, 32, 105, 115, 32, 83, 104, 111, 119, 66, 121, 78, 97, 109, 101, 44, 32, 97, 110, 100, 10, + 35, 32, 110, 101, 105, 116, 104, 101, 114, 32, 99, 97, 110, 32, 98, 101, 32, 114, 101, 116, 114, 105, 101, 100, 32, 111, 110, 99, 101, 32, 109, 97, 116, 99, 104, 101, 100, 46, 10, 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 32, 60, 45, 32, 83, 104, 111, 119, 82, 117, 108, 101, 32, 39, 65, 76, 76, 39, 63, 32, 39, 69, 88, 84, 69, 82, 78, 65, 76, 39, 32, 39, 82, 69, 83, 79, 85, 82, 67, 69, 83, 39, 32, 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 84, 121, 112, 101, 63, 10, - 35, 32, 34, 87, 73, 84, 72, 32, 84, 89, 80, 69, 32, 39, 97, 119, 115, 58, 115, 51, 116, 97, 98, 108, 101, 115, 58, 116, 97, 98, 108, 101, 45, 98, 117, 99, 107, 101, 116, 39, 34, 32, 114, 101, 115, 116, 114, 105, 99, 116, 115, 32, 116, 104, 101, 32, 108, 105, 115, 116, 105, 110, 103, 32, 40, 97, 110, 100, 32, 116, 104, 101, 32, 100, 105, 115, 99, 111, 118, 101, 114, 121, 41, 32, 116, 111, 32, 111, 110, 101, 32, 116, 121, 112, 101, 59, 32, 97, 32, 98, 97, 114, 101, 32, 105, 100, 101, 110, 116, 105, 102, 105, 101, 114, 10, - 35, 32, 105, 115, 32, 112, 97, 115, 115, 101, 100, 32, 116, 104, 114, 111, 117, 103, 104, 32, 97, 115, 32, 116, 104, 101, 32, 116, 121, 112, 101, 32, 110, 97, 109, 101, 32, 97, 115, 32, 119, 101, 108, 108, 46, 10, - 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 84, 121, 112, 101, 32, 60, 45, 32, 39, 87, 73, 84, 72, 39, 32, 39, 84, 89, 80, 69, 39, 32, 67, 111, 108, 73, 100, 79, 114, 83, 116, 114, 105, 110, 103, 10, + 35, 32, 34, 87, 73, 84, 72, 32, 84, 89, 80, 69, 32, 97, 119, 115, 46, 115, 51, 116, 97, 98, 108, 101, 115, 46, 98, 117, 99, 107, 101, 116, 34, 32, 40, 111, 114, 32, 116, 104, 101, 32, 116, 121, 112, 101, 32, 105, 110, 32, 113, 117, 111, 116, 101, 115, 41, 32, 114, 101, 115, 116, 114, 105, 99, 116, 115, 32, 116, 104, 101, 32, 108, 105, 115, 116, 105, 110, 103, 32, 40, 97, 110, 100, 32, 116, 104, 101, 32, 100, 105, 115, 99, 111, 118, 101, 114, 121, 41, 32, 116, 111, 32, 111, 110, 101, 32, 116, 121, 112, 101, 46, 10, + 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 115, 84, 121, 112, 101, 32, 60, 45, 32, 39, 87, 73, 84, 72, 39, 32, 39, 84, 89, 80, 69, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 10, + 35, 32, 34, 83, 72, 79, 87, 32, 69, 88, 84, 69, 82, 78, 65, 76, 32, 82, 69, 83, 79, 85, 82, 67, 69, 32, 84, 89, 80, 69, 83, 34, 32, 105, 115, 32, 97, 32, 113, 117, 101, 114, 121, 32, 111, 118, 101, 114, 32, 100, 117, 99, 107, 100, 98, 95, 101, 120, 116, 101, 114, 110, 97, 108, 95, 114, 101, 115, 111, 117, 114, 99, 101, 95, 116, 121, 112, 101, 115, 44, 32, 115, 111, 32, 105, 116, 32, 119, 111, 114, 107, 115, 32, 97, 115, 32, 97, 32, 115, 117, 98, 113, 117, 101, 114, 121, 32, 116, 111, 111, 46, 10, + 83, 104, 111, 119, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 115, 32, 60, 45, 32, 83, 104, 111, 119, 82, 117, 108, 101, 32, 39, 69, 88, 84, 69, 82, 78, 65, 76, 39, 32, 39, 82, 69, 83, 79, 85, 82, 67, 69, 39, 32, 39, 84, 89, 80, 69, 83, 39, 10, 35, 32, 34, 68, 69, 83, 67, 82, 73, 66, 69, 32, 40, 113, 117, 101, 114, 121, 41, 34, 32, 97, 110, 100, 32, 34, 83, 85, 77, 77, 65, 82, 73, 90, 69, 32, 40, 113, 117, 101, 114, 121, 41, 34, 32, 100, 101, 115, 99, 114, 105, 98, 101, 32, 116, 104, 101, 32, 113, 117, 101, 114, 121, 39, 115, 32, 99, 111, 108, 117, 109, 110, 115, 46, 32, 34, 83, 72, 79, 87, 32, 40, 113, 117, 101, 114, 121, 41, 34, 32, 100, 111, 101, 115, 32, 116, 111, 111, 32, 98, 117, 116, 32, 105, 115, 32, 100, 101, 112, 114, 101, 99, 97, 116, 101, 100, 44, 10, 35, 32, 115, 111, 32, 83, 104, 111, 119, 68, 101, 112, 114, 101, 99, 97, 116, 101, 100, 83, 101, 108, 101, 99, 116, 32, 105, 115, 32, 112, 97, 114, 115, 101, 100, 32, 121, 101, 116, 32, 115, 117, 112, 112, 114, 101, 115, 115, 101, 100, 32, 102, 114, 111, 109, 32, 97, 117, 116, 111, 99, 111, 109, 112, 108, 101, 116, 101, 32, 40, 109, 97, 116, 99, 104, 101, 114, 95, 102, 97, 99, 116, 111, 114, 121, 46, 99, 112, 112, 41, 32, 45, 32, 83, 72, 79, 87, 32, 119, 111, 110, 39, 116, 32, 111, 102, 102, 101, 114, 32, 116, 111, 32, 99, 111, 109, 112, 108, 101, 116, 101, 32, 97, 32, 113, 117, 101, 114, 121, 46, 10, 83, 104, 111, 119, 68, 101, 112, 114, 101, 99, 97, 116, 101, 100, 83, 101, 108, 101, 99, 116, 32, 60, 45, 32, 83, 104, 111, 119, 82, 117, 108, 101, 32, 83, 101, 108, 101, 99, 116, 83, 116, 97, 116, 101, 109, 101, 110, 116, 73, 110, 116, 101, 114, 110, 97, 108, 10, @@ -1889,11 +1891,19 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 35, 32, 69, 118, 101, 114, 121, 32, 115, 116, 97, 116, 101, 109, 101, 110, 116, 32, 97, 98, 111, 117, 116, 32, 101, 120, 116, 101, 114, 110, 97, 108, 32, 114, 101, 115, 111, 117, 114, 99, 101, 115, 44, 32, 115, 111, 32, 116, 104, 101, 32, 116, 111, 112, 45, 108, 101, 118, 101, 108, 32, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 99, 104, 111, 105, 99, 101, 32, 99, 97, 114, 114, 105, 101, 115, 32, 111, 110, 101, 32, 101, 110, 116, 114, 121, 10, 35, 32, 114, 97, 116, 104, 101, 114, 32, 116, 104, 97, 110, 32, 111, 110, 101, 32, 112, 101, 114, 32, 102, 111, 114, 109, 46, 32, 83, 72, 79, 87, 32, 91, 65, 76, 76, 93, 32, 69, 88, 84, 69, 82, 78, 65, 76, 32, 82, 69, 83, 79, 85, 82, 67, 69, 83, 32, 105, 115, 32, 97, 32, 113, 117, 101, 114, 121, 32, 40, 100, 101, 115, 99, 114, 105, 98, 101, 46, 103, 114, 97, 109, 41, 44, 32, 115, 111, 32, 105, 116, 32, 99, 97, 110, 32, 98, 101, 32, 97, 32, 115, 117, 98, 113, 117, 101, 114, 121, 46, 10, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 67, 114, 101, 97, 116, 101, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 47, 32, 82, 101, 103, 105, 115, 116, 101, 114, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 47, 32, 68, 101, 115, 116, 114, 111, 121, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 47, 32, 65, 116, 116, 97, 99, 104, 84, 111, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 32, 47, 32, 67, 111, 110, 110, 101, 99, 116, 84, 111, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 10, - 67, 114, 101, 97, 116, 101, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 60, 45, 32, 39, 67, 82, 69, 65, 84, 69, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 32, 65, 116, 116, 97, 99, 104, 65, 108, 105, 97, 115, 63, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 67, 114, 101, 97, 116, 105, 111, 110, 79, 112, 116, 105, 111, 110, 115, 63, 10, - 82, 101, 103, 105, 115, 116, 101, 114, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 60, 45, 32, 39, 82, 69, 71, 73, 83, 84, 69, 82, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 32, 65, 116, 116, 97, 99, 104, 65, 108, 105, 97, 115, 63, 32, 39, 70, 82, 79, 77, 39, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 67, 114, 101, 97, 116, 101, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 60, 45, 32, 39, 67, 82, 69, 65, 84, 69, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 32, 65, 116, 116, 97, 99, 104, 65, 108, 105, 97, 115, 63, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 67, 114, 101, 97, 116, 105, 111, 110, 79, 112, 116, 105, 111, 110, 115, 63, 10, + 82, 101, 103, 105, 115, 116, 101, 114, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 60, 45, 32, 39, 82, 69, 71, 73, 83, 84, 69, 82, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 32, 65, 116, 116, 97, 99, 104, 65, 108, 105, 97, 115, 63, 32, 39, 70, 82, 79, 77, 39, 32, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 68, 101, 115, 116, 114, 111, 121, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 116, 109, 116, 32, 60, 45, 32, 39, 68, 69, 83, 84, 82, 79, 89, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 67, 111, 108, 73, 100, 10, 35, 32, 83, 121, 110, 116, 97, 120, 32, 111, 110, 108, 121, 58, 32, 116, 104, 101, 32, 107, 101, 121, 119, 111, 114, 100, 32, 112, 97, 105, 114, 32, 101, 118, 101, 114, 121, 32, 115, 105, 110, 103, 117, 108, 97, 114, 32, 102, 111, 114, 109, 32, 114, 101, 112, 101, 97, 116, 115, 46, 10, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 60, 45, 32, 39, 69, 88, 84, 69, 82, 78, 65, 76, 39, 32, 39, 82, 69, 83, 79, 85, 82, 67, 69, 39, 10, + 35, 32, 84, 104, 101, 32, 116, 121, 112, 101, 32, 111, 102, 32, 97, 32, 114, 101, 115, 111, 117, 114, 99, 101, 44, 32, 97, 115, 32, 116, 104, 101, 32, 112, 114, 111, 118, 105, 100, 101, 114, 32, 114, 101, 103, 105, 115, 116, 101, 114, 101, 100, 32, 105, 116, 58, 32, 97, 119, 115, 46, 115, 51, 116, 97, 98, 108, 101, 115, 46, 98, 117, 99, 107, 101, 116, 46, 32, 73, 110, 32, 113, 117, 111, 116, 101, 115, 32, 105, 116, 32, 105, 115, 32, 116, 97, 107, 101, 110, 32, 97, 115, 32, 119, 114, 105, 116, 116, 101, 110, 59, 32, 115, 112, 101, 108, 108, 101, 100, 10, + 35, 32, 98, 97, 114, 101, 32, 105, 116, 32, 105, 115, 32, 102, 111, 108, 100, 101, 100, 32, 116, 111, 32, 108, 111, 119, 101, 114, 99, 97, 115, 101, 32, 40, 84, 114, 97, 110, 115, 102, 111, 114, 109, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 78, 97, 109, 101, 41, 46, 32, 65, 32, 116, 121, 112, 101, 32, 119, 105, 116, 104, 32, 111, 116, 104, 101, 114, 32, 99, 104, 97, 114, 97, 99, 116, 101, 114, 115, 32, 105, 110, 32, 105, 116, 44, 32, 111, 114, 32, 111, 110, 101, 10, + 35, 32, 115, 112, 101, 108, 108, 101, 100, 32, 119, 105, 116, 104, 32, 115, 112, 97, 99, 101, 115, 32, 97, 114, 111, 117, 110, 100, 32, 116, 104, 101, 32, 100, 111, 116, 115, 44, 32, 103, 111, 101, 115, 32, 105, 110, 32, 113, 117, 111, 116, 101, 115, 46, 10, + 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 32, 60, 45, 32, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 32, 47, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 78, 97, 109, 101, 10, + 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 78, 97, 109, 101, 32, 60, 45, 32, 66, 97, 114, 101, 78, 97, 109, 101, 10, + 35, 32, 65, 32, 110, 97, 109, 101, 32, 115, 112, 101, 108, 108, 101, 100, 32, 119, 105, 116, 104, 111, 117, 116, 32, 113, 117, 111, 116, 101, 115, 58, 32, 97, 32, 100, 111, 116, 116, 101, 100, 32, 110, 97, 109, 101, 32, 40, 68, 111, 116, 116, 101, 100, 78, 97, 109, 101, 44, 32, 108, 111, 97, 100, 46, 103, 114, 97, 109, 58, 32, 108, 97, 98, 101, 108, 115, 32, 115, 101, 112, 97, 114, 97, 116, 101, 100, 32, 98, 121, 32, 115, 105, 110, 103, 108, 101, 32, 100, 111, 116, 115, 44, 32, 110, 111, 116, 104, 105, 110, 103, 32, 105, 110, 10, + 35, 32, 98, 101, 116, 119, 101, 101, 110, 41, 32, 111, 114, 32, 97, 32, 112, 108, 97, 105, 110, 32, 119, 111, 114, 100, 10, + 66, 97, 114, 101, 78, 97, 109, 101, 32, 60, 45, 32, 68, 111, 116, 116, 101, 100, 78, 97, 109, 101, 32, 47, 32, 67, 111, 108, 73, 100, 10, 35, 32, 84, 104, 101, 32, 114, 101, 99, 105, 112, 101, 39, 115, 32, 99, 114, 101, 97, 116, 101, 32, 112, 97, 114, 97, 109, 115, 46, 32, 73, 116, 115, 32, 111, 119, 110, 32, 114, 117, 108, 101, 32, 114, 97, 116, 104, 101, 114, 32, 116, 104, 97, 110, 32, 65, 116, 116, 97, 99, 104, 79, 112, 116, 105, 111, 110, 115, 58, 32, 116, 104, 101, 32, 116, 119, 111, 32, 111, 112, 116, 105, 111, 110, 32, 98, 97, 103, 115, 32, 97, 114, 101, 10, 35, 32, 100, 105, 115, 116, 105, 110, 99, 116, 44, 32, 97, 110, 100, 32, 97, 32, 115, 116, 97, 116, 101, 109, 101, 110, 116, 32, 99, 97, 110, 32, 99, 97, 114, 114, 121, 32, 98, 111, 116, 104, 46, 10, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 67, 114, 101, 97, 116, 105, 111, 110, 79, 112, 116, 105, 111, 110, 115, 32, 60, 45, 32, 71, 101, 110, 101, 114, 105, 99, 67, 111, 112, 121, 79, 112, 116, 105, 111, 110, 76, 105, 115, 116, 10, @@ -1905,7 +1915,7 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 65, 116, 116, 97, 99, 104, 84, 111, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 32, 60, 45, 32, 39, 65, 84, 84, 65, 67, 72, 39, 32, 39, 84, 79, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 111, 117, 114, 99, 101, 32, 65, 116, 116, 97, 99, 104, 65, 108, 105, 97, 115, 32, 65, 116, 116, 97, 99, 104, 79, 112, 116, 105, 111, 110, 115, 63, 10, 67, 111, 110, 110, 101, 99, 116, 84, 111, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 32, 60, 45, 32, 39, 67, 79, 78, 78, 69, 67, 84, 39, 32, 39, 84, 79, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 111, 117, 114, 99, 101, 32, 65, 116, 116, 97, 99, 104, 79, 112, 116, 105, 111, 110, 115, 63, 10, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 83, 111, 117, 114, 99, 101, 32, 60, 45, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 67, 114, 101, 97, 116, 101, 67, 108, 97, 117, 115, 101, 32, 47, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 82, 101, 102, 101, 114, 101, 110, 99, 101, 67, 108, 97, 117, 115, 101, 10, - 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 67, 114, 101, 97, 116, 101, 67, 108, 97, 117, 115, 101, 32, 60, 45, 32, 39, 78, 69, 87, 39, 32, 39, 84, 69, 77, 80, 79, 82, 65, 82, 89, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 67, 114, 101, 97, 116, 105, 111, 110, 79, 112, 116, 105, 111, 110, 115, 63, 10, + 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 67, 114, 101, 97, 116, 101, 67, 108, 97, 117, 115, 101, 32, 60, 45, 32, 39, 78, 69, 87, 39, 32, 39, 84, 69, 77, 80, 79, 82, 65, 82, 89, 39, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 84, 121, 112, 101, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 67, 114, 101, 97, 116, 105, 111, 110, 79, 112, 116, 105, 111, 110, 115, 63, 10, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 82, 101, 102, 101, 114, 101, 110, 99, 101, 67, 108, 97, 117, 115, 101, 32, 60, 45, 32, 69, 120, 116, 101, 114, 110, 97, 108, 82, 101, 115, 111, 117, 114, 99, 101, 75, 101, 121, 119, 111, 114, 100, 32, 67, 111, 108, 73, 100, 10, 73, 110, 115, 101, 114, 116, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 87, 105, 116, 104, 67, 108, 97, 117, 115, 101, 63, 32, 39, 73, 78, 83, 69, 82, 84, 39, 32, 79, 114, 65, 99, 116, 105, 111, 110, 63, 32, 39, 73, 78, 84, 79, 39, 32, 73, 110, 115, 101, 114, 116, 84, 97, 114, 103, 101, 116, 32, 66, 121, 78, 97, 109, 101, 79, 114, 80, 111, 115, 105, 116, 105, 111, 110, 63, 32, 73, 110, 115, 101, 114, 116, 67, 111, 108, 117, 109, 110, 76, 105, 115, 116, 63, 32, 79, 118, 101, 114, 114, 105, 100, 105, 110, 103, 67, 108, 97, 117, 115, 101, 63, 32, 73, 110, 115, 101, 114, 116, 86, 97, 108, 117, 101, 115, 32, 79, 110, 67, 111, 110, 102, 108, 105, 99, 116, 67, 108, 97, 117, 115, 101, 63, 32, 82, 101, 116, 117, 114, 110, 105, 110, 103, 67, 108, 97, 117, 115, 101, 63, 10, 79, 114, 65, 99, 116, 105, 111, 110, 32, 60, 45, 32, 73, 110, 115, 101, 114, 116, 79, 114, 82, 101, 112, 108, 97, 99, 101, 32, 47, 32, 73, 110, 115, 101, 114, 116, 79, 114, 73, 103, 110, 111, 114, 101, 10, @@ -1941,8 +1951,8 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 70, 114, 111, 109, 83, 111, 117, 114, 99, 101, 32, 60, 45, 32, 70, 114, 111, 109, 83, 111, 117, 114, 99, 101, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 32, 47, 32, 70, 114, 111, 109, 83, 111, 117, 114, 99, 101, 83, 116, 114, 105, 110, 103, 10, 70, 114, 111, 109, 83, 111, 117, 114, 99, 101, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 32, 60, 45, 32, 39, 70, 82, 79, 77, 39, 32, 70, 114, 111, 109, 83, 111, 117, 114, 99, 101, 78, 97, 109, 101, 10, 70, 114, 111, 109, 83, 111, 117, 114, 99, 101, 83, 116, 114, 105, 110, 103, 32, 60, 45, 32, 39, 70, 82, 79, 77, 39, 32, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 10, - 35, 32, 97, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 32, 110, 97, 109, 101, 100, 32, 97, 102, 116, 101, 114, 32, 105, 116, 115, 32, 104, 111, 115, 116, 32, 105, 115, 32, 115, 112, 101, 108, 108, 101, 100, 32, 97, 115, 32, 100, 111, 116, 116, 101, 100, 32, 119, 111, 114, 100, 115, 58, 32, 73, 78, 83, 84, 65, 76, 76, 32, 120, 32, 70, 82, 79, 77, 32, 99, 97, 114, 108, 111, 112, 105, 46, 103, 105, 116, 104, 117, 98, 46, 105, 111, 10, - 70, 114, 111, 109, 83, 111, 117, 114, 99, 101, 78, 97, 109, 101, 32, 60, 45, 32, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 72, 111, 115, 116, 78, 97, 109, 101, 32, 47, 32, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 10, + 35, 32, 97, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 32, 109, 97, 121, 32, 98, 101, 32, 110, 97, 109, 101, 100, 32, 98, 121, 32, 97, 32, 100, 111, 116, 116, 101, 100, 32, 110, 97, 109, 101, 58, 32, 73, 78, 83, 84, 65, 76, 76, 32, 120, 32, 70, 82, 79, 77, 32, 99, 97, 114, 108, 111, 112, 105, 46, 103, 105, 116, 104, 117, 98, 46, 105, 111, 10, + 70, 114, 111, 109, 83, 111, 117, 114, 99, 101, 78, 97, 109, 101, 32, 60, 45, 32, 68, 111, 116, 116, 101, 100, 78, 97, 109, 101, 32, 47, 32, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 10, 86, 101, 114, 115, 105, 111, 110, 78, 117, 109, 98, 101, 114, 32, 60, 45, 32, 39, 86, 69, 82, 83, 73, 79, 78, 39, 32, 73, 100, 101, 110, 116, 105, 102, 105, 101, 114, 79, 114, 83, 116, 114, 105, 110, 103, 76, 105, 116, 101, 114, 97, 108, 10, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 83, 116, 97, 116, 101, 109, 101, 110, 116, 32, 60, 45, 32, 67, 114, 101, 97, 116, 101, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 83, 116, 109, 116, 32, 47, 32, 67, 114, 101, 97, 116, 101, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 70, 114, 111, 109, 72, 111, 115, 116, 83, 116, 109, 116, 32, 47, 32, 68, 114, 111, 112, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 83, 116, 109, 116, 10, 67, 114, 101, 97, 116, 101, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 83, 116, 109, 116, 32, 60, 45, 32, 39, 67, 82, 69, 65, 84, 69, 39, 32, 79, 114, 82, 101, 112, 108, 97, 99, 101, 63, 32, 39, 69, 88, 84, 69, 78, 83, 73, 79, 78, 39, 32, 39, 82, 69, 80, 79, 83, 73, 84, 79, 82, 89, 39, 32, 73, 102, 78, 111, 116, 69, 120, 105, 115, 116, 115, 63, 32, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 78, 97, 109, 101, 32, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 80, 114, 101, 102, 105, 120, 32, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 80, 117, 98, 108, 105, 99, 75, 101, 121, 63, 10, @@ -1953,10 +1963,14 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 35, 32, 116, 104, 101, 32, 115, 105, 103, 110, 105, 110, 103, 32, 107, 101, 121, 115, 41, 46, 32, 84, 104, 101, 32, 114, 101, 115, 116, 32, 105, 115, 32, 67, 82, 69, 65, 84, 69, 32, 69, 88, 84, 69, 78, 83, 73, 79, 78, 32, 82, 69, 80, 79, 83, 73, 84, 79, 82, 89, 32, 60, 110, 97, 109, 101, 62, 32, 87, 73, 84, 72, 32, 80, 82, 69, 70, 73, 88, 32, 60, 116, 104, 97, 116, 32, 112, 114, 101, 102, 105, 120, 62, 46, 10, 67, 114, 101, 97, 116, 101, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 70, 114, 111, 109, 72, 111, 115, 116, 83, 116, 109, 116, 32, 60, 45, 32, 39, 67, 82, 69, 65, 84, 69, 39, 32, 79, 114, 82, 101, 112, 108, 97, 99, 101, 63, 32, 39, 69, 88, 84, 69, 78, 83, 73, 79, 78, 39, 32, 39, 82, 69, 80, 79, 83, 73, 84, 79, 82, 89, 39, 32, 73, 102, 78, 111, 116, 69, 120, 105, 115, 116, 115, 63, 32, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 78, 97, 109, 101, 10, 68, 114, 111, 112, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 83, 116, 109, 116, 32, 60, 45, 32, 39, 68, 82, 79, 80, 39, 32, 39, 69, 88, 84, 69, 78, 83, 73, 79, 78, 39, 32, 39, 82, 69, 80, 79, 83, 73, 84, 79, 82, 89, 39, 32, 73, 102, 69, 120, 105, 115, 116, 115, 63, 32, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 78, 97, 109, 101, 10, - 35, 32, 65, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 32, 110, 97, 109, 101, 58, 32, 97, 110, 32, 105, 100, 101, 110, 116, 105, 102, 105, 101, 114, 32, 111, 114, 32, 97, 32, 115, 116, 114, 105, 110, 103, 44, 32, 111, 114, 32, 97, 32, 104, 111, 115, 116, 32, 115, 112, 101, 108, 108, 101, 100, 32, 97, 115, 32, 100, 111, 116, 116, 101, 100, 32, 119, 111, 114, 100, 115, 46, 32, 65, 32, 104, 111, 115, 116, 32, 119, 105, 116, 104, 32, 97, 32, 39, 45, 39, 32, 105, 110, 32, 105, 116, 32, 99, 97, 110, 110, 111, 116, 32, 98, 101, 10, - 35, 32, 115, 112, 101, 108, 108, 101, 100, 32, 117, 110, 113, 117, 111, 116, 101, 100, 32, 40, 39, 45, 39, 32, 105, 115, 32, 97, 110, 32, 111, 112, 101, 114, 97, 116, 111, 114, 41, 59, 32, 105, 116, 32, 105, 115, 32, 103, 105, 118, 101, 110, 32, 97, 115, 32, 97, 32, 115, 116, 114, 105, 110, 103, 58, 32, 39, 100, 117, 99, 107, 100, 98, 45, 101, 120, 116, 101, 110, 115, 105, 111, 110, 115, 46, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109, 39, 10, - 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 78, 97, 109, 101, 32, 60, 45, 32, 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 72, 111, 115, 116, 78, 97, 109, 101, 32, 47, 32, 67, 111, 108, 73, 100, 79, 114, 83, 116, 114, 105, 110, 103, 10, - 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 72, 111, 115, 116, 78, 97, 109, 101, 32, 60, 45, 32, 67, 111, 108, 73, 100, 32, 68, 111, 116, 67, 111, 108, 76, 97, 98, 101, 108, 43, 10, + 35, 32, 65, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 32, 110, 97, 109, 101, 58, 32, 97, 110, 32, 105, 100, 101, 110, 116, 105, 102, 105, 101, 114, 32, 111, 114, 32, 97, 32, 115, 116, 114, 105, 110, 103, 44, 32, 111, 114, 32, 97, 32, 100, 111, 116, 116, 101, 100, 32, 110, 97, 109, 101, 32, 115, 112, 101, 108, 108, 101, 100, 32, 119, 105, 116, 104, 111, 117, 116, 32, 113, 117, 111, 116, 101, 115, 10, + 69, 120, 116, 101, 110, 115, 105, 111, 110, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 78, 97, 109, 101, 32, 60, 45, 32, 68, 111, 116, 116, 101, 100, 78, 97, 109, 101, 32, 47, 32, 67, 111, 108, 73, 100, 79, 114, 83, 116, 114, 105, 110, 103, 10, + 35, 32, 65, 32, 100, 111, 116, 116, 101, 100, 32, 110, 97, 109, 101, 32, 115, 112, 101, 108, 108, 101, 100, 32, 119, 105, 116, 104, 111, 117, 116, 32, 113, 117, 111, 116, 101, 115, 58, 32, 99, 97, 114, 108, 111, 112, 105, 46, 103, 105, 116, 104, 117, 98, 46, 105, 111, 44, 32, 109, 121, 45, 119, 101, 98, 115, 105, 116, 101, 46, 99, 111, 109, 46, 32, 77, 97, 116, 99, 104, 101, 100, 32, 98, 121, 32, 68, 111, 116, 116, 101, 100, 78, 97, 109, 101, 77, 97, 116, 99, 104, 101, 114, 44, 32, 119, 104, 105, 99, 104, 32, 103, 108, 117, 101, 115, 32, 116, 104, 101, 10, + 35, 32, 119, 111, 114, 100, 115, 44, 32, 100, 111, 116, 115, 32, 97, 110, 100, 32, 100, 97, 115, 104, 101, 115, 32, 116, 104, 101, 32, 116, 111, 107, 101, 110, 105, 122, 101, 114, 32, 99, 117, 116, 32, 105, 116, 32, 105, 110, 116, 111, 44, 32, 97, 115, 32, 108, 111, 110, 103, 32, 97, 115, 32, 110, 111, 116, 104, 105, 110, 103, 32, 115, 101, 112, 97, 114, 97, 116, 101, 115, 32, 116, 104, 101, 109, 32, 40, 110, 111, 32, 119, 104, 105, 116, 101, 115, 112, 97, 99, 101, 32, 111, 114, 32, 99, 111, 109, 109, 101, 110, 116, 32, 105, 110, 10, + 35, 32, 98, 101, 116, 119, 101, 101, 110, 41, 58, 32, 108, 97, 98, 101, 108, 115, 32, 111, 102, 32, 119, 111, 114, 100, 115, 32, 106, 111, 105, 110, 101, 100, 32, 98, 121, 32, 115, 105, 110, 103, 108, 101, 32, 100, 97, 115, 104, 101, 115, 44, 32, 115, 101, 112, 97, 114, 97, 116, 101, 100, 32, 98, 121, 32, 115, 105, 110, 103, 108, 101, 32, 100, 111, 116, 115, 46, 32, 84, 119, 111, 32, 100, 97, 115, 104, 101, 115, 32, 105, 110, 32, 97, 32, 114, 111, 119, 32, 115, 116, 97, 114, 116, 32, 97, 32, 99, 111, 109, 109, 101, 110, 116, 32, 102, 111, 114, 10, + 35, 32, 116, 104, 101, 32, 116, 111, 107, 101, 110, 105, 122, 101, 114, 44, 32, 115, 111, 32, 39, 120, 110, 45, 45, 98, 99, 104, 101, 114, 45, 107, 118, 97, 46, 101, 120, 97, 109, 112, 108, 101, 39, 32, 99, 97, 110, 110, 111, 116, 32, 98, 101, 32, 115, 112, 101, 108, 108, 101, 100, 32, 117, 110, 113, 117, 111, 116, 101, 100, 32, 40, 105, 116, 32, 114, 101, 97, 100, 115, 32, 97, 115, 32, 39, 120, 110, 39, 41, 59, 32, 113, 117, 111, 116, 101, 100, 32, 112, 97, 114, 116, 115, 32, 40, 34, 109, 121, 45, 115, 105, 116, 101, 34, 46, 99, 111, 109, 41, 10, + 35, 32, 97, 114, 101, 32, 110, 111, 116, 32, 97, 32, 100, 111, 116, 116, 101, 100, 32, 110, 97, 109, 101, 32, 101, 105, 116, 104, 101, 114, 58, 32, 97, 32, 110, 97, 109, 101, 32, 119, 105, 116, 104, 32, 115, 117, 99, 104, 32, 112, 97, 114, 116, 115, 32, 103, 111, 101, 115, 32, 105, 110, 32, 113, 117, 111, 116, 101, 115, 32, 97, 115, 32, 97, 32, 119, 104, 111, 108, 101, 10, + 68, 111, 116, 116, 101, 100, 78, 97, 109, 101, 32, 60, 45, 32, 60, 91, 97, 45, 122, 48, 45, 57, 95, 93, 105, 43, 40, 39, 45, 39, 91, 97, 45, 122, 48, 45, 57, 95, 93, 105, 43, 41, 42, 40, 39, 46, 39, 91, 97, 45, 122, 48, 45, 57, 95, 93, 105, 43, 40, 39, 45, 39, 91, 97, 45, 122, 48, 45, 57, 95, 93, 105, 43, 41, 42, 41, 43, 62, 10, 84, 97, 98, 108, 101, 77, 97, 116, 99, 104, 82, 101, 99, 111, 103, 110, 105, 122, 101, 67, 108, 97, 117, 115, 101, 32, 60, 45, 32, 39, 77, 65, 84, 67, 72, 95, 82, 69, 67, 79, 71, 78, 73, 90, 69, 39, 32, 80, 97, 114, 101, 110, 115, 40, 77, 97, 116, 99, 104, 82, 101, 99, 111, 103, 110, 105, 122, 101, 66, 111, 100, 121, 41, 32, 84, 97, 98, 108, 101, 65, 108, 105, 97, 115, 63, 10, 77, 97, 116, 99, 104, 82, 101, 99, 111, 103, 110, 105, 122, 101, 66, 111, 100, 121, 32, 60, 45, 32, 77, 97, 116, 99, 104, 82, 101, 99, 111, 103, 110, 105, 122, 101, 67, 108, 97, 117, 115, 101, 43, 10, 77, 97, 116, 99, 104, 82, 101, 99, 111, 103, 110, 105, 122, 101, 67, 108, 97, 117, 115, 101, 32, 60, 45, 32, 77, 82, 80, 97, 114, 116, 105, 116, 105, 111, 110, 32, 47, 32, 77, 82, 79, 114, 100, 101, 114, 66, 121, 32, 47, 32, 77, 82, 77, 101, 97, 115, 117, 114, 101, 115, 32, 47, 32, 77, 82, 82, 111, 119, 115, 32, 47, 32, 77, 82, 83, 107, 105, 112, 32, 47, 32, 77, 82, 80, 97, 116, 116, 101, 114, 110, 32, 47, 32, 77, 82, 83, 117, 98, 115, 101, 116, 32, 47, 32, 77, 82, 68, 101, 102, 105, 110, 101, 65, 117, 116, 111, 32, 47, 32, 77, 82, 68, 101, 102, 105, 110, 101, 10, diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp index ddbc609a8..71f227652 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher.hpp @@ -200,10 +200,10 @@ struct MatchState { } template - MatcherResult AllocateParseResult(ARGS &&... args); + MatcherResult AllocateParseResult(ARGS &&...args); template - arena_ptr Make(ARGS &&... args); + arena_ptr Make(ARGS &&...args); void UpdateMaxTokenIndex() { if (token_iterator.Position() > context.max_token_index) { @@ -280,29 +280,101 @@ enum class MatcherType { CUSTOM }; -//! Over-approximation of the tokens a matcher can start with (its FIRST set), computed once per grammar. Lets the -//! matcher skip sub-matchers that certainly cannot match at the current token. -struct MatcherFirstSet { - bool computed = false; - //! the matcher can succeed without consuming a token - bool nullable = false; - //! no information: never skip +//! A set of tokens: token classes plus grammar literal ids (keywords and symbols), or every token +struct MatcherTokenSet { + //! no information: contains every token bool any = false; //! MatcherTokenClass bits uint8_t class_mask = 0; - //! bitset over grammar literal ids (keywords and symbols) + //! bitset over grammar literal ids vector literals; - optional_ptr table; bool HasLiteral(idx_t literal_id) const { auto word = literal_id / 64; return word < literals.size() && (literals[word] >> (literal_id % 64)) & 1; } DUCKDB_API void AddLiteral(idx_t literal_id); + //! Merge the tokens of other into this set, returns whether anything changed + DUCKDB_API bool MergeTokens(const MatcherTokenSet &other); + DUCKDB_API bool IsEmpty() const; + DUCKDB_API bool Equals(const MatcherTokenSet &other) const; + void SetAny() { + any = true; + } + //! Whether the token can be in the set; GET_LITERAL supplies its literal info only when needed + template + bool Contains(const MatcherToken &token, GET_LITERAL &&get_literal) const { + if (any) { + return true; + } + if (token.token_class & class_mask) { + return true; + } + auto literal_id = get_literal().LiteralId(); + return literal_id && HasLiteral(literal_id); + } +}; + +//! Over-approximation of the tokens a matcher can start with (its FIRST set), computed once per grammar, together with +//! the tokens for which it can match exactly one token (ONE) and the tokens it can see second (SECOND). Lets the +//! matcher skip sub-matchers that certainly cannot match at the current token. +struct MatcherFirstSet : public MatcherTokenSet { + bool computed = false; + //! the matcher can succeed without consuming a token + bool nullable = false; + //! every token in FIRST passes the lookahead check, so only FIRST has to be tested + bool first_suffices = true; + optional_ptr table; + //! first tokens for which a match consuming exactly one token is possible + MatcherTokenSet one; + //! second tokens of matches consuming at least two tokens + MatcherTokenSet second; + //! Merge other into this set, returns whether anything changed DUCKDB_API bool Merge(const MatcherFirstSet &other); + //! Derive first_suffices once the sets are final + DUCKDB_API void Finalize(); + //! No information about any token + void SetAny() { + any = true; + one.any = true; + second.any = true; + } + //! The matcher consumes exactly one token, drawn from its FIRST set + void SetSingleToken() { + one.any = any; + one.class_mask = class_mask; + one.literals = literals; + second = MatcherTokenSet(); + } //! False only if the matcher certainly cannot match at the current token - DUCKDB_API bool MightMatch(MatchState &state) const; + bool MightMatch(MatchState &state) const { + if (!computed || any || nullable) { + return true; + } + auto &iterator = state.token_iterator; + auto token = iterator.Current(); + if (!token) { + return false; + } + auto token_class = token->token_class; + if (!(token_class & class_mask)) { + auto literal_id = iterator.CurrentLiteralInfo(*table).LiteralId(); + if (!literal_id || !HasLiteral(literal_id)) { + return false; + } + if (first_suffices || one.HasLiteral(literal_id)) { + return true; + } + return MightMatchSecond(state); + } + if (first_suffices || (token_class & one.class_mask)) { + return true; + } + return MightMatchSecond(state); + } + //! The lookahead check for a token in FIRST: a one-token match or a valid second token + DUCKDB_API bool MightMatchSecond(MatchState &state) const; }; class Matcher { @@ -315,8 +387,9 @@ class Matcher { MatcherResult MatchParseResult(MatchState &state) const; //! Create matcher-local state with state.Make() for incremental execution. virtual arena_ptr StartMatch(MatchState &state) const = 0; - virtual bool IsAtomic() const { - return false; + //! Whether the matcher is an AtomicMatcher, which matches in one step without a process + bool IsAtomic() const { + return atomic; } virtual SuggestionType AddSuggestion(MatchState &state) const; virtual SuggestionType AddSuggestionInternal(MatchState &state) const = 0; @@ -395,19 +468,20 @@ class Matcher { return reinterpret_cast(*this); } -public: - MatcherFirstSet first_set; - protected: friend class MatcherAllocator; MatcherType type; - string name; - string label; - optional_idx packrat_id; + bool atomic = false; bool packrat_memoized = false; bool collapsible = false; bool structural = false; + optional_idx packrat_id; optional_ptr rule; + string name; + string label; + +public: + MatcherFirstSet first_set; }; //! Compute the FIRST sets of all matchers reachable from root @@ -416,16 +490,14 @@ DUCKDB_API void ComputeFirstSets(Matcher &root, const GrammarLiteralTable &table class AtomicMatcher : public Matcher { public: explicit AtomicMatcher(MatcherType type) : Matcher(type) { + atomic = true; } - bool IsAtomic() const final { - return true; - } DUCKDB_API arena_ptr StartMatch(MatchState &state) const final; virtual MatcherResult MatchAtomic(MatchState &state) const = 0; //! Describes the tokens this matcher can start with; the default (no information) never skips the matcher virtual void InitializeFirstSet(MatcherFirstSet &first_set, const GrammarLiteralTable &table) const { - first_set.any = true; + first_set.SetAny(); } }; @@ -457,13 +529,17 @@ class MatcherAllocator { vector> list_chains; }; +//! The arenas of a parse (parse results, matcher frames, packrat entries, transform results) start with room for +//! a typical statement, so that it does not grow them through several chunks first +static constexpr idx_t PARSER_ARENA_INITIAL_CAPACITY = 8 * ArenaAllocator::ARENA_ALLOCATOR_INITIAL_CAPACITY; + class ParseResultAllocator { public: ParseResultAllocator(); ~ParseResultAllocator(); template - optional_ptr Make(ARGS &&... args) { + optional_ptr Make(ARGS &&...args) { static_assert(std::is_base_of::value, "Expected a parse result"); auto result = arena.Make(std::forward(args)...); if (ParseResultNeedsDestructor::value) { @@ -506,7 +582,7 @@ class ParseResultAllocator { }; template -arena_ptr MatchState::Make(ARGS &&... args) { +arena_ptr MatchState::Make(ARGS &&...args) { static_assert(std::is_base_of::value, "Expected a matcher process"); return arena_ptr(context.process_allocator.Make(std::forward(args)...)); } @@ -520,7 +596,7 @@ void ParseResult::SetNameFrom(const Matcher &matcher_p) { } template -MatcherResult MatchState::AllocateParseResult(ARGS &&... args) { +MatcherResult MatchState::AllocateParseResult(ARGS &&...args) { if (!BuildParseResult()) { return MatcherResult::Success(); } diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher/arithmetic_operator_matcher.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher/arithmetic_operator_matcher.hpp index 93f31f77f..50dd0278d 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher/arithmetic_operator_matcher.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher/arithmetic_operator_matcher.hpp @@ -38,6 +38,7 @@ class ArithmeticOperatorMatcher : public AtomicMatcher { void InitializeFirstSet(MatcherFirstSet &first_set, const GrammarLiteralTable &table) const override { first_set.class_mask = MatcherTokenClass::OPERATOR; + first_set.SetSingleToken(); } private: diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher/dotted_name_matcher.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher/dotted_name_matcher.hpp new file mode 100644 index 000000000..e6b149b6a --- /dev/null +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher/dotted_name_matcher.hpp @@ -0,0 +1,115 @@ +#pragma once + +#include "duckdb/parser/peg/tokenizer/tokenizer.hpp" +#include "duckdb/parser/peg/matcher.hpp" + +namespace duckdb { + +//! Matches a dotted name spelled without quotes: 'carlopi.github.io', 'my-website.com'. The tokenizer cuts such a name +//! into words, '.' and '-' tokens; this matcher glues them back together as long as they touch (no whitespace or +//! comment in between) and the result is a dotted name (IsDottedName): labels of words joined by single dashes, +//! separated by single dots. Note that '--' starts a comment for the tokenizer, so a label with two dashes in a row +//! cannot be spelled unquoted at all; it is not a dotted name either way. +class DottedNameMatcher : public AtomicMatcher { +public: + static constexpr MatcherType TYPE = MatcherType::VARIABLE; + +public: + DottedNameMatcher() : AtomicMatcher(TYPE) { + name = "DottedName"; + } + + MatcherResult MatchAtomic(MatchState &state) const override { + auto token = state.token_iterator.Current(); + if (!token) { + return MatcherResult::Failure(); + } + auto start_offset = token->offset; + string text; + idx_t end_offset = start_offset; + idx_t token_count = 0; + while (true) { + auto next = state.token_iterator.Current(); + if (!next || next->offset != end_offset || !IsNamePart(*next)) { + break; + } + text += next->text; + end_offset = next->offset + next->length; + state.token_iterator.Advance(); + token_count++; + } + if (token_count == 0 || !IsDottedName(text)) { + return MatcherResult::Failure(); + } + state.UpdateMaxTokenIndex(); + state.token_iterator.SetPreviousTokenType(TokenType::IDENTIFIER); + if (!state.BuildParseResult()) { + return MatcherResult::Success(); + } + state.FoldIdentifier(text); + return state.AllocateParseResult(text, optional_idx(start_offset), + optional_idx(end_offset - start_offset)); + } + + SuggestionType AddSuggestionInternal(MatchState &state) const override { + return SuggestionType::MANDATORY; + } + + string ToString() const override { + return "DOTTED_NAME"; + } + + //! Never skipped: a name can start with a number token that has no token class, such as 127.0.0.1 + void InitializeFirstSet(MatcherFirstSet &first_set, const GrammarLiteralTable &table) const override { + first_set.SetAny(); + } + + //! A dotted name: two or more labels separated by single dots, each label one or more words joined by single + //! dashes, each word one or more letters, digits or '_' (bytes outside ASCII count as letters, so that a name like + //! münchen.de is a name here and gets the manager's answer rather than a syntax error). So no label starts or ends + //! with '-', and no two dashes touch + static bool IsDottedName(const string &text) { + idx_t label_count = 0; + idx_t word_length = 0; + for (idx_t i = 0; i <= text.size(); i++) { + auto c = i < text.size() ? text[i] : '.'; + if (c == '.' || c == '-') { + // a separator ends a word, which must not be empty + if (word_length == 0) { + return false; + } + word_length = 0; + if (c == '.') { + label_count++; + } + continue; + } + if (!StringUtil::CharacterIsAlpha(c) && !StringUtil::CharacterIsDigit(c) && c != '_' && + static_cast(c) < 0x80) { + return false; + } + word_length++; + } + return label_count >= 2; + } + +private: + //! A token that can be part of an unquoted dotted name: a plain word or number, or a lone '.' or '-' + static bool IsNamePart(const MatcherToken &token) { + if (token.text.empty()) { + return false; + } + switch (token.type) { + case TokenType::KEYWORD: + case TokenType::IDENTIFIER: + case TokenType::NUMBER_LITERAL: + return true; + case TokenType::OPERATOR: + return token.text == "." || token.text == "-"; + default: + return false; + } + } +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher/identifier_matcher.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher/identifier_matcher.hpp index a8163c699..3708130a2 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher/identifier_matcher.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher/identifier_matcher.hpp @@ -161,8 +161,18 @@ class IdentifierMatcher : public AtomicMatcher { } } + //! Non-keyword words, string literals where those stand for names, and the keywords the mask allows void InitializeFirstSet(MatcherFirstSet &first_set, const GrammarLiteralTable &table) const override { - first_set.class_mask = MatcherTokenClass::WORD; + first_set.class_mask = MatcherTokenClass::IDENTIFIER; + if (SupportsStringLiteral()) { + first_set.class_mask |= MatcherTokenClass::STRING; + } + table.ForEachLiteral([&](const LiteralInfo &info) { + if (info.IsKeyword() && info.HasAnyFlags(identifier_mask)) { + first_set.AddLiteral(info.LiteralId()); + } + }); + first_set.SetSingleToken(); } private: @@ -225,6 +235,14 @@ class ReservedIdentifierMatcher : public IdentifierMatcher { return state.AllocateParseResult(result_text, start_offset, token_length); } + void InitializeFirstSet(MatcherFirstSet &first_set, const GrammarLiteralTable &table) const override { + first_set.class_mask = MatcherTokenClass::WORD; + if (SupportsStringLiteral()) { + first_set.class_mask |= MatcherTokenClass::STRING; + } + first_set.SetSingleToken(); + } + private: bool MatchReservedIdentifier(MatchState &state) const { auto token = state.token_iterator.Current(); diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher/keyword_matcher.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher/keyword_matcher.hpp index cc111d606..8c43fab37 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher/keyword_matcher.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher/keyword_matcher.hpp @@ -64,6 +64,7 @@ class KeywordMatcher : public AtomicMatcher { } else { first_set.any = true; } + first_set.SetSingleToken(); } private: diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher/list.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher/list.hpp index 41acefaea..b436af05f 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher/list.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher/list.hpp @@ -1,6 +1,7 @@ #include "duckdb/parser/peg/matcher/arithmetic_operator_matcher.hpp" #include "duckdb/parser/peg/matcher/choice_matcher.hpp" #include "duckdb/parser/peg/matcher/end_of_input_matcher.hpp" +#include "duckdb/parser/peg/matcher/dotted_name_matcher.hpp" #include "duckdb/parser/peg/matcher/identifier_matcher.hpp" #include "duckdb/parser/peg/matcher/keyword_matcher.hpp" #include "duckdb/parser/peg/matcher/list_matcher.hpp" diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher/number_literal_matcher.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher/number_literal_matcher.hpp index 64936d1c2..827bede1e 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher/number_literal_matcher.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher/number_literal_matcher.hpp @@ -44,15 +44,11 @@ class NumberLiteralMatcher : public AtomicMatcher { void InitializeFirstSet(MatcherFirstSet &first_set, const GrammarLiteralTable &table) const override { first_set.class_mask = MatcherTokenClass::NUMBER; + first_set.SetSingleToken(); } -private: - static bool MatchNumberLiteral(MatchState &state) { - auto token = state.token_iterator.Current(); - if (!token) { - return false; - } - auto &token_text = token->text; + //! Whether the matcher accepts the token text; the tokenizer uses this to classify number tokens + static bool IsNumberLiteral(const string &token_text) { if (token_text.empty() || !Tokenizer::CharacterIsInitialNumber(token_text[0])) { return false; } @@ -72,7 +68,7 @@ class NumberLiteralMatcher : public AtomicMatcher { } if (Tokenizer::CharacterIsScientific(token_text[i])) { if (scientific_notation) { - throw ParserException("Already found scientific notation"); + return false; } scientific_notation = true; } @@ -83,6 +79,15 @@ class NumberLiteralMatcher : public AtomicMatcher { return false; } } + return true; + } + +private: + static bool MatchNumberLiteral(MatchState &state) { + auto token = state.token_iterator.Current(); + if (!token || !IsNumberLiteral(token->text)) { + return false; + } state.token_iterator.Advance(); state.UpdateMaxTokenIndex(); return true; diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher/operator_matcher.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher/operator_matcher.hpp index 581774acc..d1aee89f8 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher/operator_matcher.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher/operator_matcher.hpp @@ -42,6 +42,7 @@ class OperatorMatcher : public AtomicMatcher { void InitializeFirstSet(MatcherFirstSet &first_set, const GrammarLiteralTable &table) const override { first_set.class_mask = mode == OperatorMatcherMode::GENERIC_PRECEDENCE ? MatcherTokenClass::GENERIC_OPERATOR : MatcherTokenClass::OPERATOR; + first_set.SetSingleToken(); } private: diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher/string_literal_matcher.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher/string_literal_matcher.hpp index 086a51ecc..b4684b6b4 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher/string_literal_matcher.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher/string_literal_matcher.hpp @@ -70,6 +70,9 @@ class StringLiteralMatcher : public AtomicMatcher { void InitializeFirstSet(MatcherFirstSet &first_set, const GrammarLiteralTable &table) const override { first_set.class_mask = MatcherTokenClass::STRING; + // a literal can continue with further string literals on following lines + first_set.SetSingleToken(); + first_set.second.class_mask = MatcherTokenClass::STRING; } private: diff --git a/src/duckdb/src/include/duckdb/parser/peg/matcher_token.hpp b/src/duckdb/src/include/duckdb/parser/peg/matcher_token.hpp index cbd5dd427..5d9e3c949 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/matcher_token.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/matcher_token.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/string.hpp" +#include "duckdb/common/assert.hpp" #include "duckdb/common/winapi.hpp" #include "duckdb/parser/peg/token_type.hpp" #include "duckdb/parser/peg/grammar_literal_table.hpp" @@ -24,6 +25,15 @@ struct MatcherTokenClass { static constexpr uint8_t GENERIC_OPERATOR = 4; static constexpr uint8_t STRING = 8; static constexpr uint8_t NUMBER = 16; + //! a word that is not a keyword of the grammar + static constexpr uint8_t IDENTIFIER = 32; +}; + +//! A token class that the caller already derived for the text it passes to a MatcherToken +struct PrecomputedTokenClass { + explicit PrecomputedTokenClass(uint8_t value_p) : value(value_p) { + } + uint8_t value; }; //! The token class of a token as emitted by the tokenizer (implemented in base_tokenizer.cpp) @@ -37,6 +47,20 @@ struct MatcherToken { length = text.length(); token_class = ComputeMatcherTokenClass(type, text); } + //! Builds the text in place from a range of the input + MatcherToken(const char *data, idx_t size, idx_t offset_p, TokenType type_p, bool unterminated_p = false) + : type(type_p), text(data, size), offset(offset_p), length(size), unterminated(unterminated_p) { + if (type == TokenType::KEYWORD) { + token_class = MatcherTokenClass::WORD; + } else if (type == TokenType::IDENTIFIER) { + token_class = MatcherTokenClass::WORD | MatcherTokenClass::IDENTIFIER; + } else { + token_class = ComputeMatcherTokenClass(type, text); + } + } + MatcherToken(const char *data, idx_t size, idx_t offset_p, TokenType type_p, PrecomputedTokenClass token_class_p) + : type(type_p), text(data, size), offset(offset_p), length(size), token_class(token_class_p.value) { + } TokenType type; string text; @@ -48,13 +72,23 @@ struct MatcherToken { //! MatcherTokenClass bits - fixed at tokenization, unaffected by later re-typing of the token uint8_t token_class = 0; + bool HasLiteralInfo(const GrammarLiteralTable &table) const { + return literal_table_id == table.CacheId(); + } + //! The tokenizer looks every token up once; later lookups against the same table hit this cache + void SetLiteralInfo(const GrammarLiteralTable &table, LiteralInfo info) { + literal_info = info; + literal_table_id = table.CacheId(); + } + //! Whether the literal info of this table is cached on the token LiteralInfo GetLiteralInfo(const GrammarLiteralTable &table) { if (literal_table_id != table.CacheId()) { - literal_info = table.Lookup(text); - literal_table_id = table.CacheId(); + RefreshLiteralInfo(table); } return literal_info; } + //! The table lookup on a cache miss, kept out of line so the lookahead tests that call GetLiteralInfo stay small + DUCKDB_API void RefreshLiteralInfo(const GrammarLiteralTable &table); void ResetLiteralInfo() { literal_table_id = 0; diff --git a/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp b/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp index ca3a9686c..425b12a92 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp @@ -438,6 +438,7 @@ enum class PEGRuleId : uint32_t { DescribeStatement, ShowExternalResources, ShowExternalResourcesType, + ShowExternalResourceTypes, ShowDeprecatedSelect, DescribeSelect, ShowAllTables, @@ -810,6 +811,9 @@ enum class PEGRuleId : uint32_t { RegisterExternalResourceStmt, DestroyExternalResourceStmt, ExternalResourceKeyword, + ExternalResourceType, + ExternalResourceTypeName, + BareName, ExternalResourceCreationOptions, AttachToExternalResource, ConnectToExternalResource, @@ -859,7 +863,7 @@ enum class PEGRuleId : uint32_t { CreateExtensionRepositoryFromHostStmt, DropExtensionRepositoryStmt, ExtensionRepositoryName, - ExtensionRepositoryHostName, + DottedName, TableMatchRecognizeClause, MatchRecognizeBody, MatchRecognizeClause, diff --git a/src/duckdb/src/include/duckdb/parser/peg/tokenizer/parser_tokenizer.hpp b/src/duckdb/src/include/duckdb/parser/peg/tokenizer/parser_tokenizer.hpp index 7b20d9ea6..0bde14b4e 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/tokenizer/parser_tokenizer.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/tokenizer/parser_tokenizer.hpp @@ -9,6 +9,8 @@ class ParserTokenizerBehavior : public TokenizerBehavior { ~ParserTokenizerBehavior() override = default; void PushToken(idx_t start, idx_t end, TokenType type, bool unterminated = false) override; + void PushWordToken(idx_t start, idx_t end, TokenType type, const GrammarLiteralTable &table, + LiteralInfo info) override; void OnStatementEnd(idx_t pos) override; void OnLastToken(const Tokenizer &tokenizer, TokenizeState state, string last_word, idx_t last_pos) override; diff --git a/src/duckdb/src/include/duckdb/parser/peg/tokenizer/tokenizer.hpp b/src/duckdb/src/include/duckdb/parser/peg/tokenizer/tokenizer.hpp index fd5c497c5..02cb88bcf 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/tokenizer/tokenizer.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/tokenizer/tokenizer.hpp @@ -8,6 +8,9 @@ #pragma once +#include "duckdb/common/array.hpp" +#include "duckdb/common/once_flag.hpp" +#include "duckdb/common/string_util.hpp" #include "duckdb/parser/peg/keyword_helper.hpp" #include "duckdb/parser/peg/token_type.hpp" #include "duckdb/parser/peg/matcher_token.hpp" @@ -28,6 +31,23 @@ enum class TokenizeState { class Tokenizer; +//! The first check of the STANDARD state that applies to a byte, in the order the checks are made +enum class StandardByteClass : uint8_t { + STRING_QUOTE, + QUOTED_IDENTIFIER, + SEMICOLON, + DOLLAR, + MINUS, + SLASH, + SPACE, + COLON, + SINGLE_BYTE_OPERATOR, + NUMBER, + SPECIAL_STRING_PREFIX, + OPERATOR, + WORD +}; + class TokenizerBehavior { public: explicit TokenizerBehavior(const string &sql); @@ -35,6 +55,9 @@ class TokenizerBehavior { public: virtual void PushToken(idx_t start, idx_t end, TokenType type, bool unterminated = false); + //! Push a keyword or an identifier that the tokenizer already looked up in the literal table + virtual void PushWordToken(idx_t start, idx_t end, TokenType type, const GrammarLiteralTable &table, + LiteralInfo info); virtual void OnStatementEnd(idx_t pos); virtual void OnLastToken(const Tokenizer &tokenizer, TokenizeState state, string last_word, idx_t last_pos); @@ -45,6 +68,36 @@ class TokenizerBehavior { return TokenType::END_OF_INPUT; } +protected: + //! Append the token of a non-empty input range, with what precedes it + MatcherToken &EmplaceToken(idx_t start, idx_t end, TokenType type, bool unterminated = false) { + D_ASSERT(start < end); + tokens.emplace_back(sql.data() + start, end - start, start, type, unterminated); + auto &token = tokens.back(); + MarkPrecedingTrivia(token); + return token; + } + +private: + //! Record on the token that was just pushed whether a newline or a block comment precedes it + void MarkPrecedingTrivia(MatcherToken &token) { + if (tokens.size() < 2) { + return; + } + auto &previous_token = tokens[tokens.size() - 2]; + auto previous_token_end = previous_token.offset + previous_token.length; + if (has_block_comment && last_block_comment_position >= previous_token_end && + last_block_comment_position < token.offset) { + token.preceded_by_block_comment = true; + } + for (idx_t pos = previous_token_end; pos < token.offset; pos++) { + if (StringUtil::CharacterIsNewline(sql[pos])) { + token.preceded_by_newline = true; + break; + } + } + } + public: const string &sql; vector tokens; @@ -65,6 +118,7 @@ class Tokenizer { virtual bool BackslashEscapesStringLiterals() const; virtual bool IsQuotedIdentifierDelimiter(char character) const; virtual void PushOperatorToken(TokenizerBehavior &behavior, idx_t start, idx_t end) const; + void PushWordToken(TokenizerBehavior &behavior, idx_t start, idx_t end) const; virtual void HandleLastToken(TokenizerBehavior &behavior, TokenizeState state, const string &sql, idx_t last_pos) const; @@ -75,6 +129,21 @@ class Tokenizer { //! (dirty) based on the return value. bool TokenizeInputInternal(TokenizerBehavior &behavior) const; bool IsCompoundColonToken(const string &sql, idx_t pos, idx_t &token_length) const; + //! Scan the word starting at position i and push it, or enter the KEYWORD state when the input ends in it + void TokenizeWord(TokenizerBehavior &behavior, const bool *is_word, idx_t &i, idx_t &last_pos, + TokenizeState &state) const; + + //! What the STANDARD state knows about each byte + struct ByteTables { + array standard_classes; + //! The token class of the operator token that consists of the byte alone + array operator_token_classes; + }; + //! Built on first use, since the quoted identifier delimiters are a virtual property of the tokenizer + const ByteTables &GetByteTables() const; + //! Push an operator token of one byte with its literal info + void PushSingleByteOperator(TokenizerBehavior &behavior, const ByteTables &byte_tables, + const GrammarLiteralTable &table, idx_t byte_position, idx_t offset) const; public: static bool IsSingleByteOperator(char c); @@ -91,6 +160,10 @@ class Tokenizer { public: const PEGKeywordHelper &keyword_helper; + +private: + mutable OnceFlag byte_tables_once; + mutable ByteTables byte_tables; }; } // namespace duckdb 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 7db569197..d03a1a86f 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 @@ -133,11 +133,11 @@ class ParseResult { template TARGET &Cast() { if (TARGET::TYPE != ParseResultType::INVALID && type != TARGET::TYPE) { - throw InternalException("Failed to cast parse result of type %s to type %s for rule %s", - ParseResultToString(TARGET::TYPE), ParseResultToString(type), Name()); + ThrowCastError(TARGET::TYPE); } return reinterpret_cast(*this); } + DUCKDB_API void ThrowCastError(ParseResultType target) const; optional_ptr rule; ParseResultType type; diff --git a/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp b/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp index 3f05977c0..224b90be1 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp @@ -1493,6 +1493,8 @@ class PEGTransformerFactory { GeneratedTransformProcess &process); static arena_ptr FinalizeShowExternalResourcesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr + FinalizeShowExternalResourceTypesTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeShowDeprecatedSelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDescribeSelectTrampoline(PEGTransformer &transformer, @@ -2099,6 +2101,12 @@ class PEGTransformerFactory { FinalizeRegisterExternalResourceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeDestroyExternalResourceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeExternalResourceTypeTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); + static arena_ptr + FinalizeExternalResourceTypeNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeBareNameTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static arena_ptr FinalizeAttachToExternalResourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr @@ -2173,8 +2181,6 @@ class PEGTransformerFactory { static arena_ptr FinalizeExtensionRepositoryNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr - FinalizeExtensionRepositoryHostNameTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); - static arena_ptr FinalizeTableMatchRecognizeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMatchRecognizeBodyTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); @@ -3346,7 +3352,9 @@ class PEGTransformerFactory { unique_ptr child); static unique_ptr TransformShowExternalResources(PEGTransformer &transformer, const ShowType &show_rule, const bool &has_result, - optional show_external_resources_type); + optional show_external_resources_type); + static unique_ptr TransformShowExternalResourceTypes(PEGTransformer &transformer, + const ShowType &show_rule); static unique_ptr TransformShowDeprecatedSelect(PEGTransformer &transformer, const ShowType &show_rule, unique_ptr select_statement_internal); static unique_ptr TransformDescribeSelect(PEGTransformer &transformer, @@ -3966,15 +3974,16 @@ class PEGTransformerFactory { static unique_ptr TransformExtractStringArgument(PEGTransformer &transformer, const string &string_literal); static unique_ptr - TransformCreateExternalResourceStmt(PEGTransformer &transformer, const string &string_literal, + TransformCreateExternalResourceStmt(PEGTransformer &transformer, const string &external_resource_type, const optional &attach_alias, const optional> &external_resource_creation_options); static unique_ptr TransformRegisterExternalResourceStmt(PEGTransformer &transformer, - const string &string_literal, + const string &external_resource_type, const optional &attach_alias, unique_ptr expression); static unique_ptr TransformDestroyExternalResourceStmt(PEGTransformer &transformer, const Identifier &col_id); + static string TransformExternalResourceTypeName(PEGTransformer &transformer, const Identifier &bare_name); static unique_ptr TransformAttachToExternalResource( PEGTransformer &transformer, unique_ptr external_resource_source, const Identifier &attach_alias, const optional> &attach_options); @@ -3983,7 +3992,7 @@ class PEGTransformerFactory { unique_ptr external_resource_source, const optional> &attach_options); static unique_ptr TransformExternalResourceCreateClause( - PEGTransformer &transformer, const string &string_literal, + PEGTransformer &transformer, const string &external_resource_type, const optional> &external_resource_creation_options); static unique_ptr TransformExternalResourceReferenceClause(PEGTransformer &transformer, const Identifier &col_id); @@ -4055,8 +4064,6 @@ class PEGTransformerFactory { static unique_ptr TransformDropExtensionRepositoryStmt(PEGTransformer &transformer, const optional &if_exists, const Identifier &col_id_or_string); - static Identifier TransformExtensionRepositoryHostName(PEGTransformer &transformer, const Identifier &col_id, - const vector &dot_col_label); static unique_ptr TransformTableMatchRecognizeClause(PEGTransformer &transformer, unique_ptr match_recognize_body, const optional &table_alias); diff --git a/src/duckdb/src/include/duckdb/parser/query_node.hpp b/src/duckdb/src/include/duckdb/parser/query_node.hpp index 1d9042a69..23e3d2b42 100644 --- a/src/duckdb/src/include/duckdb/parser/query_node.hpp +++ b/src/duckdb/src/include/duckdb/parser/query_node.hpp @@ -74,9 +74,6 @@ class QueryNode { string ResultModifiersToString() const; - //! Adds a distinct modifier to the query node - void AddDistinct(); - virtual void Serialize(Serializer &serializer) const; static unique_ptr Deserialize(Deserializer &deserializer); //! Throws a SerializationException if a deserialized query node does not have a valid shape diff --git a/src/duckdb/src/include/duckdb/parser/statement/list.hpp b/src/duckdb/src/include/duckdb/parser/statement/list.hpp index ef2bb5f57..b4b08a7b6 100644 --- a/src/duckdb/src/include/duckdb/parser/statement/list.hpp +++ b/src/duckdb/src/include/duckdb/parser/statement/list.hpp @@ -21,7 +21,6 @@ #include "duckdb/parser/statement/merge_into_statement.hpp" #include "duckdb/parser/statement/pragma_statement.hpp" #include "duckdb/parser/statement/prepare_statement.hpp" -#include "duckdb/parser/statement/relation_statement.hpp" #include "duckdb/parser/statement/select_statement.hpp" #include "duckdb/parser/statement/set_statement.hpp" #include "duckdb/parser/statement/transaction_statement.hpp" diff --git a/src/duckdb/src/include/duckdb/parser/statement/relation_statement.hpp b/src/duckdb/src/include/duckdb/parser/statement/relation_statement.hpp deleted file mode 100644 index 1c3c19e7e..000000000 --- a/src/duckdb/src/include/duckdb/parser/statement/relation_statement.hpp +++ /dev/null @@ -1,33 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/parser/statement/relation_statement.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/parser/sql_statement.hpp" - -namespace duckdb { -class Relation; - -class RelationStatement : public SQLStatement { -public: - static constexpr const StatementType TYPE = StatementType::RELATION_STATEMENT; - -public: - explicit RelationStatement(shared_ptr relation); - - shared_ptr relation; - -protected: - RelationStatement(const RelationStatement &other) = default; - -public: - unique_ptr Copy() const override; - string ToString() const override; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parser/tableref/delimgetref.hpp b/src/duckdb/src/include/duckdb/parser/tableref/delimgetref.hpp deleted file mode 100644 index 9d936b215..000000000 --- a/src/duckdb/src/include/duckdb/parser/tableref/delimgetref.hpp +++ /dev/null @@ -1,37 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/parser/tableref/delimgetref.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/identifier.hpp" -#include "duckdb/parser/tableref.hpp" - -namespace duckdb { - -class DelimGetRef : public TableRef { -public: - explicit DelimGetRef(const vector &types_p) : TableRef(TableReferenceType::DELIM_GET), types(types_p) { - for (idx_t i = 0; i < types.size(); i++) { - string column_name = "__internal_delim_get_" + std::to_string(i); - internal_aliases.emplace_back(column_name); - } - } - - vector internal_aliases; - vector types; - -public: - string ToString() const override; - bool Equals(const TableRef &other_p) const override; - - unique_ptr Copy() override; - - void Serialize(Serializer &serializer) const override; - static unique_ptr Deserialize(Deserializer &source); -}; -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parser/token_iterator.hpp b/src/duckdb/src/include/duckdb/parser/token_iterator.hpp index 39caea5d7..9a79c3b31 100644 --- a/src/duckdb/src/include/duckdb/parser/token_iterator.hpp +++ b/src/duckdb/src/include/duckdb/parser/token_iterator.hpp @@ -60,18 +60,60 @@ class TokenIterator { return tokens[position]; } LiteralInfo CurrentLiteralInfo(const GrammarLiteralTable &table) { - if (position >= tokens.size()) { + return PeekLiteralInfo(table, 0); + } + //! The token "ahead" positions after the current one, or nullptr past the end + optional_ptr Peek(idx_t ahead) const { + auto index = position + ahead; + if (index >= tokens.size()) { + return nullptr; + } + return tokens[index]; + } + LiteralInfo PeekLiteralInfo(const GrammarLiteralTable &table, idx_t ahead) { + auto index = position + ahead; + if (index >= tokens.size()) { return LiteralInfo(); } - return tokens[position].GetLiteralInfo(table); + return tokens[index].GetLiteralInfo(table); } DUCKDB_API const MatcherToken &Previous() const; - DUCKDB_API const MatcherToken &GetToken(idx_t index) const; + const MatcherToken &GetToken(idx_t index) const { + if (index >= tokens.size()) { + ThrowIndexError(index); + } + return tokens[index]; + } - DUCKDB_API void Advance(idx_t count = 1); - DUCKDB_API void SetPosition(idx_t position); - DUCKDB_API void SetPosition(const TokenIterator &other); - DUCKDB_API void SetPreviousTokenType(TokenType type); + void Advance(idx_t count = 1) { + if (count > tokens.size() - position) { + ThrowAdvanceError(count); + } + position += count; + } + void SetPosition(idx_t position_p) { + if (position_p > tokens.size()) { + ThrowPositionError(position_p); + } + position = position_p; + } + void SetPosition(const TokenIterator &other) { + if (&tokens != &other.tokens) { + ThrowCollectionError(); + } + SetPosition(other.position); + } + void SetPreviousTokenType(TokenType type) { + if (position == 0) { + ThrowNoPreviousError(); + } + tokens[position - 1].type = type; + } + DUCKDB_API void ThrowIndexError(idx_t index) const; + DUCKDB_API void ThrowAdvanceError(idx_t count) const; + DUCKDB_API void ThrowPositionError(idx_t position_p) const; + DUCKDB_API void ThrowCollectionError() const; + DUCKDB_API void ThrowNoPreviousError() const; DUCKDB_API vector RemainingTokens() const; DUCKDB_API string ToString() const; diff --git a/src/duckdb/src/include/duckdb/parser/tokens.hpp b/src/duckdb/src/include/duckdb/parser/tokens.hpp index b4bf1b454..f0462ff5a 100644 --- a/src/duckdb/src/include/duckdb/parser/tokens.hpp +++ b/src/duckdb/src/include/duckdb/parser/tokens.hpp @@ -38,7 +38,6 @@ class PragmaStatement; class ExplainStatement; class ExportStatement; class VacuumStatement; -class RelationStatement; class SetStatement; class SetVariableStatement; class ResetVariableStatement; diff --git a/src/duckdb/src/include/duckdb/planner/binder.hpp b/src/duckdb/src/include/duckdb/planner/binder.hpp index 2a52e56b5..35be6076f 100644 --- a/src/duckdb/src/include/duckdb/planner/binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/binder.hpp @@ -23,7 +23,6 @@ #include "duckdb/parser/query_node.hpp" #include "duckdb/parser/tableref/table_function_ref.hpp" #include "duckdb/parser/result_modifier.hpp" -#include "duckdb/parser/tableref/delimgetref.hpp" #include "duckdb/parser/tokens.hpp" #include "duckdb/planner/bind_context.hpp" #include "duckdb/planner/bound_statement.hpp" @@ -538,7 +537,6 @@ class Binder : public enable_shared_from_this { BoundStatement Bind(PragmaStatement &stmt); BoundStatement Bind(ExplainStatement &stmt); BoundStatement Bind(VacuumStatement &stmt); - BoundStatement Bind(RelationStatement &stmt); BoundStatement Bind(CallStatement &stmt); BoundStatement Bind(ExportStatement &stmt); BoundStatement Bind(ExtensionStatement &stmt); @@ -645,7 +643,6 @@ class Binder : public enable_shared_from_this { BoundStatement Bind(SubqueryRef &ref); BoundStatement Bind(TableFunctionRef &ref); BoundStatement Bind(EmptyTableRef &ref); - BoundStatement Bind(DelimGetRef &ref); BoundStatement Bind(ExpressionListRef &ref); BoundStatement Bind(ColumnDataRef &ref); BoundStatement Bind(PivotRef &expr); diff --git a/src/duckdb/src/include/duckdb/planner/collation_binding.hpp b/src/duckdb/src/include/duckdb/planner/collation_binding.hpp index 867397266..0a4d30469 100644 --- a/src/duckdb/src/include/duckdb/planner/collation_binding.hpp +++ b/src/duckdb/src/include/duckdb/planner/collation_binding.hpp @@ -10,16 +10,30 @@ #include "duckdb/function/cast/default_casts.hpp" #include "duckdb/common/enums/collation_type.hpp" +#include "duckdb/function/scalar_function.hpp" namespace duckdb { struct MapCastInfo; struct MapCastNode; struct DBConfig; +//! A scalar function applied to make a value byte-comparable, looked up in the system catalog +struct CollationFunctionName { + CollationFunctionName(Identifier schema_p, Identifier name_p) + : schema(std::move(schema_p)), name(std::move(name_p)) { + } + explicit CollationFunctionName(Identifier name_p) + : CollationFunctionName(Identifier::DefaultSchema(), std::move(name_p)) { + } + + Identifier schema; + Identifier name; +}; + //! Returns the (ordered) list of scalar functions that need to be applied to a value of the given type to make it //! byte-comparable under its collation. Returns an empty list if no collation needs to be applied. -typedef vector (*get_collation_functions_t)(ClientContext &context, const LogicalType &sql_type, - CollationType type); +typedef vector (*get_collation_functions_t)(ClientContext &context, const LogicalType &sql_type, + CollationType type); struct CollationCallback { explicit CollationCallback(get_collation_functions_t get_collation_functions_p) @@ -29,6 +43,31 @@ struct CollationCallback { get_collation_functions_t get_collation_functions; }; +struct CollationFunction { + //! The scalar function that maps a string to its sort key + CollationFunctionName function; + //! Whether the collation can be combined with other collations, e.g. nocase.noaccent + bool combinable; +}; + +//! A string collation "x" is the scalar function "x" in the "collations" schema of the system catalog: it takes a +//! VARCHAR and returns a VARCHAR or BLOB that is compared (and sorted) instead of the original string. +struct CollationFunctions { + //! The schema of the system catalog that holds the collation functions + static constexpr const char *SCHEMA = "collations"; + //! Boolean function property that marks a collation as combinable, an absent property means false + static constexpr const char *COMBINABLE_PROPERTY = "duckdb.collation.combinable"; + + //! The schema that holds the collation functions + DUCKDB_API static Identifier GetSchema(); + //! Marks the function as a collation function that can be combined with other collations + DUCKDB_API static void SetCombinable(ScalarFunction &function); + //! Looks up the function of a collation (autoloading its extension), throws if the collation does not exist + DUCKDB_API static CollationFunction Lookup(ClientContext &context, const string &collation); + //! The names of all registered collations + DUCKDB_API static vector GetCollations(ClientContext &context); +}; + class CollationBinding { public: CollationBinding(); diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_aggregate_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_aggregate_expression.hpp index 8abdcc33e..e129f7c8d 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_aggregate_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_aggregate_expression.hpp @@ -17,11 +17,12 @@ namespace duckdb { class BoundAggregateExpression : public Expression { public: static constexpr const ExpressionClass TYPE = ExpressionClass::BOUND_AGGREGATE; + //! Preserves the first argument's domain for singleton input when the second argument is non-NULL + static constexpr const char *NON_NULL_SELECTOR_DOMAIN_PROPERTY = "duckdb.aggregate.non_null_selector_domain"; public: BoundAggregateExpression(BoundAggregateFunction function, vector> children, - unique_ptr filter, unique_ptr bind_info, - AggregateType aggr_type); + unique_ptr filter, cow_ptr bind_info, AggregateType aggr_type); public: bool IsDistinct() const { @@ -40,10 +41,10 @@ class BoundAggregateExpression : public Expression { vector> &GetChildrenMutable() { return children; } - const unique_ptr &BindInfo() const { + const cow_ptr &BindInfo() const { return bind_info; } - unique_ptr &BindInfoMutable() { + cow_ptr &BindInfoMutable() { return bind_info; } AggregateType GetAggregateType() const { @@ -80,6 +81,7 @@ class BoundAggregateExpression : public Expression { bool IsVolatile() const override; bool CanThrow() const override; bool PropagatesNullValues() const override; + bool CanForwardSingletonInputDomain() const; string ToString() const override; @@ -96,7 +98,7 @@ class BoundAggregateExpression : public Expression { //! List of arguments to the function vector> children; //! The bound function data (if any) - unique_ptr bind_info; + cow_ptr bind_info; //! The aggregate type (distinct or non-distinct) AggregateType aggr_type; //! Whether or not we are exporting state in this aggregate diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp index 95c9e1e3b..77c6c3b9c 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_between_expression.hpp @@ -16,8 +16,9 @@ class BoundFunctionExpression; //! The BoundBetweenExpression has been moved to a function expression //! This class exists only as a set of helper methods struct BoundBetweenExpression { - static unique_ptr Create(unique_ptr input, unique_ptr lower, - unique_ptr upper, bool lower_inclusive, bool upper_inclusive); + static unique_ptr Create(ClientContext &context, unique_ptr input, + unique_ptr lower, unique_ptr upper, + bool lower_inclusive, bool upper_inclusive); static bool LowerInclusive(const BoundFunctionExpression &between_expr); static bool UpperInclusive(const BoundFunctionExpression &between_expr); diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_cast_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_cast_expression.hpp index e6aaa29e5..3076771e5 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_cast_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_cast_expression.hpp @@ -23,9 +23,6 @@ struct BoundCastExpression { //! Create a bound cast function expression around the given child using the provided bound cast static unique_ptr Create(unique_ptr child, const LogicalType &target_type, BoundCastInfo bound_cast, bool try_cast = false); - //! Create a bound cast function expression that is rebound using only the built-in SQL casts - static unique_ptr CreateDefault(unique_ptr child, const LogicalType &target_type, - BoundCastInfo bound_cast, bool try_cast = false); //! The expression that is being cast static const Expression &Child(const BoundFunctionExpression &cast_expr); @@ -38,8 +35,6 @@ struct BoundCastExpression { static bool IsTryCast(const BoundFunctionExpression &cast_expr); //! Whether the expression contains the bind data owned by the built-in cast implementation static bool HasValidBindData(const BoundFunctionExpression &cast_expr); - //! Whether or not this cast is bound using only the built-in SQL casts - static bool IsDefaultCast(const BoundFunctionExpression &cast_expr); static const BoundCastInfo &GetBoundCast(const BoundFunctionExpression &cast_expr); static BoundCastInfo &GetBoundCastMutable(BoundFunctionExpression &cast_expr); static unique_ptr PropagateStatistics(BoundFunctionExpression &cast_expr, @@ -58,8 +53,10 @@ struct BoundCastExpression { //! Returns true if a cast is invertible (i.e. CAST(s -> t -> s) = s for all values of s). This is not true for e.g. //! boolean casts, because that can be e.g. -1 -> TRUE -> 1. This is necessary to prevent some optimizer bugs. static bool CastIsInvertible(const LogicalType &source_type, const LogicalType &target_type); - //! Returns true if every value of the integral source type is exactly representable in the floating target type - static bool IsLosslessIntegralToFloatingCast(const LogicalType &source_type, const LogicalType &target_type); + //! Returns true if the cast is strictly increasing over all values of the numeric source type, e.g. INTEGER -> + //! DECIMAL(11,1), DECIMAL(5,2) -> DOUBLE or FLOAT -> DOUBLE. A range comparison of the cast with a constant can + //! then be applied to the source values. + static bool CastIsOrderPreserving(const LogicalType &source_type, const LogicalType &target_type); //! Returns true if CAST(s -> t -> s) = s for all values of s, possibly without preserving their order (e.g. INTEGER //! -> VARCHAR). An (in)equality comparison of the cast with a constant can then be applied to the source values. static bool CastIsInvertibleForEquality(const LogicalType &source_type, const LogicalType &target_type); diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_comparison_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_comparison_expression.hpp index 03021b19a..60f627cc7 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_comparison_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_comparison_expression.hpp @@ -19,6 +19,9 @@ struct BoundComparisonExpression { static bool IsComparison(ExpressionType type); static bool IsComparison(const Expression &expr); + //! Whether equal, already-bound operands of this type have interchangeable value representations. + static bool EqualityPreservesValueRepresentation(const LogicalType &type); + static const Expression &Left(const BoundFunctionExpression &comparison_expr); static const Expression &Right(const BoundFunctionExpression &comparison_expr); @@ -26,6 +29,10 @@ struct BoundComparisonExpression { static unique_ptr &RightMutable(BoundFunctionExpression &between_expr); static unique_ptr Create(ExpressionType type, unique_ptr left, unique_ptr right); + //! Create the comparison "#left_idx #right_idx" of two input columns, without casts + static unique_ptr CreateOnColumns(ClientContext &context, ExpressionType type, + const LogicalType &left_type, idx_t left_idx, + const LogicalType &right_type, idx_t right_idx); //! Create a comparison, casting both sides to a common type within the limit of the binder, if any - throws if //! they cannot be compared static unique_ptr Bind(ClientContext &context, ExpressionType type, unique_ptr left, diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_function_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_function_expression.hpp index f208ebbab..2ef4862ef 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_function_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_function_expression.hpp @@ -21,8 +21,8 @@ class BoundFunctionExpression : public Expression { public: BoundFunctionExpression(BoundScalarFunction bound_function, vector> arguments, - unique_ptr bind_info, bool is_operator = false, - Identifier alias = Identifier(), QueryLocation location = QueryLocation()); + cow_ptr bind_info, bool is_operator = false, Identifier alias = Identifier(), + QueryLocation location = QueryLocation()); public: const BoundScalarFunction &Function() const { @@ -37,10 +37,10 @@ class BoundFunctionExpression : public Expression { vector> &GetChildrenMutable() { return children; } - const unique_ptr &BindInfo() const { + const cow_ptr &BindInfo() const { return bind_info; } - unique_ptr &BindInfoMutable() { + cow_ptr &BindInfoMutable() { return bind_info; } bool IsOperator() const { @@ -70,7 +70,7 @@ class BoundFunctionExpression : public Expression { private: static ExpressionType GetFunctionExpressionType(const BoundScalarFunction &bound_function, const vector> &arguments, - optional_ptr bind_info); + optional_ptr bind_info); private: //! The bound function expression @@ -78,7 +78,7 @@ class BoundFunctionExpression : public Expression { //! List of child-expressions of the function vector> children; //! The bound function data (if any) - unique_ptr bind_info; + cow_ptr bind_info; //! Whether or not the function is an operator, only used for rendering bool is_operator; }; diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_window_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_window_expression.hpp index a395c81f7..d58606f5f 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_window_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_window_expression.hpp @@ -26,7 +26,7 @@ class BoundWindowExpression : public Expression { public: BoundWindowExpression(LogicalType return_type, unique_ptr aggregate, - unique_ptr window, unique_ptr bind_info); + unique_ptr window, cow_ptr bind_info); public: const unique_ptr &AggregateFunction() const { @@ -41,10 +41,10 @@ class BoundWindowExpression : public Expression { unique_ptr &WindowFunctionMutable() { return window; } - const unique_ptr &BindInfo() const { + const cow_ptr &BindInfo() const { return bind_info; } - unique_ptr &BindInfoMutable() { + cow_ptr &BindInfoMutable() { return bind_info; } const vector> &GetChildren() const { @@ -197,7 +197,7 @@ class BoundWindowExpression : public Expression { //! The bound window function unique_ptr window; //! The bound function info - unique_ptr bind_info; + cow_ptr bind_info; //! The child expressions of the main window function vector> children; //! The set of expressions to partition by diff --git a/src/duckdb/src/include/duckdb/planner/expression/legacy_bound_between_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/legacy_bound_between_expression.hpp index e42e2c2d8..5309dea96 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/legacy_bound_between_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/legacy_bound_between_expression.hpp @@ -26,7 +26,7 @@ class LegacyBoundBetweenExpression : public Expression { void Serialize(Serializer &serializer) const override; static unique_ptr Deserialize(Deserializer &deserializer); - static unique_ptr DeserializeLegacyExpression(unique_ptr input, + static unique_ptr DeserializeLegacyExpression(ClientContext &context, unique_ptr input, unique_ptr lower, unique_ptr upper, bool lower_inclusive, bool upper_inclusive); diff --git a/src/duckdb/src/include/duckdb/planner/expression/window_range_info.hpp b/src/duckdb/src/include/duckdb/planner/expression/window_range_info.hpp index 7efff37f6..74a14f349 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/window_range_info.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/window_range_info.hpp @@ -21,7 +21,6 @@ struct WindowRangeCast { LogicalType source_type; LogicalType target_type; bool try_cast; - bool default_cast; void Serialize(Serializer &serializer) const; static WindowRangeCast Deserialize(Deserializer &deserializer); diff --git a/src/duckdb/src/include/duckdb/planner/expression_binder/relation_binder.hpp b/src/duckdb/src/include/duckdb/planner/expression_binder/relation_binder.hpp index ebf44990c..f20c3f092 100644 --- a/src/duckdb/src/include/duckdb/planner/expression_binder/relation_binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression_binder/relation_binder.hpp @@ -12,7 +12,7 @@ namespace duckdb { -//! The relation binder is a binder used to bind expressions in the relation API +//! The relation binder binds expressions that may not contain aggregates, DEFAULT, subqueries or window functions class RelationBinder : public ExpressionBinder { public: RelationBinder(Binder &binder, ClientContext &context, string op); diff --git a/src/duckdb/src/include/duckdb/planner/expression_nullability.hpp b/src/duckdb/src/include/duckdb/planner/expression_nullability.hpp index 8cbe1191c..b8cb245d4 100644 --- a/src/duckdb/src/include/duckdb/planner/expression_nullability.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression_nullability.hpp @@ -32,7 +32,9 @@ bool FilterRejectsNull(const Expression &filter, const Expression &expr); //! Conservatively proves that an expression cannot be NULL at a logical operator's output. class NotNullExpressionAnalyzer { public: - explicit NotNullExpressionAnalyzer(ClientContext &context, optional_ptr plan_root = nullptr); + //! Requires the complete plan; keep its root alive while calling IsNotNull. + //! Rewrites must not introduce DML CTEs during analysis. + NotNullExpressionAnalyzer(ClientContext &context, LogicalOperator &plan_root); bool IsNotNull(LogicalOperator &op, const Expression &expr); @@ -42,7 +44,8 @@ class NotNullExpressionAnalyzer { private: ClientContext &context; - optional_ptr plan_root; + LogicalOperator &plan_root; + bool has_dml_cte; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp b/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp index 5a0c7acb6..36a755e22 100644 --- a/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp +++ b/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp @@ -21,6 +21,7 @@ struct DynamicFilterData; class BoundFunctionExpression; class ClientContext; +enum class SelectivityOptionalFilterType : uint8_t; class ExpressionFilter : public TableFilter { public: @@ -52,6 +53,9 @@ class ExpressionFilter : public TableFilter { ExpressionType expression_type); //! Build a single-column filter comparing against a constant. static unique_ptr CreateComparisonFilter(ExpressionType comparison_type, Value constant); + static unique_ptr CreateSelectivityOptionalFilter(unique_ptr child_expr, + const LogicalType &column_type, + SelectivityOptionalFilterType type); static bool IsSimpleFilterColumnRef(const Expression &expr); //! Flips comparison_type for a constant on the left static optional_ptr diff --git a/src/duckdb/src/include/duckdb/planner/filter/table_filter_function_helpers.hpp b/src/duckdb/src/include/duckdb/planner/filter/table_filter_function_helpers.hpp index 6efc144c9..95479f1b9 100644 --- a/src/duckdb/src/include/duckdb/planner/filter/table_filter_function_helpers.hpp +++ b/src/duckdb/src/include/duckdb/planner/filter/table_filter_function_helpers.hpp @@ -167,7 +167,7 @@ inline void ExecuteWithSelectivityTracking(DataChunk &args, Vector &result, TRAC } } -void TableFilterFunctionSerialize(Serializer &serializer, const optional_ptr bind_data, +void TableFilterFunctionSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function); unique_ptr TableFilterFunctionDeserialize(Deserializer &deserializer, BoundScalarFunction &function); diff --git a/src/duckdb/src/include/duckdb/planner/filter/table_filter_functions.hpp b/src/duckdb/src/include/duckdb/planner/filter/table_filter_functions.hpp index 91b060325..958574cf3 100644 --- a/src/duckdb/src/include/duckdb/planner/filter/table_filter_functions.hpp +++ b/src/duckdb/src/include/duckdb/planner/filter/table_filter_functions.hpp @@ -61,7 +61,7 @@ struct SelectivityOptionalFilterState final : public TableFilterState { } }; -enum class SelectivityOptionalFilterType : uint8_t { MIN_MAX = 0, BF = 1, PRF = 3 }; +enum class SelectivityOptionalFilterType : uint8_t { MIN_MAX = 0, BF = 1, PRF = 3, IN_FILTER = 4 }; void GetThresholdAndVectorsToCheck(SelectivityOptionalFilterType type, float &selectivity_threshold, idx_t &n_vectors_to_check); @@ -93,10 +93,30 @@ struct TableFilterFunctions { //! describes a complete key set, so only a sealed filter may be looked up or handed to a scan. class BloomFilter { public: - BloomFilter() = default; + class ReadView { + public: + ReadView(const uint64_t *buffer, uint64_t bitmask) : buffer(buffer), bitmask(bitmask) { + } + + bool LookupOne(hash_t hash) const; + idx_t LookupHashes(const Vector &hashes, SelectionVector &result, idx_t count) const; + idx_t LookupHashes(const Vector &hashes, const SelectionVector &sel, SelectionVector &result, + idx_t count) const; + + private: + const uint64_t *buffer; + uint64_t bitmask; + }; + + //! Deferred buffers must be cleared through InitializeRange before inserting any keys. + enum class Initialization { IMMEDIATE, DEFERRED }; + //! Cap the bitmap size without reducing its desired bits per key. void Initialize(ClientContext &context_p, idx_t number_of_rows, - idx_t max_bitmap_bytes = NumericLimits::Maximum()); + idx_t max_bitmap_bytes = NumericLimits::Maximum(), + Initialization initialization = Initialization::IMMEDIATE); + //! Deferred initialization must cover disjoint ranges of [0,total) before insertion begins. + void InitializeRange(idx_t begin, idx_t end, idx_t total); //! VectorOperations::Hash writes at the source row positions, so the hashes to insert are the ones sel //! points at rather than the first count entries @@ -110,10 +130,26 @@ class BloomFilter { void InsertOne(hash_t hash); bool LookupOne(hash_t hash) const; - //! Folds the filter down to the smallest size that still meets the target false positive rate, releases the - //! memory that folding freed up, and marks the filter complete. + //! Folds the filter down to the smallest size that still meets the target false positive rate, releases excess + //! spare capacity, and marks the filter complete. void Seal(ClientContext &context); + idx_t GetBitmapSize() const { + return num_sectors * sizeof(uint64_t); + } + idx_t GetAllocationSize() const { + return buf_.GetSize(); + } + idx_t GetMemoryBudget() const { + return memory_budget; + } + //! Completed buffers may be replaced only before publication. + HugeAllocation CopyBuffer(ClientContext &context) const; + void ReplaceBuffer(HugeAllocation buffer); + void InstallReadCopy(HugeAllocation buffer); + ReadView GetReadView(idx_t buffer_index = 0) const; + + //! Allocation and geometry are configured; only a sealed filter is ready for lookup. bool IsInitialized() const { return initialized; } @@ -130,6 +166,7 @@ class BloomFilter { } //! Marks the filter as handed to a probe-side consumer: it must stay immutable afterwards void MarkPublished() { + D_ASSERT(initialized && sealed); published = true; } @@ -145,26 +182,37 @@ class BloomFilter { private: idx_t num_sectors; - //! Sector capacity of buf_, so an unpublished filter can be reused across recursive iterations - idx_t allocated_sectors = 0; + idx_t memory_budget = 0; uint64_t bitmask; // num_sectors - 1 -> used to get the sector offset bool initialized = false; bool sealed = false; bool useful = false; bool published = false; - AllocatedData buf_; + Initialization initialization = Initialization::IMMEDIATE; + HugeAllocation buf_; uint64_t *bf; + HugeAllocation read_copy; +}; + +//! Captured by the producer; a missing group selects the primary buffer. +struct BloomFilterReadLocality { + idx_t shard_count = 1; + optional_idx replica_group; }; +BloomFilter::ReadView GetBloomFilterReadView(const BloomFilter &filter, const BloomFilterReadLocality &locality); + //! FunctionData for bloom filter internal function struct BloomFilterFunctionData : public FunctionData { BloomFilterFunctionData(shared_ptr filter_p, bool filters_null_values_p, const string &key_column_name_p, const LogicalType &key_type_p, - float selectivity_threshold_p, idx_t n_vectors_to_check_p); + float selectivity_threshold_p, idx_t n_vectors_to_check_p, + BloomFilterReadLocality locality_p = {}); //! Published filters are shared and immutable: the hash table may drop its own reference at any time shared_ptr filter; + BloomFilterReadLocality locality; bool filters_null_values; string key_column_name; LogicalType key_type; @@ -198,7 +246,8 @@ class PrefixRangeFilter { virtual unique_ptr InitializeBuildState(ClientContext &context) const = 0; virtual void InsertKeys(Vector &keys, BuildState &state) const = 0; virtual void InsertKeysParallel(Vector &keys, BuildState &state) const = 0; - virtual void MergeBuildState(BuildState &state) = 0; + //! Consumes a completed state after all writers have finished. + virtual void MergeBuildState(unique_ptr state) = 0; virtual idx_t GetBuildStateSize() const = 0; virtual idx_t LookupKeys(Vector &keys, SelectionVector &result_sel, idx_t count) const = 0; //! result_sel contains local positions into sel rather than source row ids. @@ -206,9 +255,19 @@ class PrefixRangeFilter { idx_t count) const = 0; virtual FilterPropagateResult LookupRange(const Value &lower_bound, const Value &upper_bound) const = 0; virtual bool IsInitialized() const = 0; + bool IsPublished() const { + return published; + } + void MarkPublished() { + D_ASSERT(IsInitialized()); + published = true; + } static bool SupportedType(const LogicalType &type); static unique_ptr CreatePrefixRangeFilter(const LogicalType &key_type); static bool TryComputeSpan(const Value &lower_bound, const Value &upper_bound, uhugeint_t &result); + +private: + bool published = false; }; //! FunctionData for prefix range internal function diff --git a/src/duckdb/src/include/duckdb/planner/logical_operator.hpp b/src/duckdb/src/include/duckdb/planner/logical_operator.hpp index e4c9973d2..fbfe46237 100644 --- a/src/duckdb/src/include/duckdb/planner/logical_operator.hpp +++ b/src/duckdb/src/include/duckdb/planner/logical_operator.hpp @@ -71,6 +71,8 @@ class LogicalOperator { //! Returns true if this operator or any of its descendants has side effects //! Used to prevent inlining or elimination of side-effecting CTEs. bool HasSideEffects() const; + //! Returns true if a CTE body contains a data-modifying operator. + bool CTEContainsDML() const; //! Returns true if this operator or any of its descendants contains a volatile expression bool HasVolatileExpressions() const; diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_aggregate.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_aggregate.hpp index cedaa4c11..2c9ca1e48 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_aggregate.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_aggregate.hpp @@ -58,7 +58,17 @@ class LogicalAggregate : public LogicalOperator { vector GetTableIndex() const override; string GetName() const override; + //! Whether the result is the same over the input with or without repeated rows: every aggregate is DISTINCT, or + //! a function that neither depends on how often a value occurs nor on the order of its input (min, max, bool_and, + //! bool_or, ...), nothing is volatile and no aggregate state is exported + bool IgnoresDuplicates() const; + const Expression &GetExpression(ColumnBinding binding) const; + + //! Whether the rows of `op` are unique in the columns `keys`: the keys are traced through projections and filters + //! to an aggregate with one full grouping set whose groups are all among the keys (or to an aggregate without + //! groups, which emits one row). + static bool KeysAreUnique(LogicalOperator &op, vector keys); const Expression &GetGroupExpression(ProjectionIndex group_index) const; protected: diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_comparison_join.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_comparison_join.hpp index 4a2f03bd3..1b1b1a1af 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_comparison_join.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_comparison_join.hpp @@ -34,8 +34,6 @@ class LogicalComparisonJoin : public LogicalJoin { vector> duplicate_eliminated_columns; //! If this is a DelimJoin, whether it has been flipped to de-duplicating the RHS instead bool delim_flipped = false; - //! (If join_type == MARK) can this comparison join be converted from a mark join to semi - bool convert_mark_to_semi = true; //! Scans where we should push generated filters into (if any) unique_ptr filter_pushdown; diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_copy_to_file.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_copy_to_file.hpp index a334871cc..1906a2257 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_copy_to_file.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_copy_to_file.hpp @@ -24,7 +24,7 @@ class LogicalCopyToFile : public LogicalOperator { static constexpr const LogicalOperatorType TYPE = LogicalOperatorType::LOGICAL_COPY_TO_FILE; public: - LogicalCopyToFile(CopyFunction function, unique_ptr bind_data, unique_ptr copy_info, + LogicalCopyToFile(CopyFunction function, cow_ptr bind_data, unique_ptr copy_info, TableIndex table_index) : LogicalOperator(LogicalOperatorType::LOGICAL_COPY_TO_FILE), function(std::move(function)), bind_data(std::move(bind_data)), copy_info(std::move(copy_info)), table_index(table_index) { @@ -32,7 +32,7 @@ class LogicalCopyToFile : public LogicalOperator { public: CopyFunction function; - unique_ptr bind_data; + cow_ptr bind_data; unique_ptr copy_info; TableIndex table_index; diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_get.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_get.hpp index 8fc063528..8e9065dc3 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_get.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_get.hpp @@ -31,7 +31,7 @@ class LogicalGet : public LogicalOperator { static constexpr const LogicalOperatorType TYPE = LogicalOperatorType::LOGICAL_GET; public: - LogicalGet(TableIndex table_index, BoundTableFunction function, unique_ptr bind_data, + LogicalGet(TableIndex table_index, BoundTableFunction function, cow_ptr bind_data, vector returned_types, vector returned_names, virtual_column_map_t virtual_columns = virtual_column_map_t()); @@ -40,7 +40,7 @@ class LogicalGet : public LogicalOperator { //! The function that is called, together with the argument types this call was bound with BoundTableFunction function; //! The bind data of the function - unique_ptr bind_data; + cow_ptr bind_data; //! Process-local input that cannot be reconstructed from SQL parameters shared_ptr bind_info; //! The types of ALL columns that can be returned by the table function diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_set_operation.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_set_operation.hpp index 342a8c6aa..eeeba1733 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_set_operation.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_set_operation.hpp @@ -9,8 +9,10 @@ #pragma once #include "duckdb/planner/logical_operator.hpp" +#include "duckdb/planner/joinside.hpp" namespace duckdb { +class Binder; class LogicalSetOperation : public LogicalOperator { LogicalSetOperation(TableIndex table_index, idx_t column_count, LogicalOperatorType type, bool setop_all, @@ -34,12 +36,36 @@ class LogicalSetOperation : public LogicalOperator { bool setop_all; //! Whether or not UNION statements can be executed out of order bool allow_out_of_order; + //! EXCEPT / INTERSECT: the types the binder resolved for the columns. The columns are compared as these types, + //! that is under their collations. The children do not tell: a UNION child has the types of its first child, and + //! a cast to VARCHAR does not carry a collation + vector comparison_types; + //! EXCEPT / INTERSECT: how many of the last columns are the correlated columns of a subquery that the set operation + //! is part of (FlattenDependentJoins appends them). They are compared as they are, under no collation: the join + //! with the outer query compares them so, and a collation would mix the rows of outer values it treats as equal + idx_t correlated_column_count = 0; public: vector GetColumnBindings() override { return GenerateColumnBindings(table_index, column_count); } + //! The types the columns of an EXCEPT / INTERSECT are compared as: comparison_types, or for a set operation that + //! was not planned by the binder what the children say (a collation of either child applies) + vector GetComparisonTypes(ClientContext &context); + //! How an EXCEPT / INTERSECT compares the columns of its children: IS NOT DISTINCT FROM (NULLs are equal) on every + //! column, under its collation except for the correlated columns. These are the conditions of the join CreateJoin + //! builds, without the row numbers. + vector GetComparisons(ClientContext &context); + //! Plans EXCEPT as an ANTI join and INTERSECT as a SEMI join on all columns. With setop_all both children get a + //! row_number() over all columns that is compared as well, so that the n-th copies of a row match each other. + //! The last correlated_column_count columns are compared as they are, the others under their collations. + //! The result is a projection of the left columns with the table index of the set operation. + static unique_ptr CreateJoin(Binder &binder, const vector &types, + TableIndex setop_index, LogicalOperatorType type, bool setop_all, + unique_ptr left, unique_ptr right, + idx_t correlated_column_count = 0); + void Serialize(Serializer &serializer) const override; static unique_ptr Deserialize(Deserializer &deserializer); diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_window.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_window.hpp index 2f73c5245..3a14dcccf 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_window.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_window.hpp @@ -22,12 +22,16 @@ class LogicalWindow : public LogicalOperator { static constexpr const LogicalOperatorType TYPE = LogicalOperatorType::LOGICAL_WINDOW; public: - explicit LogicalWindow(TableIndex window_index) - : LogicalOperator(LogicalOperatorType::LOGICAL_WINDOW), window_index(window_index) { + LogicalWindow(TableIndex window_index, optional_idx partition_limit) + : LogicalOperator(LogicalOperatorType::LOGICAL_WINDOW), window_index(window_index), + partition_limit(partition_limit) { } TableIndex window_index; + //! The maximum number of rows to return per partition + optional_idx partition_limit; + public: vector GetColumnBindings() override; diff --git a/src/duckdb/src/include/duckdb/planner/subquery/has_volatile_expressions.hpp b/src/duckdb/src/include/duckdb/planner/subquery/has_volatile_expressions.hpp new file mode 100644 index 000000000..3bd517b1a --- /dev/null +++ b/src/duckdb/src/include/duckdb/planner/subquery/has_volatile_expressions.hpp @@ -0,0 +1,16 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/planner/subquery/has_volatile_expressions.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +namespace duckdb { +class LogicalOperator; + +//! Check subquery volatility, excluding the built-in error() but including its arguments. +bool HasVolatileExpressionsIgnoringError(const LogicalOperator &op); + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/table_filter_state.hpp b/src/duckdb/src/include/duckdb/planner/table_filter_state.hpp index f3328b8b4..4ea34e733 100644 --- a/src/duckdb/src/include/duckdb/planner/table_filter_state.hpp +++ b/src/duckdb/src/include/duckdb/planner/table_filter_state.hpp @@ -10,31 +10,82 @@ #include "duckdb/planner/table_filter.hpp" #include "duckdb/execution/expression_executor.hpp" +#include "duckdb/common/shared_ptr.hpp" +#include "duckdb/common/optional.hpp" namespace duckdb { struct SelectionVector; class Vector; +struct TableFilterState; + +struct TableFilterCacheIdentity { + bool valid = true; +}; + +class TableFilterCache { +public: + virtual ~TableFilterCache() = default; + + bool IsValidFor(const TableFilterState &state) const; + void Filter(const SelectionVector &value_indices, SelectionVector &sel, idx_t &count); + void FilterConstant(idx_t value_index, idx_t &count); + //! Selection indexes runs; row_counts supplies the logical row weight of each run. + void FilterRuns(const SelectionVector &value_indices, array_ptr row_counts, SelectionVector &sel, + idx_t &count); + bool CanSkipAll() const; + //! Whether this batch can be filtered without reading value indices. Does not advance adaptive feedback. + bool CanAcceptAll() const; + //! Borrow a pure root mask while the cache and its filter state remain alive. + optional> GetPureMask() const; + +protected: + virtual optional> GetPureMaskInternal() const { + return {}; + } + virtual bool CanAcceptAllInternal() const { + return false; + } + virtual bool CanSkipAllInternal() const { + return false; + } + virtual void FilterInternal(const SelectionVector &value_indices, SelectionVector &sel, idx_t &count) = 0; + virtual void FilterConstantInternal(idx_t value_index, idx_t &count) = 0; + virtual void FilterRunsInternal(const SelectionVector &value_indices, array_ptr row_counts, + SelectionVector &sel, idx_t &count) = 0; + +private: + friend struct TableFilterState; + shared_ptr identity; +}; struct ExpressionFilterExecutor { virtual ~ExpressionFilterExecutor() = default; + static unique_ptr TryCreate(const Expression &expression); + virtual idx_t FilterSelection(SelectionVector &sel, Vector &vector, idx_t scan_count, idx_t &approved_tuple_count) = 0; + virtual bool CanCache() const { + return false; + } + virtual unique_ptr CreateCache(Vector &values, idx_t count); }; //! Thread-local state for executing a table filter struct TableFilterState { public: - virtual ~TableFilterState() = default; + TableFilterState() = default; + TableFilterState(const TableFilterState &) = delete; + TableFilterState &operator=(const TableFilterState &) = delete; + virtual ~TableFilterState(); public: static unique_ptr Initialize(ClientContext &context, const TableFilter &filter); + unique_ptr CreateCache(Vector &values, idx_t count); - //! Whether evaluating the filter can throw. Such a filter must only ever be evaluated on the rows that are still - //! selected - evaluating it on the distinct values of a segment (a dictionary, the RLE runs) would raise errors - //! for rows that another filter already removed - bool can_throw = false; + //! Whether a pure cache plan is available for this filter. + bool can_cache = false; public: template @@ -47,6 +98,10 @@ struct TableFilterState { DynamicCastCheck(this); return reinterpret_cast(*this); } + +private: + friend class TableFilterCache; + shared_ptr cache_identity; }; struct ExpressionFilterState : public TableFilterState { @@ -61,6 +116,7 @@ struct ExpressionFilterState : public TableFilterState { unique_ptr executor; unique_ptr fast_executor; + bool can_cache_result = false; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/tableref/bound_joinref.hpp b/src/duckdb/src/include/duckdb/planner/tableref/bound_joinref.hpp index cfac7e02c..3dafbaf10 100644 --- a/src/duckdb/src/include/duckdb/planner/tableref/bound_joinref.hpp +++ b/src/duckdb/src/include/duckdb/planner/tableref/bound_joinref.hpp @@ -43,7 +43,7 @@ class BoundJoinRef { bool lateral; //! The correlated columns of the right-side with the left-side CorrelatedColumns correlated_columns; - //! The mark index, for mark joins generated by the relational API + //! The mark index, for a join ref whose join type is MARK TableIndex mark_index; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/arena_allocator.hpp b/src/duckdb/src/include/duckdb/storage/arena_allocator.hpp index 80bea9939..d0ba322a3 100644 --- a/src/duckdb/src/include/duckdb/storage/arena_allocator.hpp +++ b/src/duckdb/src/include/duckdb/storage/arena_allocator.hpp @@ -83,11 +83,18 @@ class ArenaAllocator { //! Equal sizes return the source unchanged. DUCKDB_API data_ptr_t Reallocate(data_ptr_t pointer, idx_t old_size, idx_t size); - DUCKDB_API data_ptr_t AllocateAligned(idx_t size); + data_ptr_t AllocateAligned(idx_t size) { + AlignNext(); + return Allocate(AlignValue(size)); + } DUCKDB_API data_ptr_t ReallocateAligned(data_ptr_t pointer, idx_t old_size, idx_t size); //! Increment the internal cursor (if required) so the next allocation is guaranteed to be aligned to 8 bytes - DUCKDB_API void AlignNext(); + void AlignNext() { + if (head && !ValueIsAligned(head->current_position)) { + head->current_position = AlignValue(head->current_position); + } + } //! This shrinks the LAST allocation that was made using the allocator //! Note that we can ONLY safely call this method if Allocate has been called previously with a size >= shrink_size @@ -102,9 +109,24 @@ class ArenaAllocator { idx_t current_position = 0; }; //! Returns the current position of the arena - DUCKDB_API Position GetPosition() const; + Position GetPosition() const { + Position result; + if (head) { + result.chunk = head.get(); + result.current_position = head->current_position; + } + return result; + } //! Releases everything that was allocated after the position was taken - those allocations may no longer be used - DUCKDB_API void Rewind(const Position &position); + void Rewind(const Position &position) { + if (position.chunk && head.get() == position.chunk) { + // the common case: nothing but the current chunk was used since the position was taken + D_ASSERT(position.current_position <= head->current_position); + head->ResetPosition(position.current_position); + return; + } + RewindSlow(position); + } //! Resets the current head and destroys all previous arena chunks DUCKDB_API void Reset(); @@ -133,18 +155,18 @@ class ArenaAllocator { } template - T *Make(ARGS &&... args) { + T *Make(ARGS &&...args) { auto mem = AllocateAligned(sizeof(T)); return new (mem) T(std::forward(args)...); } template - arena_ptr MakePtr(ARGS &&... args) { + arena_ptr MakePtr(ARGS &&...args) { return arena_ptr(Make(std::forward(args)...)); } template - unsafe_arena_ptr MakeUnsafePtr(ARGS &&... args) { + unsafe_arena_ptr MakeUnsafePtr(ARGS &&...args) { return unsafe_arena_ptr(Make(std::forward(args)...)); } @@ -168,7 +190,9 @@ class ArenaAllocator { } private: - void AllocateNewBlock(idx_t min_size); + DUCKDB_API void AllocateNewBlock(idx_t min_size); + //! Rewind to a position in an older chunk, or to the position of an arena that was empty + DUCKDB_API void RewindSlow(const Position &position); private: //! Internal allocator that is used by the arena allocator diff --git a/src/duckdb/src/include/duckdb/storage/block_allocator.hpp b/src/duckdb/src/include/duckdb/storage/block_allocator.hpp index 5cac17bae..d145548d4 100644 --- a/src/duckdb/src/include/duckdb/storage/block_allocator.hpp +++ b/src/duckdb/src/include/duckdb/storage/block_allocator.hpp @@ -29,6 +29,31 @@ class TaskScheduler; struct ProducerToken; struct BlockQueue; struct BlockAllocatorLifetimeState; +class BlockAllocator; +class BlockAllocatorThreadLocalState; + +//! The block cache of a worker thread. While it is initialized, the thread allocates through it instead of through the +//! thread_local cache, whose first use registers a destructor that glibc cannot fail to allocate without ending the +//! process +class BlockAllocatorWorkerState { +public: + BlockAllocatorWorkerState(); + ~BlockAllocatorWorkerState(); + BlockAllocatorWorkerState(const BlockAllocatorWorkerState &) = delete; + BlockAllocatorWorkerState &operator=(const BlockAllocatorWorkerState &) = delete; + BlockAllocatorWorkerState(BlockAllocatorWorkerState &&) = delete; + BlockAllocatorWorkerState &operator=(BlockAllocatorWorkerState &&) = delete; + +public: + bool IsInitialized() const; + //! Create the cache, this allocates + void Initialize(const BlockAllocator &block_allocator); + +private: + unique_ptr state; + //! The state the thread allocated through before, restored when this one goes away + optional_ptr previous; +}; class BlockAllocator { friend class BlockAllocatorThreadLocalState; @@ -57,6 +82,16 @@ class BlockAllocator { //! Free backing retained in global queues, thread-local caches, and ongoing reclamation. idx_t GetCachedMemory() const; + //! Approximate locality of fixed-pool backing, unknown for other allocations + optional_idx GetAllocationShard(const_data_ptr_t pointer) const; + idx_t GetPoolShardCount() const; + idx_t GetLocalPoolShard() const; + idx_t GetFallbackShardCount() const; + //! Approximate cache locality by grouping adjacent CPUs in fours, wrapping at shard_count. + static idx_t GetLocalShard(idx_t shard_count); + static idx_t GetShardGroup(idx_t shard, idx_t shard_count); + static idx_t GetLocalShardGroup(idx_t shard_count); + //! Flush outstanding allocations bool SupportsFlush() const; optional_idx DecayDelay() const; @@ -79,8 +114,10 @@ class BlockAllocator { BlockAllocator(Allocator &allocator, idx_t block_size, idx_t pool_size, idx_t shard_count); //! The buffer allocator's huge-page backend keeps matching allocation and release ownership. - data_ptr_t AllocateHugeData(idx_t size) const; - void FreeHugeData(data_ptr_t pointer, idx_t size) const; + data_ptr_t AllocateHugeData(idx_t size, optional_idx &home) const; + void FreeHugeData(data_ptr_t pointer, idx_t size, optional_idx home) const; + data_ptr_t AllocateFallbackData(idx_t size) const; + void FreeFallbackData(data_ptr_t pointer, idx_t size, optional_idx home) const; enum class FlushState : uint8_t { IDLE, SCHEDULED, RESCHEDULE_REQUESTED }; enum class ReclaimMode : uint8_t { FORCE, DECAY, OPPORTUNISTIC }; @@ -98,7 +135,6 @@ class BlockAllocator { idx_t ModuloBlockSize(idx_t n) const; idx_t DivBlockSize(idx_t n) const; - idx_t GetLocalPoolShard() const; uint32_t GetBlockID(data_ptr_t pointer) const; data_ptr_t GetPointer(uint32_t block_id) const; diff --git a/src/duckdb/src/include/duckdb/storage/block_manager.hpp b/src/duckdb/src/include/duckdb/storage/block_manager.hpp index ec3b8eeb2..96a790e67 100644 --- a/src/duckdb/src/include/duckdb/storage/block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/block_manager.hpp @@ -58,6 +58,10 @@ class BlockManager { virtual bool IsRootBlock(MetaBlockPointer root) = 0; //! Mark a block as included in the next checkpoint virtual void MarkBlockAsCheckpointed(block_id_t block_id) = 0; + //! Mark a newly used block as part of a commit: checkpoints whose bound is past the commit include it + virtual void MarkBlockAsCommitted(block_id_t block_id, transaction_t commit_id) { + MarkBlockAsCheckpointed(block_id); + } //! Mark a block as "used"; either the block is removed from the free list, or the reference count is incremented virtual void MarkBlockAsUsed(block_id_t block_id) = 0; //! Mark a block as "modified"; modified blocks are added to the free list after a checkpoint (i.e. their data is @@ -80,8 +84,8 @@ class BlockManager { void Write(Block &block) { Write(block, block.id); } - //! Write the header; should be the final step of a checkpoint - virtual void WriteHeader(QueryContext context, DatabaseHeader header) = 0; + //! Write the header of a checkpoint with the given bound; should be the final step of a checkpoint + virtual void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound) = 0; //! Returns the number of total blocks virtual idx_t TotalBlocks() = 0; diff --git a/src/duckdb/src/include/duckdb/storage/checkpoint/table_index_writer.hpp b/src/duckdb/src/include/duckdb/storage/checkpoint/table_index_writer.hpp index 4fc89c101..a562bb17f 100644 --- a/src/duckdb/src/include/duckdb/storage/checkpoint/table_index_writer.hpp +++ b/src/duckdb/src/include/duckdb/storage/checkpoint/table_index_writer.hpp @@ -13,6 +13,7 @@ #include "duckdb/storage/index_storage_info.hpp" namespace duckdb { +class Context; class PartialBlockManager; class PendingPublication; class SingleFileCheckpointWriter; @@ -43,6 +44,8 @@ class TableIndexWriter { virtual void AddPendingPublication(unique_ptr publication) = 0; //! Get the targeted storage version for the current writer StorageVersion GetStorageVersion() const; + //! The context to attribute the checkpoint IO to + virtual Context &GetContext() const = 0; protected: //! Used to colocate blocks across indexes, used when index supports deferred checkpointing. @@ -56,6 +59,7 @@ class SingleFileTableIndexWriter : public TableIndexWriter { private: PartialBlockManager CreatePerIndexPartialBlockManager() override; + Context &GetContext() const override; void AddPendingPublication(unique_ptr publication) override; private: diff --git a/src/duckdb/src/include/duckdb/storage/checkpoint/write_overflow_strings_to_disk.hpp b/src/duckdb/src/include/duckdb/storage/checkpoint/write_overflow_strings_to_disk.hpp index 5a69e6018..8176c0d29 100644 --- a/src/duckdb/src/include/duckdb/storage/checkpoint/write_overflow_strings_to_disk.hpp +++ b/src/duckdb/src/include/duckdb/storage/checkpoint/write_overflow_strings_to_disk.hpp @@ -13,13 +13,16 @@ namespace duckdb { +class Context; class PartialBlockManager; class WriteOverflowStringsToDisk : public OverflowStringWriter { public: - explicit WriteOverflowStringsToDisk(PartialBlockManager &partial_block_manager); + WriteOverflowStringsToDisk(Context &context, PartialBlockManager &partial_block_manager); ~WriteOverflowStringsToDisk() override; + //! The context to attribute the write IO to + Context &context; //! The block manager PartialBlockManager &partial_block_manager; diff --git a/src/duckdb/src/include/duckdb/storage/compression/alp/algorithm/alp.hpp b/src/duckdb/src/include/duckdb/storage/compression/alp/algorithm/alp.hpp index 3122f0473..3355d89e6 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/alp/algorithm/alp.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/alp/algorithm/alp.hpp @@ -399,15 +399,10 @@ struct AlpDecompression { AlpEncodingIndices encoding_indices = {vector_exponent, vector_factor}; // Bit Unpacking - uint64_t for_decoded[AlpConstants::ALP_VECTOR_SIZE] = {0}; - if (bit_width > 0) { - BitpackingPrimitives::UnPackBuffer(data_ptr_cast(for_decoded), for_encoded, count, bit_width); - } - - // unFOR - for (idx_t i = 0; i < count; i++) { - for_decoded[i] += frame_of_reference; - } + uint64_t for_decoded[AlpConstants::ALP_VECTOR_SIZE]; + BitpackingPrimitives::UnPackBufferWithFrame(data_ptr_cast(for_decoded), for_encoded, + BitpackingPrimitives::RoundUpToAlgorithmGroupSize(count), + bit_width, frame_of_reference); // Decoding for (idx_t i = 0; i < count; i++) { diff --git a/src/duckdb/src/include/duckdb/storage/compression/alprd/algorithm/alprd.hpp b/src/duckdb/src/include/duckdb/storage/compression/alprd/algorithm/alprd.hpp index 25f1b8cb6..37e430317 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/alprd/algorithm/alprd.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/alprd/algorithm/alprd.hpp @@ -220,25 +220,25 @@ struct AlpRDDecompression { const AlpRDConstants::EXCEPTION_POSITION_TYPE *exceptions_positions, AlpRDConstants::BIT_WIDTH_TYPE left_bit_width, AlpRDConstants::BIT_WIDTH_TYPE right_bit_width) { - AlpRDConstants::DICTIONARY_ELEMENT_TYPE left_decoded[AlpRDConstants::ALP_VECTOR_SIZE] = {0}; - EXACT_TYPE right_decoded[AlpRDConstants::ALP_VECTOR_SIZE] = {0}; + AlpRDConstants::DICTIONARY_ELEMENT_TYPE left_decoded[AlpRDConstants::ALP_VECTOR_SIZE]; // Bitunpacking left and right parts BitpackingPrimitives::UnPackBuffer( data_ptr_cast(left_decoded), left_encoded, values_count, left_bit_width); - BitpackingPrimitives::UnPackBuffer(data_ptr_cast(right_decoded), right_encoded, values_count, - right_bit_width); + BitpackingPrimitives::UnPackBufferWithFrame( + data_ptr_cast(output), right_encoded, BitpackingPrimitives::RoundUpToAlgorithmGroupSize(values_count), + right_bit_width, 0); // Decoding for (idx_t i = 0; i < values_count; i++) { AlpRDConstants::DICTIONARY_ELEMENT_TYPE left = left_parts_dict[left_decoded[i]]; - EXACT_TYPE right = right_decoded[i]; + EXACT_TYPE right = output[i]; output[i] = (static_cast(left) << right_bit_width) | right; } // Exceptions Patching (exceptions only occur in left parts) for (idx_t i = 0; i < exceptions_count; i++) { - EXACT_TYPE right = right_decoded[exceptions_positions[i]]; + EXACT_TYPE right = output[exceptions_positions[i]] & ((EXACT_TYPE(1) << right_bit_width) - 1); AlpRDConstants::EXCEPTION_TYPE left = exceptions[i]; output[exceptions_positions[i]] = (static_cast(left) << right_bit_width) | right; } diff --git a/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/decompression.hpp b/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/decompression.hpp index c89d03ed8..096cd5b5c 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/decompression.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/dict_fsst/decompression.hpp @@ -51,6 +51,8 @@ struct CompressedStringScanState : public SegmentScanState { StringScanType string_scan_type = StringScanType::STANDARD); void ScanToDictionaryVector(ColumnSegment &segment, Vector &result, idx_t result_offset, idx_t start, idx_t scan_count); + void SelectToDictionaryVector(Vector &result, idx_t start, idx_t vector_count, const SelectionVector &sel, + idx_t sel_count); const SelectionVector &GetSelVec(idx_t start, idx_t scan_count); void Select(Vector &result, idx_t result_offset, idx_t start, const SelectionVector &sel, idx_t sel_count, StringScanType string_scan_type = StringScanType::STANDARD); @@ -98,8 +100,7 @@ struct CompressedStringScanState : public SegmentScanState { void *decoder = nullptr; bool all_values_inlined = false; - unsafe_unique_array filter_result; - bool null_filter_result_initialized = false; + unique_ptr filter_cache; }; } // namespace dict_fsst diff --git a/src/duckdb/src/include/duckdb/storage/compression/roaring/roaring.hpp b/src/duckdb/src/include/duckdb/storage/compression/roaring/roaring.hpp index 6c7ef07b2..b83c2a5da 100644 --- a/src/duckdb/src/include/duckdb/storage/compression/roaring/roaring.hpp +++ b/src/duckdb/src/include/duckdb/storage/compression/roaring/roaring.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/array_ptr.hpp" +#include "duckdb/common/optional.hpp" #include "duckdb/common/typedefs.hpp" #include "duckdb/common/helper.hpp" #include "duckdb/common/types/validity_mask.hpp" @@ -685,14 +686,30 @@ struct RoaringScanState : public SegmentScanState { void ScanPartial(idx_t start_idx, ValidityMask &result, idx_t offset, idx_t count); void Skip(ContainerScanState &scan_state, idx_t skip_count); +private: + template + void InitializeContainer(optional &state, ARGS &&...args) { + current_container = nullptr; + current_container = &state.emplace(std::forward(args)...); + } + public: BufferHandle handle; ColumnSegment &segment; - unique_ptr current_container; + optional_ptr current_container; SegmentLayout layout; ContainerMetadataCollection metadata_collection; vector container_metadata; vector data_start_position; + +private: + optional bitset_state; + optional compressed_run_state; + optional uncompressed_run_state; + optional> compressed_null_state; + optional> compressed_non_null_state; + optional> uncompressed_null_state; + optional> uncompressed_non_null_state; }; //! Boolean BitPacking diff --git a/src/duckdb/src/include/duckdb/storage/data_table.hpp b/src/duckdb/src/include/duckdb/storage/data_table.hpp index c4fbe1658..cf51f0ef2 100644 --- a/src/duckdb/src/include/duckdb/storage/data_table.hpp +++ b/src/duckdb/src/include/duckdb/storage/data_table.hpp @@ -44,6 +44,7 @@ class TableDataWriter; class TableStatistics; class ConflictManager; class TableScanState; +struct TableScanAssignment; struct CollectionCheckpointResult; struct TableDeleteState; struct ConstraintState; @@ -104,6 +105,9 @@ class DataTable : public enable_shared_from_this { const vector &column_indexes); optional_idx NextParallelScan(ClientContext &context, ParallelTableScanState &state, TableScanState &scan_state, bool initialize_columns = true); + //! Claims a range without column initialization and retains it for another worker + bool NextParallelScanAssignment(ClientContext &context, ParallelTableScanState &state, TableScanState &scan_state, + TableScanAssignment &assignment); //! Scans up to STANDARD_VECTOR_SIZE elements from the table starting //! from offset and store them in result. Offset is incremented with how many @@ -246,6 +250,10 @@ class DataTable : public enable_shared_from_this { idx_t GetTotalRows() const; idx_t GetNextRowId() const; idx_t GetRowGroupCount() const; + //! The number of row groups, including the ones that are not loaded yet, without loading them + idx_t GetRowGroupCountWithoutLoading() const; + //! The same, including the row groups of the transaction-local storage + idx_t GetRowGroupCountWithoutLoading(ClientContext &context); idx_t GetRowGroupCountWithLocalStorage(ClientContext &context); vector @@ -300,8 +308,12 @@ class DataTable : public enable_shared_from_this { vector GetPartitionStats(ClientContext &context); private: + optional_idx NextParallelScanInternal(ClientContext &context, ParallelTableScanState &state, + TableScanState &scan_state, bool initialize_columns, + optional_ptr assignment); //! Verify the new added constraints against current persistent&local data - void VerifyNewConstraint(LocalStorage &local_storage, DataTable &parent, const BoundConstraint &constraint); + void VerifyNewConstraint(ClientContext &context, LocalStorage &local_storage, DataTable &parent, + const BoundConstraint &constraint); //! Verify constraints with a chunk from the Update containing only the specified column_ids void VerifyUpdateConstraints(ConstraintState &state, ClientContext &context, DataChunk &chunk, diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp index dc0e40462..80cc836b7 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp @@ -50,12 +50,16 @@ struct ReadThroughputEstimator { }; struct CachingFileHandle { + friend class CachingFileSystem; + public: using CachedFile = ExternalFileCache::CachedFile; +private: + CachingFileHandle(QueryContext context, CachingFileSystem &caching_file_system, const OpenFileInfo &path, + FileOpenFlags flags, optional_ptr opener); + public: - DUCKDB_API CachingFileHandle(QueryContext context, CachingFileSystem &caching_file_system, const OpenFileInfo &path, - FileOpenFlags flags, optional_ptr opener); DUCKDB_API ~CachingFileHandle(); public: @@ -99,6 +103,10 @@ struct CachingFileHandle { DUCKDB_API void Seek(idx_t location); private: + //! Open the file unless cached blocks allow deferring it; returns false if the file system returned no handle + bool Initialize(); + //! Open the underlying FileHandle if not yet open; returns nullptr if the file system returned no handle + shared_ptr TryGetFileHandle(); //! Remove the 'force_full_download' option from the file handle if present, and return whether it was present bool StripForceFullDownloadIfPresent(); //! Refresh the cached file if the global cache state has changed. diff --git a/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp b/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp index e0a048e1c..c46851c65 100644 --- a/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp @@ -65,7 +65,7 @@ class InMemoryBlockManager : public BlockManager { void Write(QueryContext context, FileBuffer &block, block_id_t block_id) override { throw InternalException("Cannot perform IO in in-memory database - Write with client context!"); } - void WriteHeader(QueryContext context, DatabaseHeader header) override { + void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound) override { throw InternalException("Cannot perform IO in in-memory database - WriteHeader!"); } bool InMemory() override { diff --git a/src/duckdb/src/include/duckdb/storage/metadata/metadata_reader.hpp b/src/duckdb/src/include/duckdb/storage/metadata/metadata_reader.hpp index cb94abfb8..84175f30a 100644 --- a/src/duckdb/src/include/duckdb/storage/metadata/metadata_reader.hpp +++ b/src/duckdb/src/include/duckdb/storage/metadata/metadata_reader.hpp @@ -45,6 +45,9 @@ class MetadataReader : public ReadStream { MetadataPointer FromDiskPointer(MetaBlockPointer pointer); + //! Throws if the chain of metadata blocks loops back to a block that was already read + void CheckForCycle(); + private: MetadataManager &manager; BlockReaderType type; @@ -56,6 +59,10 @@ class MetadataReader : public ReadStream { idx_t offset; idx_t next_offset; idx_t capacity; + //! Cycle detection: the pointer of the block that was read when blocks_read reached the previous power of two + idx_t cycle_check_pointer; + idx_t cycle_check_at; + idx_t blocks_read; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/object_cache.hpp b/src/duckdb/src/include/duckdb/storage/object_cache.hpp index 4c4ed3a05..509b2ac67 100644 --- a/src/duckdb/src/include/duckdb/storage/object_cache.hpp +++ b/src/duckdb/src/include/duckdb/storage/object_cache.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/common.hpp" +#include "duckdb/common/condition_variable.hpp" #include "duckdb/common/enums/memory_tag.hpp" #include "duckdb/common/lru_cache.hpp" #include "duckdb/common/mutex.hpp" @@ -17,6 +18,8 @@ #include "duckdb/common/unordered_map.hpp" #include "duckdb/storage/buffer/buffer_pool_reservation.hpp" +#include + namespace duckdb { class ClientContext; @@ -85,7 +88,7 @@ class ObjectCache { } template - shared_ptr GetOrCreate(const string &key, ARGS &&... args) { + shared_ptr GetOrCreate(const string &key, ARGS &&...args) { const lock_guard lock(lock_mutex); // Check non-evictable entries first @@ -128,18 +131,30 @@ class ObjectCache { } const lock_guard lock(lock_mutex); - const auto estimated_memory = value->GetEstimatedCacheMemory(); - const bool is_evictable = estimated_memory.IsValid(); - if (!is_evictable) { - non_evictable_entries[std::move(key)] = std::move(value); - return; - } + PutInternal(std::move(key), std::move(value)); + } - auto reservation = - make_uniq(MemoryTag::OBJECT_CACHE, buffer_pool, estimated_memory.GetIndex()); - lru_cache.Put(std::move(key), std::move(value), std::move(reservation)); + //! Puts `value` under `key` unless an entry is there already, and returns the entry under `key` afterwards. + shared_ptr GetOrPut(const string &key, shared_ptr value) { + const lock_guard lock(lock_mutex); + auto non_evictable_it = non_evictable_entries.find(key); + if (non_evictable_it != non_evictable_entries.end()) { + return non_evictable_it->second; + } + auto existing = lru_cache.Get(key); + if (existing) { + return existing; + } + PutInternal(key, value); + return value; } + //! Returns the entry under `key`, creating it with `create` first if there is none. `create` runs without the + //! cache lock; concurrent calls for the same key wait for it, calls for other keys do not. If `create` throws or + //! returns null, nothing is cached, and the waiting calls retry with their own `create`. + DUCKDB_API shared_ptr + GetOrCreateObject(const string &key, const std::function()> &create); + void Delete(const string &key) { const lock_guard lock(lock_mutex); auto iter = non_evictable_entries.find(key); @@ -159,7 +174,7 @@ class ObjectCache { } template - shared_ptr GetOrCreateWithTypePrefix(const string &key, ARGS &&... args) { + shared_ptr GetOrCreateWithTypePrefix(const string &key, ARGS &&...args) { return GetOrCreate(MakeCacheKey(key), std::forward(args)...); } @@ -203,6 +218,21 @@ class ObjectCache { bool EvictToMemoryLimit(idx_t memory_limit); private: + //! Replaces the entry under `key`, whether pinned or evictable. Requires the lock. + void PutInternal(string key, shared_ptr value) { + const auto estimated_memory = value->GetEstimatedCacheMemory(); + const bool is_evictable = estimated_memory.IsValid(); + if (!is_evictable) { + lru_cache.Delete(key); + non_evictable_entries[std::move(key)] = std::move(value); + return; + } + non_evictable_entries.erase(key); + auto reservation = + make_uniq(MemoryTag::OBJECT_CACHE, buffer_pool, estimated_memory.GetIndex()); + lru_cache.Put(std::move(key), std::move(value), std::move(reservation)); + } + //! Build the internal cache key for a typed entry by namespacing the caller-provided key with the entry's //! ObjectType. template @@ -210,6 +240,16 @@ class ObjectCache { return StringUtil::Format("%s-%s", T::ObjectType(), key); } +private: + //! A creation by `GetOrCreateObject` in progress, which other calls for the same key wait for. + struct InFlightCreation { + mutex lock; + condition_variable finished_cv; + bool finished = false; + }; + //! Unregisters a creation and wakes its waiters, however the creation ended. + void FinishCreation(const string &key, InFlightCreation &creation); + private: mutable mutex lock_mutex; //! LRU cache for evictable entries @@ -219,6 +259,10 @@ class ObjectCache { unordered_map> non_evictable_entries; //! Used to create buffer pool reservation on entries creation. BufferPool &buffer_pool; + //! Guards `in_flight_creations`, separately from the cache itself. + mutex in_flight_lock; + //! Creations by `GetOrCreateObject` in progress, by key. + unordered_map> in_flight_creations; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/optimistic_data_writer.hpp b/src/duckdb/src/include/duckdb/storage/optimistic_data_writer.hpp index 3104bb393..e152ac84b 100644 --- a/src/duckdb/src/include/duckdb/storage/optimistic_data_writer.hpp +++ b/src/duckdb/src/include/duckdb/storage/optimistic_data_writer.hpp @@ -34,45 +34,39 @@ enum class OptimisticWritePartialManagers { PER_COLUMN, GLOBAL }; class OptimisticDataWriter { public: - OptimisticDataWriter(ClientContext &context, DataTable &table); - OptimisticDataWriter(Context &context, DataTable &table); + explicit OptimisticDataWriter(DataTable &table); OptimisticDataWriter(DataTable &table, OptimisticDataWriter &parent); ~OptimisticDataWriter(); + //! The methods below take the context of the operation that performs them: the writer can outlive the + //! connection that created it (e.g. a writer of a transaction that is shared between connections). //! Creates a collection to write to unique_ptr - CreateCollection(DataTable &storage, const vector &insert_types, + CreateCollection(Context &context, DataTable &storage, const vector &insert_types, OptimisticWritePartialManagers type = OptimisticWritePartialManagers::PER_COLUMN); //! Write a new row group to disk (if possible) - void WriteNewRowGroup(OptimisticWriteCollection &row_groups, idx_t flushed_row_group_idx); + void WriteNewRowGroup(Context &context, OptimisticWriteCollection &row_groups, idx_t flushed_row_group_idx); //! Write any unflushed row groups of a collection to disk - void WriteUnflushedRowGroups(OptimisticWriteCollection &row_groups); + void WriteUnflushedRowGroups(Context &context, OptimisticWriteCollection &row_groups); //! Final flush of the optimistic writer - fully flushes the partial block manager - void FinalFlush(); + void FinalFlush(Context &context); //! Merge the partially written blocks from one optimistic writer into another - void Merge(OptimisticDataWriter &other); - void Merge(unique_ptr &other_manager); + void Merge(Context &context, OptimisticDataWriter &other); + void Merge(Context &context, unique_ptr &other_manager); //! Rollback void Rollback(); //! Whether this writer can write to disk at all (not temporary / in-memory / read-only) bool CanWriteToDisk() const; - //! Return the runtime services. - Context &GetContext() { - return context; - } - private: //! Prepare a write to disk - bool PrepareWrite(); + bool PrepareWrite(Context &context); //! Flushes a specific row group to disk - void FlushToDisk(OptimisticWriteCollection &collection, const vector> &row_groups, - const vector &segment_indexes); + void FlushToDisk(Context &context, OptimisticWriteCollection &collection, + const vector> &row_groups, const vector &segment_indexes); private: - //! The services in which we're writing the data. - Context &context; //! The table. DataTable &table; //! The partial block manager, if any. diff --git a/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp b/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp index de15f83ea..5c6f8d83b 100644 --- a/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/partial_block_manager.hpp @@ -12,6 +12,7 @@ #include "duckdb/common/mutex.hpp" #include "duckdb/common/optional.hpp" #include "duckdb/common/optional_idx.hpp" +#include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/query_context.hpp" #include "duckdb/common/unique_ptr.hpp" #include "duckdb/storage/block.hpp" @@ -36,7 +37,7 @@ class PartialBlockManager { public: //! Use the default packing threshold unless supplied; it must not exceed the block size. - PartialBlockManager(Context &context, BlockManager &block_manager, PartialBlockType partial_block_type, + PartialBlockManager(BlockManager &block_manager, PartialBlockType partial_block_type, optional_idx max_partial_block_size = optional_idx(), uint32_t max_use_count = DEFAULT_MAX_USE_COUNT); //! Discard pending blocks without flushing or finalizing their packables. @@ -49,18 +50,22 @@ class PartialBlockManager { //! Absorb other's pending blocks, leaving it empty on success; may flush and finalize packables. //! Managers must be distinct, exclusively accessed, and share the block manager and mode. //! Coalescing blocks requires unassigned persistent block IDs. - void Merge(PartialBlockManager &other); + void Merge(Context &context, PartialBlockManager &other); //! Flush and finalize all pending blocks, leaving the map empty on success; in-memory mode skips disk IO. - void FlushPartialBlocks(); + void FlushPartialBlocks(Context &context); //! Consume a valid source pin and pack its first byte_size bytes; 0 < byte_size <= block size. //! Returns a fixed destination only in FULL_CHECKPOINT mode, otherwise nullopt; may flush before returning. //! The packable must outlive its pending allocation, until flushed or discarded. //! The caller must permit adoption and modification of the source's backing storage. - optional Write(BlockPackable &packable, BufferHandle &&source, uint32_t byte_size); + optional Write(Context &context, BlockPackable &packable, BufferHandle &&source, uint32_t byte_size); //! Borrow a valid source pin and copy its first byte_size bytes synchronously without adopting its storage. //! The source is neither modified nor retained; destination and packable lifetime rules are as above. + optional Write(Context &context, BlockPackable &packable, const BufferHandle &source, + uint32_t byte_size); + //! As above, for index checkpoints, whose Index::Checkpoint API does not provide a context: blocks this flushes + //! are not attributed to a query. optional Write(BlockPackable &packable, const BufferHandle &source, uint32_t byte_size); //! Reserve a disk block ID, using checkpoint accounting in FULL_CHECKPOINT mode; not for in-memory storage. @@ -68,8 +73,10 @@ class PartialBlockManager { //! Returns a reference to the underlying block manager. BlockManager &GetBlockManager() const; - //! Returns the query context to attribute IO to. - QueryContext GetQueryContext() const; + //! Returns what the partial block manager writes for. + PartialBlockType GetPartialBlockType() const { + return partial_block_type; + } private: //! Remove the smallest fitting block from the map, or return nullptr if none fits. @@ -81,11 +88,12 @@ class PartialBlockManager { //! Remove the block with least free space if the map limit is exceeded; otherwise return nullptr. unique_ptr PruneFreeList(); //! Consume the block, retaining it if reusable or flushing it otherwise; also flush any pruned map entry. - void RetainOrFlush(unique_ptr partial_block); + void RetainOrFlush(optional_ptr context, unique_ptr partial_block); + //! Store a copy of the source in a block and retain or flush it. + optional WriteCopy(optional_ptr context, BlockPackable &packable, const BufferHandle &source, + uint32_t byte_size); private: - //! The context in which we use the partial block manager (owned by the checkpoint writer) - Context &context; BlockManager &block_manager; PartialBlockType partial_block_type; mutex partial_block_lock; diff --git a/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp b/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp index 950d09c04..9cd500b8d 100644 --- a/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp @@ -92,6 +92,8 @@ class SingleFileBlockManager : public BlockManager { bool IsRootBlock(MetaBlockPointer root) override; //! Mark a block as included in a checkpoint void MarkBlockAsCheckpointed(block_id_t block_id) override; + //! Mark a newly used block as part of a commit + void MarkBlockAsCommitted(block_id_t block_id, transaction_t commit_id) override; //! Mark a block as used (no longer re-writeable) void MarkBlockAsUsed(block_id_t block_id) override; //! Mark a block as modified (re-writeable after a checkpoint) @@ -117,7 +119,7 @@ class SingleFileBlockManager : public BlockManager { //! Write the block to disk. void Write(QueryContext context, FileBuffer &buffer, block_id_t block_id) override; //! Write the header to disk, this is the final step of the checkpointing process - void WriteHeader(QueryContext context, DatabaseHeader header) override; + void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound) override; //! Sync changes to the underlying file void FileSync() override; //! Truncate the underlying database file after a checkpoint @@ -214,8 +216,8 @@ class SingleFileBlockManager : public BlockManager { set free_list; //! The list of blocks that have been freed, but cannot yet be re-used because they are still in-use set free_blocks_in_use; - //! The list of blocks that are in-use, but haven't been written as part of a checkpoint yet - set newly_used_blocks; + //! Blocks in use that no written header includes yet, by commit id (MAX_TRANSACTION_ID while uncommitted) + unordered_map newly_used_blocks; //! The list of multi-use blocks (i.e. blocks that have >1 reference in the file) //! When a multi-use block is marked as modified, the reference count is decreased by 1 instead of directly //! Appending the block to the modified_blocks list diff --git a/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp b/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp index 5c54c5f96..7d5af669a 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/geometry_stats.hpp @@ -283,6 +283,10 @@ class GeometryStatsFlags { static constexpr auto HAS_NON_EMPTY_PART = 0x8; }; +//! Geometry statistics. The struct itself does not know whether it belongs to a GEOMETRY or a +//! GEOGRAPHY column: the GeometryModel argument of Merge/Update (GEODETIC enables the antimeridian-aware, +//! circular longitude extent math used by GEOGRAPHY) must be derived from the column type by the +//! caller, i.e. `Geometry::GetModel(type)`. struct GeometryStatsData { GeometryTypeSet types; GeometryExtent extent; @@ -300,20 +304,25 @@ struct GeometryStatsData { flags = GeometryStatsFlags::Unknown(); } - void Merge(const GeometryStatsData &other) { + void Merge(const GeometryStatsData &other, GeometryModel model) { types.Merge(other.types); - extent.Merge(other.extent); + extent.Merge(other.extent, model); flags.Merge(other.flags); } - void Update(const string_t &geom_blob) { + void Update(const string_t &geom_blob, GeometryModel model) { // Parse type const auto type_info = Geometry::GetType(geom_blob); types.Add(type_info.first, type_info.second); - // Update extent + // Compute this row's own extent first, then merge it as a whole. Extending the accumulated + // extent vertex-by-vertex would only cover the vertices: the (possibly antimeridian-wrapped) + // arc the row's own bounding box spans between them could stick out of the accumulated extent, + // and the row-level && operator compares against that per-row bounding box. + auto row_extent = GeometryExtent::Empty(); bool has_any_empty = false; - const auto vert_count = Geometry::GetExtent(geom_blob, extent, has_any_empty); + const auto vert_count = Geometry::GetExtent(geom_blob, row_extent, has_any_empty, model); + extent.Merge(row_extent, model); // Update flags if (has_any_empty) { diff --git a/src/duckdb/src/include/duckdb/storage/statistics/stats_writer.hpp b/src/duckdb/src/include/duckdb/storage/statistics/stats_writer.hpp index 2970dc18e..f0fecdb4e 100644 --- a/src/duckdb/src/include/duckdb/storage/statistics/stats_writer.hpp +++ b/src/duckdb/src/include/duckdb/storage/statistics/stats_writer.hpp @@ -131,7 +131,9 @@ struct StatsWriter : public BaseStatsWriter { friend struct StringStats; explicit StatsWriter(const LogicalType &type) - : is_varchar(type.id() == LogicalTypeId::VARCHAR), is_geometry(type.id() == LogicalTypeId::GEOMETRY), + : is_varchar(type.id() == LogicalTypeId::VARCHAR), + is_geometry(type.id() == LogicalTypeId::GEOMETRY || type.id() == LogicalTypeId::GEOGRAPHY), + geometry_model(Geometry::GetModel(type)), is_bignum(BaseStatistics::GetStatsType(type) == StatisticsType::BIGNUM_STATS) { Clear(); } @@ -157,7 +159,7 @@ struct StatsWriter : public BaseStatsWriter { inline void Update(const string_t &value) { SetHasValid(); if (is_geometry) { - geometry_stats.Update(value); + geometry_stats.Update(value, geometry_model); return; } if (is_bignum) { @@ -249,7 +251,7 @@ struct StatsWriter : public BaseStatsWriter { void Merge(BaseStatistics &other) const { MergeBase(other); if (is_geometry) { - GeometryStats::GetDataUnsafe(other).Merge(geometry_stats); + GeometryStats::GetDataUnsafe(other).Merge(geometry_stats, geometry_model); } else if (is_bignum) { BignumStats::Merge(other, string_t(bignum_min), string_t(bignum_max)); } else { @@ -281,6 +283,7 @@ struct StatsWriter : public BaseStatsWriter { idx_t total_string_length; bool is_varchar; bool is_geometry; + GeometryModel geometry_model; bool is_bignum; GeometryStatsData geometry_stats; string bignum_min; diff --git a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp index 09489b653..6cfcbb4f7 100644 --- a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp @@ -42,7 +42,7 @@ class StorageCommitState { //! Write the commit's WAL flush marker. With sync_now the WAL is synced up to it before returning; //! otherwise the marker is only pushed to the OS and the WAL offset to sync up to is returned (0 if //! nothing was written, or it was synced here) - virtual idx_t FlushCommit(bool sync_now) = 0; + virtual idx_t FlushCommit(transaction_t commit_id, bool sync_now) = 0; virtual void AddRowGroupData(DataTable &table, idx_t start_index, idx_t count, unique_ptr row_group_data) = 0; 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 12a1e3fc3..7ae02e1e7 100644 --- a/src/duckdb/src/include/duckdb/storage/table/append_state.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/append_state.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/vector.hpp" #include "duckdb/function/compression_function.hpp" #include "duckdb/planner/bound_constraint.hpp" @@ -17,6 +18,7 @@ namespace duckdb { class ColumnSegment; +class Context; class DataTable; class LocalTableStorage; class RowGroup; @@ -126,6 +128,8 @@ struct ConstraintState { struct LocalAppendState { TableAppendState append_state; LocalTableStorage *storage; + //! The context of the operation that appends (the local storage can outlive the connection that created it) + optional_ptr context; unique_ptr constraint_state; }; diff --git a/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp index d81d8f7dd..785a9d1bc 100644 --- a/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/array_column_data.hpp @@ -53,7 +53,7 @@ class ArrayColumnData : public ColumnData { void VisitBlockIds(BlockIdVisitor &visitor) const override; - unique_ptr CreateCheckpointState(const RowGroup &row_group, + unique_ptr CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) override; unique_ptr Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info, const BaseStatistics &old_stats) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/column_checkpoint_state.hpp b/src/duckdb/src/include/duckdb/storage/table/column_checkpoint_state.hpp index 02dcd4151..2081fcca2 100644 --- a/src/duckdb/src/include/duckdb/storage/table/column_checkpoint_state.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/column_checkpoint_state.hpp @@ -18,11 +18,12 @@ namespace duckdb { class ColumnData; class DatabaseInstance; class RowGroup; +class Context; class PartialBlockManager; class TableDataWriter; struct ColumnCheckpointState { - ColumnCheckpointState(const RowGroup &row_group, ColumnData &original_column, + ColumnCheckpointState(const RowGroup &row_group, ColumnData &original_column, Context &context, PartialBlockManager &partial_block_manager); virtual ~ColumnCheckpointState(); @@ -32,6 +33,8 @@ struct ColumnCheckpointState { unique_ptr global_stats; protected: + //! The context to attribute the checkpoint IO to + Context &context; PartialBlockManager &partial_block_manager; shared_ptr result_column; @@ -52,6 +55,9 @@ struct ColumnCheckpointState { PartialBlockManager &GetPartialBlockManager() { return partial_block_manager; } + Context &GetContext() { + return context; + } public: template diff --git a/src/duckdb/src/include/duckdb/storage/table/column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/column_data.hpp index 9b0e05d96..2b770f8c9 100644 --- a/src/duckdb/src/include/duckdb/storage/table/column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/column_data.hpp @@ -55,6 +55,7 @@ struct ColumnCheckpointInfo { idx_t column_idx; public: + Context &GetContext(); PartialBlockManager &GetPartialBlockManager(); CompressionType GetCompressionType(); @@ -208,7 +209,7 @@ class ColumnData : public enable_shared_from_this { virtual void VisitBlockIds(BlockIdVisitor &visitor) const; - virtual unique_ptr CreateCheckpointState(const RowGroup &row_group, + virtual unique_ptr CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager); //! If this is a nested column, "stats" are the corresponding statistics from the parent column //! Otherwise, "stats" == this->statistics->stats diff --git a/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp index ce39663d0..fc32e784a 100644 --- a/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp @@ -56,7 +56,7 @@ class GeoColumnData final : public ColumnData { idx_t row_group_start) override; unique_ptr GetUpdateStatistics() override; - unique_ptr CreateCheckpointState(const RowGroup &row_group, + unique_ptr CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) override; unique_ptr Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info, const BaseStatistics &old_stats) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp index d7736bd0c..8bb7434f5 100644 --- a/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/list_column_data.hpp @@ -69,7 +69,7 @@ class ListColumnData : public ColumnData { void VisitBlockIds(BlockIdVisitor &visitor) const override; - unique_ptr CreateCheckpointState(const RowGroup &row_group, + unique_ptr CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) override; unique_ptr Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info, const BaseStatistics &old_stats) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/row_group.hpp b/src/duckdb/src/include/duckdb/storage/table/row_group.hpp index 3814bbb46..7b38ebf8d 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_group.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_group.hpp @@ -63,15 +63,17 @@ enum class ColumnDataType; class ClientContext; struct RowGroupWriteInfo { - RowGroupWriteInfo(PartialBlockManager &manager, const vector &compression_types, + RowGroupWriteInfo(Context &context, PartialBlockManager &manager, const vector &compression_types, CheckpointOptions options = CheckpointOptions()); - RowGroupWriteInfo(PartialBlockManager &manager, const vector &compression_types, + RowGroupWriteInfo(Context &context, PartialBlockManager &manager, const vector &compression_types, vector> &column_partial_block_managers_p); private: PartialBlockManager &manager; public: + //! The context to attribute the write IO to + Context &context; const vector &compression_types; CheckpointOptions options; @@ -205,6 +207,8 @@ class RowGroup : public SegmentBase { vector> CollectScanIOTasks(CollectionScanState &state, idx_t row_count) const; //! Collects the async I/O tasks of the remaining assignment, leaving out the vectors the zonemaps reject vector> CollectAssignmentIOTasks(CollectionScanState &state) const; + //! Collects the on-disk blocks needed by the remaining assignment without scheduling reads. + void CollectAssignmentBlocks(CollectionScanState &state, PrefetchState &blocks) const; //! Prepares the next eligible vector in the assigned range, idempotent, returns false when none remain bool PrepareScan(ScanOptions options, CollectionScanState &state); //! Processes the vector prepared by PrepareScan, clearing the prepared state when the vector is finished @@ -309,10 +313,9 @@ class RowGroup : public SegmentBase { ColumnData &GetRawColumnData(storage_t c) const; private: - //! Registers prefetch candidates for the rows in [start_row, end_row), returns false when prefetching is not - //! supported - bool RegisterScanIO(CollectionScanState &state, idx_t start_row, idx_t end_row, - PrefetchState &prefetch_state) const; + //! Collects prefetch candidates for the rows in [start_row, end_row) + void CollectScanBlocks(CollectionScanState &state, idx_t start_row, idx_t end_row, + PrefetchState &prefetch_state) const; //! Shared scan-state setup for InitializeScan and InitializeScanWithOffset bool InitializeScanInternal(CollectionScanState &state, SegmentNode &node, idx_t vector_offset); //! Advances the scan past the current vector, clearing the prepared state @@ -340,6 +343,8 @@ class RowGroup : public SegmentBase { private: mutable mutex row_group_lock; + //! Held while an update writes its columns, so concurrent updates of a row never mix their columns + mutex update_lock; vector column_pointers; //! Whether or not each column is loaded (mutable because `const` can lazy load) mutable unique_ptr[]> is_loaded; diff --git a/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp b/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp index 5d3440825..5f7be108f 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_group_collection.hpp @@ -98,6 +98,8 @@ class RowGroupCollection { idx_t GetTotalRows() const; idx_t GetNextRowId() const; idx_t GetRowGroupCount() const; + //! The number of row groups, including the ones that are not loaded yet, without loading them + idx_t GetRowGroupCountWithoutLoading() const; Allocator &GetAllocator() const; void Initialize(PersistentCollectionData &data); diff --git a/src/duckdb/src/include/duckdb/storage/table/row_group_reorderer.hpp b/src/duckdb/src/include/duckdb/storage/table/row_group_reorderer.hpp index 822917336..f59745aae 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_group_reorderer.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_group_reorderer.hpp @@ -34,7 +34,7 @@ class RowGroupReorderer { static OffsetPruningResult GetOffsetAfterPruning(OrderByStatistics order_by, OrderByColumnType column_type, OrderType order_type, OrderByNullType null_order, const StorageIndex &column_idx, idx_t row_offset, - vector &stats); + vector &stats, bool has_secondary_order); private: const RowGroupOrderOptions options; diff --git a/src/duckdb/src/include/duckdb/storage/table/row_group_segment_tree.hpp b/src/duckdb/src/include/duckdb/storage/table/row_group_segment_tree.hpp index 26562fc29..4ee4713b0 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_group_segment_tree.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_group_segment_tree.hpp @@ -26,6 +26,8 @@ class RowGroupSegmentTree : public SegmentTree { MetaBlockPointer GetRootPointer() const { return root_pointer; } + //! The number of row groups, including the ones that are not loaded yet, without loading them + idx_t GetRowGroupCountWithoutLoading() const; protected: optional> LoadSegment() const override; diff --git a/src/duckdb/src/include/duckdb/storage/table/row_id_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/row_id_column_data.hpp index 63e61dbda..945732c89 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_id_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_id_column_data.hpp @@ -56,7 +56,7 @@ class RowIdColumnData : public ColumnData { void VisitBlockIds(BlockIdVisitor &visitor) const override; - unique_ptr CreateCheckpointState(const RowGroup &row_group, + unique_ptr CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) override; unique_ptr Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info, const BaseStatistics &old_stats) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/row_number_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/row_number_column_data.hpp index e56525cca..00bd280b0 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_number_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_number_column_data.hpp @@ -52,7 +52,7 @@ class RowNumberColumnData : public ColumnData { void VisitBlockIds(BlockIdVisitor &visitor) const override; - unique_ptr CreateCheckpointState(const RowGroup &row_group, + unique_ptr CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) override; unique_ptr Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info, const BaseStatistics &old_stats) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp b/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp index 97289a5af..49090ad84 100644 --- a/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp @@ -23,6 +23,8 @@ namespace duckdb { class AdaptiveFilter; +class BlockAllocator; +struct PrefetchState; class AsyncTask; class ColumnSegment; class LocalTableStorage; @@ -262,6 +264,33 @@ struct PreparedScanVector { void Reset(); }; +//! An unordered native scan range with its tree and exact row-group payload kept alive. +class RowGroupScanAssignment { + friend class CollectionScanState; + +public: + idx_t RowCount() const; + +private: + QueryContext context; + shared_ptr row_groups; + optional_ptr> row_group; + shared_ptr pinned_row_group; + idx_t vector_index = 0; + idx_t max_row_group_row = 0; +}; + +enum class TableScanSource { PERSISTENT, TRANSACTION_LOCAL }; + +//! A claimed table range with its source recorded by the storage claim. +struct TableScanAssignment { + TableScanAssignment() = default; + TableScanAssignment(const CollectionScanState &scan_state, TableScanSource source); + + RowGroupScanAssignment row_group; + TableScanSource source = TableScanSource::PERSISTENT; +}; + class CollectionScanState { public: explicit CollectionScanState(TableScanState &parent_p); @@ -319,6 +348,18 @@ class CollectionScanState { idx_t RemainingAssignmentRows() const; //! Initializes the column scans a claim deferred void InitializeColumnScans(); + //! Initializes a claimed range using its pinned payload, which may predate a checkpoint. + bool InitializeRowGroupScan(SegmentNode &node, shared_ptr payload, idx_t vector_offset, + idx_t end_row); + //! Captures an unprepared assignment without transferring decoding or filter state. + RowGroupScanAssignment GetAssignment() const; + //! Starts the assignment in this worker's scan state, rechecking its current filters. + bool SetAssignment(const RowGroupScanAssignment &assignment); + //! Whether this projection supports metadata-only assignment block discovery. + static bool SupportsAssignmentBlockDiscovery(const vector &column_ids, + const vector &types); + //! Collects assignment block handles and optionally prepares prefetch tasks. + void PrepareAssignmentBlocks(PrefetchState &blocks, vector> &tasks, bool prefetch); //! Processes the vector prepared by PrepareScanIO void ProcessPreparedScan(DuckTransaction &transaction, DataChunk &result); //! Drops the prepared row group and returns false when the current filters prune it @@ -387,6 +428,8 @@ class TableScanState { void InitializeColumnScans(); //! Rows scanned from persistent and transaction-local storage idx_t RowsScanned() const; + //! Starts a captured assignment in its source and releases the inactive collection's pins + bool StartAssignment(const TableScanAssignment &assignment, bool prefetch_attempted); //! Releases what the scans of both storages pin, for a state that is kept around between assignments void ReleasePins(); @@ -436,6 +479,7 @@ struct PrefetchState { ~PrefetchState(); void AddBlock(shared_ptr block); + optional_idx GetCachedShard(BlockAllocator &allocator); vector> blocks; }; diff --git a/src/duckdb/src/include/duckdb/storage/table/segment_tree.hpp b/src/duckdb/src/include/duckdb/storage/table/segment_tree.hpp index 9349682b5..d16e4d8a4 100644 --- a/src/duckdb/src/include/duckdb/storage/table/segment_tree.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/segment_tree.hpp @@ -156,6 +156,10 @@ class SegmentTree { LoadAllSegments(l); return nodes.size(); } + //! The number of segments that are loaded so far: unlike GetSegmentCount this does not load the other segments + idx_t GetLoadedSegmentCount(SegmentLock &l) const { + return nodes.size(); + } //! Gets a pointer to the nth segment. Negative numbers start from the back. optional_ptr> GetSegmentByIndex(int64_t index) const { auto l = Lock(); diff --git a/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp index c44ca73f3..48115a12b 100644 --- a/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/standard_column_data.hpp @@ -53,7 +53,7 @@ class StandardColumnData : public ColumnData { void VisitBlockIds(BlockIdVisitor &visitor) const override; - unique_ptr CreateCheckpointState(const RowGroup &row_group, + unique_ptr CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) override; unique_ptr Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info, const BaseStatistics &stats) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp index 118b77c72..f3c7902b5 100644 --- a/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/struct_column_data.hpp @@ -70,7 +70,7 @@ class StructColumnData : public ColumnData { void VisitBlockIds(BlockIdVisitor &visitor) const override; - unique_ptr CreateCheckpointState(const RowGroup &row_group, + unique_ptr CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) override; unique_ptr Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info, const BaseStatistics &old_stats) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/validity_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/validity_column_data.hpp index 7acc82d4c..b368855f1 100644 --- a/src/duckdb/src/include/duckdb/storage/table/validity_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/validity_column_data.hpp @@ -22,8 +22,16 @@ class ValidityColumnData : public ColumnData { optional_ptr parent); public: + //! Adapt mask-only validity decoding to the value vector produced by the parent column. + static void ScanValidity(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result); + static void ScanPartialValidity(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, + idx_t result_offset); + static void SelectValidity(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, Vector &result, + const SelectionVector &sel, idx_t sel_count, idx_t result_offset, + ScanVectorType scan_type); + void AppendData(ColumnAppendState &state, UnifiedVectorFormat &vdata, idx_t count) override; - unique_ptr CreateCheckpointState(const RowGroup &row_group, + unique_ptr CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) override; void Verify(RowGroup &parent) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp index 9a97ae0b5..29fadb778 100644 --- a/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/variant_column_data.hpp @@ -61,7 +61,7 @@ class VariantColumnData : public ColumnData { void VisitBlockIds(BlockIdVisitor &visitor) const override; - unique_ptr CreateCheckpointState(const RowGroup &row_group, + unique_ptr CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) override; unique_ptr Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info, const BaseStatistics &old_stats) override; diff --git a/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp b/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp index 51382548e..28c86fab6 100644 --- a/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp +++ b/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp @@ -36,8 +36,8 @@ struct CommitInfo { class DuckTransaction : public Transaction { public: - DuckTransaction(DuckTransactionManager &manager, ClientContext &context, transaction_t start_time, - SnapshotView view, idx_t catalog_version); + DuckTransaction(DuckTransactionManager &manager, Context &context, transaction_t start_time, SnapshotView view, + idx_t catalog_version); ~DuckTransaction() override; //! The start timestamp of this transaction @@ -72,7 +72,7 @@ class DuckTransaction : public Transaction { void SetModifications(DatabaseModificationType type) override; bool ShouldWriteToWAL(AttachedDatabase &db); - ErrorData PreFlushOptimisticBlocks(AttachedDatabase &db) noexcept; + ErrorData PreFlushOptimisticBlocks(ClientContext &context, AttachedDatabase &db) noexcept; //! Appends the local storage to the tables; with a WAL, the commit state records the optimistically written blocks ErrorData AppendLocalStorage(ClientContext &context, AttachedDatabase &db, unique_ptr &commit_state) noexcept; @@ -81,7 +81,7 @@ class DuckTransaction : public Transaction { unique_ptr &commit_state) noexcept; //! Commit the current transaction with the given commit identifier. Returns an error message if the transaction //! commit failed, or an empty string if the commit was successful - ErrorData Commit(AttachedDatabase &db, CommitInfo &commit_info, + ErrorData Commit(ClientContext &context, AttachedDatabase &db, CommitInfo &commit_info, unique_ptr commit_state) noexcept; //! Returns whether or not a commit of this transaction should trigger an automatic checkpoint bool AutomaticCheckpoint(AttachedDatabase &db, const UndoBufferProperties &properties); diff --git a/src/duckdb/src/include/duckdb/transaction/duck_transaction_manager.hpp b/src/duckdb/src/include/duckdb/transaction/duck_transaction_manager.hpp index 82bd4d417..0a7912cfc 100644 --- a/src/duckdb/src/include/duckdb/transaction/duck_transaction_manager.hpp +++ b/src/duckdb/src/include/duckdb/transaction/duck_transaction_manager.hpp @@ -42,11 +42,11 @@ class DuckTransactionManager : public TransactionManager { static DuckTransactionManager &Get(AttachedDatabase &db); //! Start a new transaction - Transaction &StartTransaction(ClientContext &context) override; + Transaction &StartTransaction(Context &context, MetaTransaction &meta_transaction) override; //! Commit the given transaction ErrorData CommitTransaction(ClientContext &context, Transaction &transaction) override; //! Rollback the given transaction - void RollbackTransaction(Transaction &transaction) override; + void RollbackTransaction(ClientContext &context, Transaction &transaction) override; void Checkpoint(ClientContext &context, bool force = false) override; diff --git a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp index 563f1eb9e..4ab935672 100644 --- a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp +++ b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp @@ -53,8 +53,6 @@ class LocalTableStorage : public enable_shared_from_this { ExpressionExecutor &default_executor); ~LocalTableStorage(); - Context &context; - reference table_ref; //! The DuckTableEntry visible to this transaction that references table_ref. //! Updated through the append path (InitializeAppend, Append, LocalMerge) and @@ -86,8 +84,8 @@ class LocalTableStorage : public enable_shared_from_this { void InitializeScan(const QueryContext &context, CollectionScanState &state, optional_ptr table_filters = nullptr); //! Write a new row group to disk (if possible) - void WriteNewRowGroup(idx_t flushed_row_group_idx); - void FlushBlocks(); + void WriteNewRowGroup(Context &context, idx_t flushed_row_group_idx); + void FlushBlocks(Context &context); //! Whether Flush() takes the bulk-append path for this storage: the append covers at least one //! full row group and there are no deletes. Only depends on transaction-local state, i.e. this //! can be decided before taking any locks. @@ -153,7 +151,7 @@ class LocalStorage { }; public: - explicit LocalStorage(Context &context, DuckTransaction &transaction); + explicit LocalStorage(DuckTransaction &transaction); static LocalStorage &Get(DuckTransaction &transaction); static LocalStorage &Get(ClientContext &context, AttachedDatabase &db); @@ -170,34 +168,37 @@ class LocalStorage { CollectionScanState &scan_state, bool initialize_columns = true); //! Begin appending to the local storage - void InitializeAppend(LocalAppendState &state, DataTable &table, DuckTableEntry &table_entry); + void InitializeAppend(Context &context, LocalAppendState &state, DataTable &table, DuckTableEntry &table_entry); //! Initialize the storage and its indexes, but no row groups. - void InitializeStorage(LocalAppendState &state, DataTable &table, DuckTableEntry &table_entry); + void InitializeStorage(Context &context, LocalAppendState &state, DataTable &table, DuckTableEntry &table_entry); //! Append a chunk to the local storage static void Append(LocalAppendState &state, DuckTableEntry &table_entry, DataChunk &table_chunk); //! Finish appending to the local storage static void FinalizeAppend(LocalAppendState &state); //! Merge a row group collection into the transaction-local storage - void LocalMerge(DataTable &table, DuckTableEntry &table_entry, OptimisticWriteCollection &collection); + void LocalMerge(Context &context, DataTable &table, DuckTableEntry &table_entry, + OptimisticWriteCollection &collection); //! Create an optimistic row group collection for this table. //! Returns the index into the optimistic_collections vector for newly created collection. - PhysicalIndex CreateOptimisticCollection(DataTable &table, unique_ptr collection); + PhysicalIndex CreateOptimisticCollection(Context &context, DataTable &table, + unique_ptr collection); //! Returns the optimistic row group collection corresponding to the index. - OptimisticWriteCollection &GetOptimisticCollection(DataTable &table, const PhysicalIndex collection_index); + OptimisticWriteCollection &GetOptimisticCollection(Context &context, DataTable &table, + const PhysicalIndex collection_index); //! Resets the optimistic row group collection corresponding to the index. - void ResetOptimisticCollection(DataTable &table, const PhysicalIndex collection_index); + void ResetOptimisticCollection(Context &context, DataTable &table, const PhysicalIndex collection_index); //! Returns the optimistic writer. - OptimisticDataWriter &GetOptimisticWriter(DataTable &table); + OptimisticDataWriter &GetOptimisticWriter(Context &context, DataTable &table); //! Delete a set of rows from the local storage - idx_t Delete(DataTable &table, DuckTableEntry &table_entry, Vector &row_ids, idx_t count); + idx_t Delete(Context &context, DataTable &table, DuckTableEntry &table_entry, Vector &row_ids, idx_t count); //! Update a set of rows in the local storage void Update(DataTable &table, DuckTableEntry &table_entry, Vector &row_ids, const vector &column_ids, DataChunk &data); //! Commits the local storage, writing it to the WAL and completing the commit - void Commit(optional_ptr commit_state); + void Commit(Context &context, optional_ptr commit_state); //! Rollback the local storage void Rollback(); @@ -221,32 +222,29 @@ class LocalStorage { DataChunk &chunk, ColumnFetchState &fetch_state); //! Returns true, if the local storage contains the row id. bool CanFetch(DataTable &table, const row_t row_id); - TableIndexList &GetIndexes(DataTable &table); + TableIndexList &GetIndexes(Context &context, DataTable &table); optional_ptr GetStorage(const DataTable &table); - void VerifyNewConstraint(DataTable &parent, const BoundConstraint &constraint); + void VerifyNewConstraint(Context &context, DataTable &parent, const BoundConstraint &constraint); - Context &GetContext() const { - return context; - } DuckTransaction &GetTransaction() const { return transaction; } - void FlushBulkAppendBlocksAndSync(AttachedDatabase &db); + void FlushBulkAppendBlocksAndSync(Context &context, AttachedDatabase &db); bool SyncedFlushedBlocks() const { return synced_flushed_blocks; } private: - Context &context; DuckTransaction &transaction; LocalTableManager table_manager; bool synced_flushed_blocks = false; private: //! Flushes the local rows into the shared table and indexes; invalidates the database if they cannot be restored - void Flush(DataTable &table, LocalTableStorage &storage, optional_ptr commit_state); + void Flush(Context &context, DataTable &table, LocalTableStorage &storage, + optional_ptr commit_state); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp b/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp index d3a9116f4..463f641c6 100644 --- a/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp +++ b/src/duckdb/src/include/duckdb/transaction/meta_transaction.hpp @@ -20,6 +20,7 @@ namespace duckdb { class AttachedDatabase; class ClientContext; +class DatabaseInstance; class SecretManager; class SecretStorage; struct DatabaseModificationType; @@ -39,19 +40,15 @@ struct TransactionReference { //! The MetaTransaction manages multiple transactions for different attached databases class MetaTransaction { public: - DUCKDB_API MetaTransaction(ClientContext &context, timestamp_t start_timestamp, - transaction_t global_transaction_id); + DUCKDB_API MetaTransaction(DatabaseInstance &db, timestamp_t start_timestamp, transaction_t global_transaction_id); DUCKDB_API ~MetaTransaction(); - ClientContext &context; //! The timestamp when the transaction started timestamp_t start_timestamp; //! The global identifier of the transaction transaction_t global_transaction_id; //! The validity checker of the transaction ValidChecker transaction_validity; - //! The active query number - atomic active_query; public: DUCKDB_API static MetaTransaction &Get(ClientContext &context); @@ -59,21 +56,19 @@ class MetaTransaction { return start_timestamp; } - Transaction &GetTransaction(AttachedDatabase &db); + //! The transaction for the database, started on behalf of the given context if it does not exist yet + Transaction &GetTransaction(ClientContext &context, AttachedDatabase &db); optional_ptr TryGetTransaction(AttachedDatabase &db); void RemoveTransaction(AttachedDatabase &db); - ErrorData Commit(); - void Rollback(); + ErrorData Commit(ClientContext &context); + void Rollback(ClientContext &context); // Finalize the transaction after a COMMIT of ROLLBACK. - void Finalize(); - - idx_t GetActiveQuery(); - void SetActiveQuery(transaction_t query_number); + void Finalize(ClientContext &context); void SetReadOnly(); bool IsReadOnly() const; - void ModifyDatabase(AttachedDatabase &db, DatabaseModificationType modification); + void ModifyDatabase(ClientContext &context, AttachedDatabase &db, DatabaseModificationType modification); optional_ptr ModifiedDatabase() { return modified_database; } diff --git a/src/duckdb/src/include/duckdb/transaction/transaction.hpp b/src/duckdb/src/include/duckdb/transaction/transaction.hpp index afa97acb0..292732ca7 100644 --- a/src/duckdb/src/include/duckdb/transaction/transaction.hpp +++ b/src/duckdb/src/include/duckdb/transaction/transaction.hpp @@ -22,6 +22,7 @@ class SchemaCatalogEntry; class AttachedDatabase; class ColumnData; class ClientContext; +class Context; class CatalogEntry; class DataTable; class DatabaseInstance; @@ -40,14 +41,10 @@ struct DatabaseModificationType; //! transaction class Transaction { public: - DUCKDB_API Transaction(TransactionManager &manager, ClientContext &context); + DUCKDB_API Transaction(TransactionManager &manager, Context &context); DUCKDB_API virtual ~Transaction(); TransactionManager &manager; - weak_ptr context; - //! The current active query for the transaction. Set to MAXIMUM_QUERY_ID if - //! no query is active. - atomic active_query; public: DUCKDB_API static Transaction &Get(ClientContext &context, AttachedDatabase &db); diff --git a/src/duckdb/src/include/duckdb/transaction/transaction_context.hpp b/src/duckdb/src/include/duckdb/transaction/transaction_context.hpp index 1d225b5e0..b9db70df7 100644 --- a/src/duckdb/src/include/duckdb/transaction/transaction_context.hpp +++ b/src/duckdb/src/include/duckdb/transaction/transaction_context.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/assert.hpp" +#include "duckdb/common/atomic.hpp" #include "duckdb/common/common.hpp" #include "duckdb/common/error_data.hpp" #include "duckdb/common/exception.hpp" @@ -75,6 +76,8 @@ class TransactionContext { bool auto_rollback = false; unique_ptr current_transaction; + //! The query number of the query currently running on this connection (MAXIMUM_QUERY_ID if none) + atomic active_query_id = MAXIMUM_QUERY_ID; ErrorData autocheckpoint_error; TransactionContext(const TransactionContext &) = delete; diff --git a/src/duckdb/src/include/duckdb/transaction/transaction_manager.hpp b/src/duckdb/src/include/duckdb/transaction/transaction_manager.hpp index c9bef2daf..59bf1e724 100644 --- a/src/duckdb/src/include/duckdb/transaction/transaction_manager.hpp +++ b/src/duckdb/src/include/duckdb/transaction/transaction_manager.hpp @@ -19,6 +19,8 @@ namespace duckdb { class AttachedDatabase; class ClientContext; +class Context; +class MetaTransaction; class Catalog; struct ClientLockWrapper; class DatabaseInstance; @@ -31,12 +33,12 @@ class TransactionManager { explicit TransactionManager(AttachedDatabase &db); virtual ~TransactionManager(); - //! Start a new transaction - virtual Transaction &StartTransaction(ClientContext &context) = 0; + //! Start a new transaction as part of the given meta transaction + virtual Transaction &StartTransaction(Context &context, MetaTransaction &meta_transaction) = 0; //! Commit the given transaction. Returns a non-empty error message on failure. virtual ErrorData CommitTransaction(ClientContext &context, Transaction &transaction) = 0; //! Rollback the given transaction - virtual void RollbackTransaction(Transaction &transaction) = 0; + virtual void RollbackTransaction(ClientContext &context, Transaction &transaction) = 0; virtual void Checkpoint(ClientContext &context, bool force = false) = 0; diff --git a/src/duckdb/src/include/duckdb/transaction/undo_buffer.hpp b/src/duckdb/src/include/duckdb/transaction/undo_buffer.hpp index 941ebe8c6..195024bd0 100644 --- a/src/duckdb/src/include/duckdb/transaction/undo_buffer.hpp +++ b/src/duckdb/src/include/duckdb/transaction/undo_buffer.hpp @@ -16,6 +16,7 @@ namespace duckdb { class BufferManager; class ClientContext; +class DatabaseInstance; class CommitDropState; class DuckTransaction; class StorageCommitState; @@ -46,7 +47,7 @@ class UndoBuffer { }; public: - explicit UndoBuffer(DuckTransaction &transaction, ClientContext &context); + explicit UndoBuffer(DuckTransaction &transaction, DatabaseInstance &db); //! Write a specified entry to the undo buffer UndoBufferReference CreateEntry(UndoFlags type, idx_t len); diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index c9e23c16a..bffcd9260 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -168,11 +168,11 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_error_info_set_text) (duckdb_v2_error_info_handle info, const char *text, idx_t text_length); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_id) - (duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char **param_names, + (duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char *const *param_names, const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_name) - (duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char **param_names, + (duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char *const *param_names, const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_factory_create_type_from_text) @@ -187,8 +187,8 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_instance_create) (duckdb_v2_environment_handle env, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_instance_create_with_options) - (duckdb_v2_environment_handle env, const char **option_names, const idx_t *option_names_lengths, - const char **option_values, const idx_t *option_values_lengths, idx_t option_count, + (duckdb_v2_environment_handle env, const char *const *option_names, const idx_t *option_names_lengths, + const char *const *option_values, const idx_t *option_values_lengths, idx_t option_count, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_instance_destroy)(duckdb_v2_instance_handle *instance); DUCKDB_V2_ERROR(*duckdb_v2_instance_detach) @@ -260,7 +260,7 @@ typedef struct { (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, duckdb_v2_schema_handle *out_schema, duckdb_v2_schema_handle *out_parameters, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_execute) - (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_statement_iterator_destroy)(duckdb_v2_statement_iterator_handle *iterator); @@ -323,7 +323,7 @@ typedef struct { (duckdb_v2_factory_handle factory, int16_t in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_struct) - (duckdb_v2_factory_handle factory, const char **names, const idx_t *names_lengths, + (duckdb_v2_factory_handle factory, const char *const *names, const idx_t *names_lengths, const duckdb_v2_value_handle *children, idx_t field_count, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_time) @@ -800,7 +800,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_instance_register_replacement_scan) (duckdb_v2_instance_handle instance, duckdb_v2_replacement_scan_handle scan, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_qname_create) - (const char **parts, const idx_t *parts_lengths, idx_t part_count, duckdb_v2_qname_handle *name, + (const char *const *parts, const idx_t *parts_lengths, idx_t part_count, duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_qname_destroy)(duckdb_v2_qname_handle *name); DUCKDB_V2_ERROR(*duckdb_v2_qname_equals) @@ -836,7 +836,7 @@ typedef struct { duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_collection) (duckdb_v2_replacement_scan_info_handle info, duckdb_v2_column_data_collection_handle collection, - const char **column_names, const idx_t *column_names_lengths, idx_t column_count, + const char *const *column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_replacement_scan_set_function_name) (duckdb_v2_replacement_scan_info_handle info, duckdb_v2_qname_handle name, duckdb_v2_error_info_handle *err); @@ -848,7 +848,7 @@ typedef struct { (duckdb_v2_arrow_exporter_handle exporter, duckdb_v2_data_chunk_handle *chunk, bool consume, bool flush, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_arrow_exporter_create) - (duckdb_v2_context_handle context, const duckdb_v2_logical_type_handle *types, const char **names, + (duckdb_v2_context_handle context, const duckdb_v2_logical_type_handle *types, const char *const *names, const idx_t *names_lengths, idx_t count, idx_t batch_size, duckdb_v2_arrow_exporter_handle *out_exporter, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_arrow_exporter_destroy)(duckdb_v2_arrow_exporter_handle *exporter); @@ -860,7 +860,7 @@ typedef struct { (duckdb_v2_arrow_importer_handle importer, struct ArrowArray *array, bool consume, bool flush, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_arrow_importer_create) - (duckdb_v2_context_handle context, struct ArrowSchema *schema, idx_t batch_size, + (duckdb_v2_context_handle context, const struct ArrowSchema *schema, idx_t batch_size, duckdb_v2_arrow_importer_handle *out_importer, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_arrow_importer_destroy)(duckdb_v2_arrow_importer_handle *importer); DUCKDB_V2_ERROR(*duckdb_v2_arrow_importer_get_schema) @@ -1072,9 +1072,9 @@ typedef struct { duckdb_v2_prepared_statement_handle *out_prepared, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_prepared_statement_destroy)(duckdb_v2_prepared_statement_handle *prepared); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_execute) - (duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, - const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, - duckdb_v2_error_info_handle *err); + (duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_reuses_plan) (duckdb_v2_prepared_statement_handle prepared, bool *out_reuses, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_table_description_destroy)(duckdb_v2_table_description_handle *desc); @@ -1282,11 +1282,11 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_arrow_result_wait) (duckdb_v2_arrow_result_handle result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_prepared_statement_execute_arrow) - (duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, - const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, - duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); + (duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_execute_arrow) - (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + (duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_set_stats_callback) @@ -1568,8 +1568,8 @@ typedef struct { (duckdb_v2_query_metrics_node_handle node, const char **name, idx_t *name_length, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_statement_add_collection) (duckdb_v2_sql_statement_handle statement, const char *name, idx_t name_length, - duckdb_v2_column_data_collection_handle collection, const char **column_names, const idx_t *column_names_lengths, - idx_t column_count, duckdb_v2_error_info_handle *err); + duckdb_v2_column_data_collection_handle collection, const char *const *column_names, + const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_add_virtual_column) (duckdb_v2_table_function_handle function, DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_metrics_get_bind_data) @@ -1599,6 +1599,56 @@ typedef struct { (duckdb_v2_stats_handle stats, duckdb_v2_value_handle *value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_stats_set_value) (duckdb_v2_stats_handle stats, duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_get_generic_property) + (duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, + duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_aggregate_function_set_generic_property) + (duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_get_generic_property) + (duckdb_v2_scalar_function_handle function, const char *name, idx_t name_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_set_generic_property) + (duckdb_v2_scalar_function_handle function, const char *name, idx_t name_length, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); + DUCKDB_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_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_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) + (duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, const char *key, idx_t key_length, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR (*duckdb_v2_object_cache_entry_destroy)(duckdb_v2_object_cache_entry_handle *entry); + DUCKDB_V2_ERROR(*duckdb_v2_object_cache_entry_get_data) + (duckdb_v2_object_cache_entry_handle entry, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_object_cache_get) + (duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, const char *key, idx_t key_length, + duckdb_v2_object_cache_entry_handle *entry, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_object_cache_get_or_create) + (duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, const char *key, idx_t key_length, + duckdb_v2_object_cache_create_callback_fn create, void *create_user_data, + duckdb_v2_object_cache_entry_handle *entry, duckdb_v2_error_info_handle *err); + 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_table_function_set_to_string_callback) + (duckdb_v2_table_function_handle function, duckdb_v2_table_function_to_string_callback_fn callback, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_to_string_get_bind_data) + (duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_to_string_get_user_data) + (duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_table_function_to_string_set) + (duckdb_v2_table_function_to_string_info_handle info, const char *key, idx_t key_length, const char *value, + idx_t value_length, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_instance_open_shared) + (duckdb_v2_environment_handle env, const char *path, idx_t path_length, const char *const *option_names, + const idx_t *option_names_lengths, const char *const *option_values, const idx_t *option_values_lengths, + idx_t option_count, duckdb_v2_instance_init_callback_fn init, void *init_user_data, + duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -3652,6 +3702,62 @@ typedef struct { #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_stats_set_value duckdb_ext_api.duckdb_v2_stats_set_value #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_aggregate_function_get_generic_property \ + duckdb_ext_api.duckdb_v2_aggregate_function_get_generic_property +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_aggregate_function_set_generic_property \ + duckdb_ext_api.duckdb_v2_aggregate_function_set_generic_property +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_scalar_function_get_generic_property duckdb_ext_api.duckdb_v2_scalar_function_get_generic_property +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_scalar_function_set_generic_property duckdb_ext_api.duckdb_v2_scalar_function_set_generic_property +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#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_context_get_object_cache duckdb_ext_api.duckdb_v2_context_get_object_cache +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_instance_get_object_cache duckdb_ext_api.duckdb_v2_instance_get_object_cache +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_object_cache_delete duckdb_ext_api.duckdb_v2_object_cache_delete +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_object_cache_entry_destroy duckdb_ext_api.duckdb_v2_object_cache_entry_destroy +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_object_cache_entry_get_data duckdb_ext_api.duckdb_v2_object_cache_entry_get_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_object_cache_get duckdb_ext_api.duckdb_v2_object_cache_get +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_object_cache_get_or_create duckdb_ext_api.duckdb_v2_object_cache_get_or_create +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_object_cache_put duckdb_ext_api.duckdb_v2_object_cache_put +#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 +#define duckdb_v2_table_function_to_string_get_bind_data duckdb_ext_api.duckdb_v2_table_function_to_string_get_bind_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_to_string_get_user_data duckdb_ext_api.duckdb_v2_table_function_to_string_get_user_data +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_table_function_to_string_set duckdb_ext_api.duckdb_v2_table_function_to_string_set +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_instance_open_shared duckdb_ext_api.duckdb_v2_instance_open_shared +#endif // capigen:end appended #endif // DUCKDB_BUILD_STATIC_EXTENSION diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index c72c236a0..e3b53641c 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -3874,6 +3874,20 @@ typedef struct _duckdb_v2_attach_options { /* --- Function pointer typedefs for instance --- */ +/*! + * Initializes an instance that `duckdb_v2_instance_open_shared()` has just created, before the instance is shared: + * calls for the same file wait until it returns. It can, for instance, write GLOBAL settings that cannot be given at + * startup, or create a connection and run SQL that sets up the database. + * + * `err` is a live error slot, never NULL. Populate it with `duckdb_v2_error_info_set_code()` / + * `duckdb_v2_error_info_set_text()` to fail the initialization; do not destroy it. + * + * The callback must not throw or unwind across the boundary, and must not open the same file through + * `duckdb_v2_instance_open_shared()`, which would wait for the callback to return. + */ +typedef void (*duckdb_v2_instance_init_callback_fn)(duckdb_v2_instance_handle instance, void *user_data, + duckdb_v2_error_info_handle *err); + /* --- Functions for instance --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -3933,8 +3947,71 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_create(duckdb_v2_environment_han * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_create_with_options( - duckdb_v2_environment_handle env, const char **option_names, const idx_t *option_names_lengths, - const char **option_values, const idx_t *option_values_lengths, idx_t option_count, + duckdb_v2_environment_handle env, const char *const *option_names, const idx_t *option_names_lengths, + const char *const *option_values, const idx_t *option_values_lengths, idx_t option_count, + duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Opens the database file at `path` in an instance shared through the environment: a new handle to the instance that + * already has the file open, or else to a new instance, created with the startup options, with the file attached as its + * default database. + * + * Every call for the same file returns a new handle to the same instance, so connections created from any of them see + * the same database. The file is identified by its absolute path, as DuckDB resolves it. Destroy each handle via + * `duckdb_v2_instance_destroy()`; the instance is destroyed once the last handle and the last connection on it are, and + * a call for the same file meanwhile waits for it to be, rather than opening the file again while it is being closed. + * + * `init`, when given, is called once with the instance this call creates, before any other call can share it: calls for + * the same file wait until it returns. It is not called when the call shares an existing instance. When it reports an + * error, the instance is destroyed, the call fails with that error, and the next call for the file creates an instance + * again. + * + * An existing instance is shared only when it was created with the same startup options, compared by the settings they + * give: both name the same options, an alias counting as the option it stands for, and each value is equal once + * converted to the option's type, with text compared regardless of case, so that `threads=03` matches `threads=3` and + * `access_mode=read_only` matches `access_mode=READ_ONLY`. The value of an option DuckDB does not know is compared as + * written. Otherwise ERROR_RESOURCE_IN_USE is returned. `:memory:` or an empty view opens a new in-memory instance on + * every call, which is never shared; a named in-memory database such as `:memory:name` is shared like a file. The + * startup options are those of `duckdb_v2_instance_create_with_options()`, with the same restrictions. + * + * A file that an instance of the environment attached with `duckdb_v2_instance_attach()` is not shared, and opening it + * returns an error like a second `duckdb_v2_instance_attach()` would; nor can a file opened here be attached to another + * instance. `duckdb_v2_instance_attach()`, `duckdb_v2_instance_detach()` and `duckdb_v2_instance_set_default()` on a + * shared handle change the instance for every handle to it. + * + * A client cannot compose this from the other functions: telling that two paths name the same file as DuckDB resolves + * it, waiting for an instance whose last handle and connection were just destroyed to finish closing its files, and + * initializing a new instance before another call can share it, all need the engine. + * + * history: + * - unstable: v2.0.0 + * + * @param env The environment the instance is shared through. + * @param path Path to the database file, or `:memory:` / an empty view for a new in-memory database. + * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this + * is 0. + * @param option_names Optional. An array of option_count option names (canonical or alias). Pass NULL when option_count + * is 0. + * @param option_names_lengths Byte lengths of the entries in `option_names`; element i is the length of + * `option_names[i]`. May be NULL only when `option_names` is NULL. + * @param option_values Optional. An array of option_count values, parallel to option_names, in the textual form SQL + * `SET` accepts. Pass NULL when option_count is 0. + * @param option_values_lengths Byte lengths of the entries in `option_values`; element i is the length of + * `option_values[i]`. May be NULL only when `option_values` is NULL. + * @param option_count The number of startup options. + * @param init Optional. Initializes the instance when this call creates it. Pass NULL for none. + * @param init_user_data Opaque pointer passed through to `init` untouched. May be NULL. + * @param out_instance Receives a new handle to the shared instance. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_open_shared( + duckdb_v2_environment_handle env, const char *path, idx_t path_length, const char *const *option_names, + const idx_t *option_names_lengths, const char *const *option_values, const idx_t *option_values_lengths, + idx_t option_count, duckdb_v2_instance_init_callback_fn init, void *init_user_data, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err); #endif @@ -4263,6 +4340,251 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_log(duckdb_v2_connection_handl /* --- Struct definitions for logging --- */ +/* ============================================================================ + * MODULE: object cache + * ============================================================================ */ + +/* --- Enums for object cache --- */ + +/* --- Struct forward declarations for object cache --- */ + +/* --- Types for object cache --- */ + +/*! + * A borrowed opaque handle to the object cache of an instance. Obtained from `duckdb_v2_instance_get_object_cache()` or + * `duckdb_v2_context_get_object_cache()`, valid for as long as the instance is, and never destroyed by the caller. + */ +typedef struct _duckdb_v2_object_cache { + void *internal_ptr; +} * duckdb_v2_object_cache_handle; + +/*! + * An owned opaque handle to an entry of an object cache. Obtained from `duckdb_v2_object_cache_get()` or + * `duckdb_v2_object_cache_get_or_create()`, and destroyed with `duckdb_v2_object_cache_entry_destroy()`. Holding the + * handle keeps the entry's data alive, but not in the cache: the cache may still evict, replace or delete the entry + * meanwhile, and the data is only destroyed once the last handle is. Only entries in the cache count against the memory + * limit: data that is held through a handle after its entry was evicted, replaced or deleted no longer does. + */ +typedef struct _duckdb_v2_object_cache_entry { + void *internal_ptr; +} * duckdb_v2_object_cache_entry_handle; + +/* --- Constants for object cache --- */ + +/* --- Function pointer typedefs for object cache --- */ + +/*! + * Creates the data of a cache entry that does not exist yet. + * + * Runs outside the cache lock, while other calls creating the same entry on the same instance wait for it: it must not + * use the object cache itself. Calls for other keys, or on other instances, do not wait. A failure reported through + * `err` leaves the entry uncreated and fails the call, as does a `size_bytes` above the cache capacity; the waiting + * calls then retry, running their own create callback. + */ +typedef void (*duckdb_v2_object_cache_create_callback_fn)(void *user_data, duckdb_v2_opaque *data, idx_t *size_bytes, + duckdb_v2_error_info_handle *err); + +/* --- Functions for object cache --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Borrows the object cache of an instance. + * + * The returned handle is borrowed: it is valid only for as long as the instance is, and must not be destroyed. + * + * history: + * - unstable: v2.0.0 + * + * @param instance The instance to take the object cache from. + * @param cache Receives the borrowed object cache. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_get_object_cache(duckdb_v2_instance_handle instance, + duckdb_v2_object_cache_handle *cache, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Borrows the object cache of the instance a context belongs to. + * + * The returned handle is borrowed: it is valid only for as long as the instance is, and must not be destroyed. + * + * history: + * - unstable: v2.0.0 + * + * @param context The context to take the object cache from. + * @param cache Receives the borrowed object cache. + * @param err Optional. On failure, receives an opaque 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_object_cache(duckdb_v2_context_handle context, + duckdb_v2_object_cache_handle *cache, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Puts an entry into the cache, replacing the entry of the same type and key, if any. + * + * Entries are looked up by type and key together, so a key only has to be unique within its type. Name types after the + * extension, e.g. `my_extension.footer`, as the cache is shared by everything on the instance. + * + * The opaque handle bundles the data with an optional destructor, invoked once the entry is gone from the cache and + * nobody holds it any longer. If the call fails, the destructor is invoked right away. The destructor may run on any + * thread, possibly while the cache is locked, so it must not use the object cache itself. A `size_bytes` of 0 pins the + * entry for as long as it is not deleted or replaced, and the instance lives. Any other value makes it evictable: the + * cache counts it against the memory limit while it is in the cache, and may drop it, least recently used first, when + * memory is needed, also while it is held. Sizes above the cache capacity are rejected. + * + * history: + * - unstable: v2.0.0 + * + * @param cache The cache to put the entry into. + * @param type The type of the entry. Borrowed and copied. + * @param type_length The length of `type` in bytes. `type` need not be null-terminated and may be NULL only when this + * is 0. + * @param key The key of the entry. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param data Opaque handle bundling the data pointer plus an optional destructor. Owned by the cache from here on, + * even if the call fails. + * @param size_bytes The approximate memory the data takes up, or 0 to pin the entry. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API 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); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Looks an entry up, marking it as recently used. + * + * `entry` receives null if the cache has no entry of the type under the key, because there never was one or it was + * evicted. Otherwise the caller owns it, and must destroy it via `duckdb_v2_object_cache_entry_destroy()`. + * + * history: + * - unstable: v2.0.0 + * + * @param cache The cache to look the entry up in. + * @param type The type of the entry. Borrowed for the duration of the call. + * @param type_length The length of `type` in bytes. `type` need not be null-terminated and may be NULL only when this + * is 0. + * @param key The key of the entry. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param entry Receives the entry, or null if there is none. 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_object_cache_get(duckdb_v2_object_cache_handle cache, const char *type, + idx_t type_length, const char *key, idx_t key_length, + duckdb_v2_object_cache_entry_handle *entry, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Looks an entry up, creating it first with the create callback if there is none. + * + * Creation is atomic: of several threads racing for the same entry, one runs the create callback and the others wait + * for it and receive its result. If that creation fails, the call that ran it fails, and each waiting call tries again + * with its own create callback. Calls for other keys never wait for a creation. The entry is returned as + * `duckdb_v2_object_cache_get()` does, owned by the caller. Fails if the key holds an entry that was not created + * through this API. + * + * history: + * - unstable: v2.0.0 + * + * @param cache The cache to look the entry up in. + * @param type The type of the entry. Borrowed for the duration of the call. + * @param type_length The length of `type` in bytes. `type` need not be null-terminated and may be NULL only when this + * is 0. + * @param key The key of the entry. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param create Creates the data of the entry if there is none yet. + * @param create_user_data Handed to the create callback. Borrowed for the duration of the call. + * @param entry Receives the entry. 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_object_cache_get_or_create(duckdb_v2_object_cache_handle cache, const char *type, + idx_t type_length, const char *key, idx_t key_length, + duckdb_v2_object_cache_create_callback_fn create, + void *create_user_data, + duckdb_v2_object_cache_entry_handle *entry, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Deletes an entry from the cache. Deleting an entry that is not there is not an error. + * + * Holders of the entry keep its data until they destroy their handle, but from here on it no longer counts against the + * memory limit. + * + * history: + * - unstable: v2.0.0 + * + * @param cache The cache to delete the entry from. + * @param type The type of the entry. Borrowed for the duration of the call. + * @param type_length The length of `type` in bytes. `type` need not be null-terminated and may be NULL only when this + * is 0. + * @param key The key of the entry. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_object_cache_delete(duckdb_v2_object_cache_handle cache, const char *type, + idx_t type_length, const char *key, idx_t key_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the data pointer of an entry, valid for as long as the entry handle is. + * + * history: + * - unstable: v2.0.0 + * + * @param entry The entry to take the data of. + * @param data Receives the data pointer. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_object_cache_entry_get_data(duckdb_v2_object_cache_entry_handle entry, + void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Destroys the entry handle, releasing its hold on the data. Always succeeds. On success the handle is set to null. + * Safe to call on an already-null slot. + * + * history: + * - unstable: v2.0.0 + * + * @param entry The entry handle to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_object_cache_entry_destroy(duckdb_v2_object_cache_entry_handle *entry); +#endif + +/* --- Struct definitions for object cache --- */ + /* ============================================================================ * MODULE: qname * ============================================================================ */ @@ -4335,8 +4657,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_parse(const char *text, idx_t text_ * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_create(const char **parts, const idx_t *parts_lengths, idx_t part_count, - duckdb_v2_qname_handle *name, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_qname_create(const char *const *parts, const idx_t *parts_lengths, + idx_t part_count, duckdb_v2_qname_handle *name, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -5528,6 +5851,55 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_property(duckdb_v2 duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets a generic, named property on the aggregate function. + * + * Generic properties are free-form `name = value` pairs that the engine or extensions can read from a function, e.g. + * `duckdb.collation.combinable = true` marks a collation function as combinable. Setting a property that is already set + * replaces its value. Reading a property that is not set yields NULL, which boolean properties treat as false. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the property of. + * @param name The name of the property, e.g. `duckdb.collation.combinable`. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param value The value of the property. Borrowed (copied in). + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_generic_property( + duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Reads a generic, named property of the aggregate function, as set by + * `duckdb_v2_aggregate_function_set_generic_property()`. + * + * A property that is not set is not an error: `out_value` then receives NULL. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to read the property of. + * @param name The name of the property, e.g. `duckdb.collation.combinable`. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param out_value Receives the value of the property, owned by the caller, or NULL if the property is not set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_get_generic_property( + duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, + duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Sets the optional bind callback of the aggregate function. @@ -9608,6 +9980,9 @@ typedef enum DUCKDB_V2_LOGICAL_TYPE_ID { //! Geometry (spatial extension). DUCKDB_V2_LOGICAL_TYPE_ID_GEOMETRY = 60, + + //! Geography (spatial extension); like GEOMETRY, but with spherical edges. + DUCKDB_V2_LOGICAL_TYPE_ID_GEOGRAPHY = 61, DUCKDB_V2_LOGICAL_TYPE_ID_STRUCT = 100, DUCKDB_V2_LOGICAL_TYPE_ID_LIST = 101, DUCKDB_V2_LOGICAL_TYPE_ID_MAP = 102, @@ -9651,8 +10026,8 @@ typedef enum DUCKDB_V2_LOGICAL_TYPE_ID { * parameter. Parameters are (name, value) pairs in two parallel arrays, exactly as for factory_create_type_from_name. * * Returns ERROR_INPUT_INVALID when param_count is 0 and the id needs parameters (DECIMAL, LIST, STRUCT, TUPLE, MAP, - * ARRAY, UNION, ENUM, VARIANT, GEOMETRY), for the bind-time-only ids (SQLNULL, UNKNOWN), for TYPE — construct that via - * factory_create_type_from_text — and for INVALID. + * ARRAY, UNION, ENUM, VARIANT, GEOMETRY, GEOGRAPHY), for the bind-time-only ids (SQLNULL, UNKNOWN), for TYPE — + * construct that via factory_create_type_from_text — and for INVALID. * * history: * - unstable: v2.0.0 @@ -9670,7 +10045,7 @@ typedef enum DUCKDB_V2_LOGICAL_TYPE_ID { * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id( - duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char **param_names, + duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char *const *param_names, const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); #endif @@ -9721,7 +10096,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id( * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_name( - duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char **param_names, + duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char *const *param_names, const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); #endif @@ -9898,8 +10273,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_to_text(duckdb_v2_logical_ty * The inspection dual of create_type_from_name: these are the parameters that reconstruct the type through it. Per * kind: DECIMAL 2 (width, scale); LIST 1 (element type); ARRAY 2 (element type, size); MAP 2 (key type, value type); * STRUCT and TUPLE one per field; UNION one per member; ENUM one per dictionary entry; VARCHAR 1 when a collation is - * set, else 0; GEOMETRY 1 when a coordinate system is set, else 0; everything else 0. A bound type reports only what it - * actually carries, so a bind-time modifier that is not retained — an ignored VARCHAR length, say — does not reappear. + * set, else 0; GEOMETRY and GEOGRAPHY 1 when a coordinate system is set, else 0; everything else 0. A bound type + * reports only what it actually carries, so a bind-time modifier that is not retained — an ignored VARCHAR length, say + * — does not reappear. * * history: * - unstable: v2.0.0 @@ -10771,7 +11147,8 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_add_named_argument(duckd */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_collection( duckdb_v2_replacement_scan_info_handle info, duckdb_v2_column_data_collection_handle collection, - const char **column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); + const char *const *column_names, const idx_t *column_names_lengths, idx_t column_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -11065,6 +11442,30 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_name(duckdb_v2_scalar duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the schema of the system catalog that the scalar function is registered in. + * + * The schema is borrowed and copied. Calling this again replaces the previous schema. Without a schema the function is + * registered in the default schema. The schema must exist when the function is registered, e.g. `collations`, whose + * functions are the string collations of the database. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the schema of. + * @param schema The name of the schema. Borrowed and copied. + * @param schema_length The length of `schema` in bytes. `schema` must be valid UTF-8, need not be null-terminated, and + * may be NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_schema(duckdb_v2_scalar_function_handle function, + const char *schema, idx_t schema_length, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Returns the documentation of the function so it can be filled in. @@ -11157,6 +11558,56 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_property(duckdb_v2_sc duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets a generic, named property on the scalar function. + * + * Generic properties are free-form `name = value` pairs that the engine or extensions can read from a function, e.g. + * `duckdb.collation.combinable = true` marks a collation function as combinable. Setting a property that is already set + * replaces its value. Reading a property that is not set yields NULL, which boolean properties treat as false. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the property of. + * @param name The name of the property, e.g. `duckdb.collation.combinable`. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param value The value of the property. Borrowed (copied in). + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_generic_property(duckdb_v2_scalar_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Reads a generic, named property of the scalar function, as set by `duckdb_v2_scalar_function_set_generic_property()`. + * + * A property that is not set is not an error: `out_value` then receives NULL. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to read the property of. + * @param name The name of the property, e.g. `duckdb.collation.combinable`. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param out_value Receives the value of the property, owned by the caller, or NULL if the property is not set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_get_generic_property(duckdb_v2_scalar_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Sets the optional resolve types callback of the scalar function. @@ -11887,7 +12338,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_bind(duckdb_v2_connection_handl DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_add_collection(duckdb_v2_sql_statement_handle statement, const char *name, idx_t name_length, duckdb_v2_column_data_collection_handle collection, - const char **column_names, + const char *const *column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err); #endif @@ -12759,9 +13210,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_create(duckdb_v2_conne * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute( - duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, - const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, - duckdb_v2_error_info_handle *err); + duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -12914,7 +13365,7 @@ typedef enum DUCKDB_V2_RESULT_STEP_STATUS { * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute( - duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif @@ -13331,6 +13782,15 @@ typedef struct _duckdb_v2_table_function_get_bind_info_info { void *internal_ptr; } * duckdb_v2_table_function_get_bind_info_info_handle; +/*! + * A borrowed opaque handle to the arguments supplied to a table function when the engine describes a bound call of it + * in a query plan, e.g. for `EXPLAIN`. The "to string" callback receives this handle and can use it to report the + * key-value pairs the plan shows for the scan. + */ +typedef struct _duckdb_v2_table_function_to_string_info { + void *internal_ptr; +} * duckdb_v2_table_function_to_string_info_handle; + /*! * An owned opaque handle to a multi-file table function being built. A multi-file function wraps an already registered * table function that reads a single file, and adds everything that is needed to read many files at once on top of it: @@ -13397,6 +13857,9 @@ typedef void (*duckdb_v2_table_function_stats_callback_fn)(duckdb_v2_table_funct duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err); +typedef void (*duckdb_v2_table_function_to_string_callback_fn)(duckdb_v2_table_function_to_string_info_handle info, + duckdb_v2_error_info_handle *err); + /* --- Functions for table --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -15266,6 +15729,98 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_set_option( duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the optional "to string" callback of the table function. + * + * The engine invokes the callback with the bind data of a bound call when it renders a query plan that scans the + * function, e.g. for `EXPLAIN`, `EXPLAIN ANALYZE` and the profiler, both for the logical and for the physical plan. The + * callback reports what the plan shows for the scan as key-value pairs with `duckdb_v2_table_function_to_string_set()`, + * e.g. the file or the remote table it reads. Without the callback the physical plan shows the name of the function + * under the key `Function`; with it, the plan shows what the callback reports instead, so a callback that wants the + * name shown reports it itself. The engine shows the projections, filters and estimated cardinality of the scan next to + * them either way. The callback may be invoked more than once for the same bind data, and is not invoked with the + * global state of a scan, so it should only report what the bind already determined. A function wrapped in a multi-file + * function is not asked: the plan describes the multi-file scan. + * + * With profiling enabled (including `EXPLAIN ANALYZE`), the engine also invokes the callback while the query executes, + * once per worker thread that scans the function. Calls can therefore run concurrently with the same bind data and user + * data, so the callback must not modify them without synchronization, and an error it reports there fails the query. + * Builds with assertions enabled also invoke it while executing queries without profiling. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the callback of. + * @param callback The "to string" callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_to_string_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_to_string_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * + * history: + * - unstable: v2.0.0 + * + * @param info The to string info handle. + * @param data Receives the user data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_get_user_data( + duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the bind data the function's bind callback set for the bound call being described. + * + * history: + * - unstable: v2.0.0 + * + * @param info The to string info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_get_bind_data( + duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Reports a key-value pair the query plan shows for the scan, e.g. `File` and the path of the file it reads. The plan + * shows the pairs in the order they were first reported; setting a key again replaces its value in place. Fails with + * `ERROR_INPUT_INVALID` when the key is empty. + * + * history: + * - unstable: v2.0.0 + * + * @param info The to string info handle. + * @param key The key. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated. + * @param value The value. Borrowed and copied. May span several lines. + * @param value_length The length of `value` in bytes. `value` need not be null-terminated and may be NULL only when + * this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_set(duckdb_v2_table_function_to_string_info_handle info, + const char *key, idx_t key_length, + const char *value, idx_t value_length, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Creates a new multi-file function through a factory. @@ -16678,10 +17233,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_interval(duckdb_v2_factory_h * * The value is scaled by 10^scale, so (18500, 18, 3) is 18.500. width is the total digit count and must be 1..255, the * range of the uint8_t parameter; scale is the number of digits after the point and must not exceed width. Violating - * either returns ERROR_INPUT_INVALID, as does a value too wide for the storage tier the width selects. Widths above 38 - * build a wide decimal stored as BIGNUM, for which the 128-bit backing integer always fits. The value itself is not - * range-checked against the width; value_cast is the validating path, and the one that reaches decimals wider than 255 - * digits. + * either returns ERROR_INPUT_INVALID, as does a value that does not fit in width digits. Widths above 38 build a wide + * decimal stored as BIGNUM, for which the 128-bit backing integer always fits. value_cast reaches decimals wider than + * 255 digits. * * history: * - unstable: v2.0.0 @@ -16851,7 +17405,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_array(duckdb_v2_factory_hand * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, const char **names, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, const char *const *names, const idx_t *names_lengths, const duckdb_v2_value_handle *children, idx_t field_count, duckdb_v2_value_handle *out_value, @@ -17145,7 +17699,7 @@ typedef struct _duckdb_v2_arrow_result { * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_importer_create(duckdb_v2_context_handle context, - struct ArrowSchema *schema, idx_t batch_size, + const struct ArrowSchema *schema, idx_t batch_size, duckdb_v2_arrow_importer_handle *out_importer, duckdb_v2_error_info_handle *err); #endif @@ -17299,7 +17853,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_importer_destroy(duckdb_v2_arrow_im */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_create(duckdb_v2_context_handle context, const duckdb_v2_logical_type_handle *types, - const char **names, const idx_t *names_lengths, + const char *const *names, const idx_t *names_lengths, idx_t count, idx_t batch_size, duckdb_v2_arrow_exporter_handle *out_exporter, duckdb_v2_error_info_handle *err); @@ -17430,7 +17984,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_destroy(duckdb_v2_arrow_ex * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow( - duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char **parameter_names, + duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif @@ -17457,9 +18011,9 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow( * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute_arrow( - duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, - const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, - duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); + duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE diff --git a/src/duckdb/src/logging/log_manager.cpp b/src/duckdb/src/logging/log_manager.cpp index 6ae3dc8fa..34b8abe9b 100644 --- a/src/duckdb/src/logging/log_manager.cpp +++ b/src/duckdb/src/logging/log_manager.cpp @@ -236,7 +236,7 @@ void LogManager::SetLogSinkInternal(DatabaseInstance &db, LogConfig &new_config, if (sink_name_to_lower == LogConfig::FILE_STORAGE_NAME) { auto &fs = FileSystem::GetFileSystem(db); - if (fs.SubSystemIsDisabled(LocalFileSystem().GetName())) { + if (fs.SubSystemIsDisabled("LocalFileSystem")) { throw InvalidConfigurationException("Can not enable file logging with the LocalFileSystem disabled"); } } diff --git a/src/duckdb/src/logging/log_sink.cpp b/src/duckdb/src/logging/log_sink.cpp index 4ddcb128d..39b1d0687 100644 --- a/src/duckdb/src/logging/log_sink.cpp +++ b/src/duckdb/src/logging/log_sink.cpp @@ -392,7 +392,7 @@ void FileLogSink::SetPaths(const string &base_path) { it.second.path.clear(); } - LocalFileSystem fs; + auto &fs = FileSystem::GetFileSystem(db); if (normalize_contexts) { tables[LoggingTargetTable::LOG_CONTEXTS].path = fs.JoinPath(base_path, "duckdb_log_contexts.csv"); tables[LoggingTargetTable::LOG_ENTRIES].path = fs.JoinPath(base_path, "duckdb_log_entries.csv"); diff --git a/src/duckdb/src/main/attached_database.cpp b/src/duckdb/src/main/attached_database.cpp index 833040a38..b8abd9e8e 100644 --- a/src/duckdb/src/main/attached_database.cpp +++ b/src/duckdb/src/main/attached_database.cpp @@ -207,10 +207,21 @@ AttachedDatabase::AttachedDatabase(DatabaseInstance &db, Catalog &catalog_p, Sto } AttachedDatabase::~AttachedDatabase() { - // FIXME: Theoretically, we should catch all places higher up the call stack where the - // FIXME: shared pointer goes out of scope and we need to invoke a checkpoint. - // FIXME: However, for now, we keep this to avoid unintentional behavior / oversights. - Close(DatabaseCloseAction::TRY_CHECKPOINT); + if (!is_closed && is_detached) { + // a reference held outside of a transaction outlived the detach + auto action = Exception::UncaughtException() ? DatabaseCloseAction::SKIP_CHECKPOINT : detach_close_action; + try { + Close(action); + } catch (std::exception &ex) { + ErrorData data(ex); + try { + DUCKDB_LOG_ERROR(db, "Silent exception in ~AttachedDatabase():\t" + data.Message()); + } catch (...) { // NOLINT + } + } catch (...) { // NOLINT + } + } + D_ASSERT(is_closed || Exception::UncaughtException()); } bool AttachedDatabase::IsSystem() const { @@ -267,7 +278,7 @@ Identifier AttachedDatabase::ExtractDatabaseName(const string &dbpath, FileSyste return Identifier(name); } -void AttachedDatabase::InvokeCloseIfLastReference(shared_ptr &attached_db, ClientContext &context) { +DatabaseCloseAction AttachedDatabase::GetDetachCloseAction(ClientContext &context) { auto close_action = DatabaseCloseAction::CHECKPOINT; auto checkpoint_on_detach = Settings::Get(context); if (checkpoint_on_detach == CheckpointOnDetach::ENABLED) { @@ -277,7 +288,24 @@ void AttachedDatabase::InvokeCloseIfLastReference(shared_ptr & } else if (!Settings::Get(context)) { close_action = DatabaseCloseAction::SKIP_CHECKPOINT; } + return close_action; +} + +void AttachedDatabase::MarkDetached(DatabaseCloseAction close_action) { + lock_guard guard(*close_lock); + if (is_detached) { + return; + } + is_detached = true; + detach_close_action = close_action; +} +void AttachedDatabase::InvokeCloseIfLastReference(shared_ptr &attached_db, ClientContext &context) { + InvokeCloseIfLastReference(attached_db, GetDetachCloseAction(context)); +} + +void AttachedDatabase::InvokeCloseIfLastReference(shared_ptr &attached_db, + DatabaseCloseAction close_action) { auto close_lock = attached_db->close_lock; { lock_guard guard(*close_lock); @@ -286,6 +314,9 @@ void AttachedDatabase::InvokeCloseIfLastReference(shared_ptr & return; } attached_db->is_closing = true; + if (attached_db->is_detached) { + close_action = attached_db->detach_close_action; + } } // use_count() is a relaxed load, so it doesn't order accesses through references dropped without close_lock. // Dropping a copy does (acq_rel decrement, never reaching zero); a fence would too, but TSan ignores fences. diff --git a/src/duckdb/src/main/buffered_data/buffered_data.cpp b/src/duckdb/src/main/buffered_data/buffered_data.cpp index a988b9b03..6a273b052 100644 --- a/src/duckdb/src/main/buffered_data/buffered_data.cpp +++ b/src/duckdb/src/main/buffered_data/buffered_data.cpp @@ -5,6 +5,8 @@ #include "duckdb/main/query_result.hpp" #include "duckdb/main/client_config.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/settings.hpp" +#include "duckdb/main/config.hpp" namespace duckdb { @@ -20,7 +22,8 @@ BufferedData::BufferedData(Type type, ClientContext &context_p, ResultLifetime l : type(type), context(context_p.shared_from_this()), // The setting has no lower bound. A buffer that can never admit a chunk blocks // every sink while empty, and the stream silently ends with zero rows - total_buffer_size(MaxValue(ClientConfig::GetConfig(context_p).max_streaming_buffer_size, 1)), + total_buffer_size(MaxValue( + DBConfig::ParseMemoryLimitOrMaximum(Settings::Get(context_p)), 1)), lifetime(lifetime), format_context(std::move(format_context_p)), format(FormatOrChunk(std::move(format_p))), format_state(format->InitGlobal(format_context)) { } diff --git a/src/duckdb/src/main/capi/v1/arrow-c.cpp b/src/duckdb/src/main/capi/v1/arrow-c.cpp index 5a84ffa78..b2d90728f 100644 --- a/src/duckdb/src/main/capi/v1/arrow-c.cpp +++ b/src/duckdb/src/main/capi/v1/arrow-c.cpp @@ -5,6 +5,13 @@ #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/main/capi/capi_internal.hpp" #include "duckdb/main/query_parameters.hpp" +#include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/expression/star_expression.hpp" +#include "duckdb/parser/parsed_data/create_view_info.hpp" +#include "duckdb/parser/query_node/select_node.hpp" +#include "duckdb/parser/statement/create_statement.hpp" +#include "duckdb/parser/statement/select_statement.hpp" +#include "duckdb/parser/tableref/table_function_ref.hpp" #include "fmt/format.h" using duckdb::ArrowConverter; @@ -494,16 +501,35 @@ duckdb_state Ingest(duckdb_connection connection, const char *table_name, struct if (!input) { return DuckDBError; } + // a CONNECT-ed connection routes a statement as its SQL text, which a statement built from parser nodes lacks + if (cconn->context->IsConnected()) { + return DuckDBError; + } + // construct the `arrow_scan(...)` function expression auto factory = duckdb::make_shared_ptr(*input); - cconn->TableFunction("arrow_scan", {}, {}, std::move(factory)) - ->CreateView(duckdb::Identifier(table_name), true, true); + auto scan = duckdb::make_uniq(); + scan->function = duckdb::make_uniq( + "arrow_scan", duckdb::vector>()); + scan->bind_info = std::move(factory); + // construct the `SELECT * FROM arrow_scan(...)` statement + auto node = duckdb::make_uniq(); + node->select_list.push_back(duckdb::make_uniq()); + node->from_table = std::move(scan); + auto select = duckdb::make_uniq(); + select->node = std::move(node); + // construct the `CREATE TEMP VIEW AS` statement using the select statement + auto info = duckdb::make_uniq(duckdb::QualifiedName( + duckdb::Identifier(), duckdb::Identifier::InvalidSchema(), duckdb::Identifier(table_name))); + info->query = std::move(select); + info->temporary = true; + info->on_conflict = duckdb::OnCreateConflict::REPLACE_ON_CONFLICT; + auto statement = duckdb::make_uniq(); + statement->info = std::move(info); + // Execute the CREATE VIEW + if (cconn->Query(std::move(statement))->HasError()) { + return DuckDBError; + } } catch (...) { // LCOV_EXCL_START - // Tried covering this in tests, but it proved harder than expected. At the time of writing: - // - Passing any name to `CreateView` worked without throwing an exception - // - Passing a null Arrow array worked without throwing an exception - // - Passing an invalid schema (without any columns) led to an InternalException with SIGABRT, which is meant to - // be un-catchable. This case likely needs to be handled gracefully within `arrow_scan`. - // Ref: https://discord.com/channels/909674491309850675/921100573732909107/1115230468699336785 return DuckDBError; } // LCOV_EXCL_STOP diff --git a/src/duckdb/src/main/capi/v1/catalog-c.cpp b/src/duckdb/src/main/capi/v1/catalog-c.cpp index 646ff6764..0ef5f302c 100644 --- a/src/duckdb/src/main/capi/v1/catalog-c.cpp +++ b/src/duckdb/src/main/capi/v1/catalog-c.cpp @@ -1,3 +1,4 @@ +#include "duckdb/planner/collation_binding.hpp" #include "duckdb/common/type_visitor.hpp" #include "duckdb/common/types.hpp" #include "duckdb/common/helper.hpp" @@ -17,6 +18,8 @@ struct CCatalogWrapper { struct CCatalogEntryWrapper { CatalogEntry &entry; + //! Set when the entry is the function implementing a collation: the entry is reported as that collation + string collation_name; CCatalogEntryWrapper(CatalogEntry &entry) : entry(entry) { } }; @@ -125,15 +128,25 @@ duckdb_catalog_entry duckdb_catalog_get_entry(duckdb_catalog catalog, duckdb_cli auto &catalog_ref = *reinterpret_cast(catalog); auto &context_ref = *reinterpret_cast(context); - auto entry = catalog_ref.catalog.GetEntry(context_ref.context, duckdb::CatalogTypeFromC(entry_type), - duckdb::Identifier(schema_name), duckdb::Identifier(entry_name), + auto type = duckdb::CatalogTypeFromC(entry_type); + duckdb::Identifier schema(schema_name); + if (type == duckdb::CatalogType::COLLATION_ENTRY) { + // a collation is the scalar function of the same name in the collation schema + type = duckdb::CatalogType::SCALAR_FUNCTION_ENTRY; + schema = duckdb::CollationFunctions::GetSchema(); + } + auto entry = catalog_ref.catalog.GetEntry(context_ref.context, type, schema, duckdb::Identifier(entry_name), duckdb::OnEntryNotFound::RETURN_NULL); if (!entry) { return nullptr; } - return reinterpret_cast(new duckdb::CCatalogEntryWrapper(*entry)); + auto wrapper = new duckdb::CCatalogEntryWrapper(*entry); + if (entry_type == DUCKDB_CATALOG_ENTRY_TYPE_COLLATION) { + wrapper->collation_name = entry_name; + } + return reinterpret_cast(wrapper); } //---------------------------------------------------------------------------------------------------------------------- @@ -146,6 +159,9 @@ duckdb_catalog_entry_type duckdb_catalog_entry_get_type(duckdb_catalog_entry ent } auto &entry_ref = *reinterpret_cast(entry); + if (!entry_ref.collation_name.empty()) { + return DUCKDB_CATALOG_ENTRY_TYPE_COLLATION; + } return duckdb::CatalogTypeToC(entry_ref.entry.type); } @@ -154,6 +170,9 @@ const char *duckdb_catalog_entry_get_name(duckdb_catalog_entry entry) { return nullptr; } auto &entry_ref = *reinterpret_cast(entry); + if (!entry_ref.collation_name.empty()) { + return entry_ref.collation_name.c_str(); + } return entry_ref.entry.name.c_str(); } diff --git a/src/duckdb/src/main/capi/v1/copy_function-c.cpp b/src/duckdb/src/main/capi/v1/copy_function-c.cpp index 9993bf9d1..811d7180b 100644 --- a/src/duckdb/src/main/capi/v1/copy_function-c.cpp +++ b/src/duckdb/src/main/capi/v1/copy_function-c.cpp @@ -300,12 +300,12 @@ struct CCopyToGlobalState : GlobalFunctionData { }; struct CCopyToGlobalInitInfo { - CCopyToGlobalInitInfo(ClientContext &context, FunctionData &bind_data, const string &file_path) + CCopyToGlobalInitInfo(ClientContext &context, const FunctionData &bind_data, const string &file_path) : context(context), bind_data(bind_data), file_path(file_path) { } ClientContext &context; - FunctionData &bind_data; + const FunctionData &bind_data; const string &file_path; string error; @@ -315,7 +315,7 @@ struct CCopyToGlobalInitInfo { duckdb_delete_callback_t delete_callback = nullptr; }; -unique_ptr CCopyToGlobalInit(ClientContext &context, FunctionData &bind_data, +unique_ptr CCopyToGlobalInit(ClientContext &context, const FunctionData &bind_data, const string &file_path) { auto &bind_info = bind_data.Cast(); auto &function_info = bind_info.function_info->Cast(); @@ -417,7 +417,7 @@ const char *duckdb_copy_function_global_init_get_file_path(duckdb_copy_function_ namespace duckdb { namespace { -unique_ptr CCopyToLocalInit(ExecutionContext &context, FunctionData &bind_data) { +unique_ptr CCopyToLocalInit(ExecutionContext &context, const FunctionData &bind_data) { // This isnt exposed to the C-API yet, so we just return empty local function data return make_uniq(); } @@ -431,18 +431,18 @@ namespace duckdb { namespace { struct CCopyToSinkInfo { - CCopyToSinkInfo(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate) + CCopyToSinkInfo(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate) : context(context), bind_data(bind_data), gstate(gstate) { } ClientContext &context; - FunctionData &bind_data; + const FunctionData &bind_data; GlobalFunctionData &gstate; string error; bool success = true; }; -void CCopyToSink(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +void CCopyToSink(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate, DataChunk &input) { auto &bind_info = bind_data.Cast(); auto &function_info = bind_info.function_info->Cast(); @@ -534,7 +534,7 @@ void *duckdb_copy_function_sink_get_global_state(duckdb_copy_function_sink_info namespace duckdb { namespace { -void CCopyToCombine(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +void CCopyToCombine(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate) { // Do nothing for now (this isnt exposed to the C-API yet) } @@ -549,19 +549,19 @@ namespace duckdb { namespace { struct CCopyToFinalizeInfo { - CCopyToFinalizeInfo(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate) + CCopyToFinalizeInfo(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate) : context(context), bind_data(bind_data), gstate(gstate) { } ClientContext &context; - FunctionData &bind_data; + const FunctionData &bind_data; GlobalFunctionData &gstate; string error; bool success = true; }; -void CCopyToFinalize(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate) { +void CCopyToFinalize(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate) { auto &bind_info = bind_data.Cast(); auto &function_info = bind_info.function_info->Cast(); diff --git a/src/duckdb/src/main/capi/v1/helper-c.cpp b/src/duckdb/src/main/capi/v1/helper-c.cpp index 43569a89c..cbfe0577a 100644 --- a/src/duckdb/src/main/capi/v1/helper-c.cpp +++ b/src/duckdb/src/main/capi/v1/helper-c.cpp @@ -112,6 +112,8 @@ LogicalTypeId LogicalTypeIdFromC(const duckdb_type type) { return LogicalTypeId::TIME_NS; case DUCKDB_TYPE_GEOMETRY: return LogicalTypeId::GEOMETRY; + case DUCKDB_TYPE_GEOGRAPHY: + return LogicalTypeId::GEOGRAPHY; case DUCKDB_TYPE_VARIANT: return LogicalTypeId::VARIANT; default: // LCOV_EXCL_START @@ -210,6 +212,8 @@ duckdb_type LogicalTypeIdToC(const LogicalTypeId type) { return DUCKDB_TYPE_TIME_NS; case LogicalTypeId::GEOMETRY: return DUCKDB_TYPE_GEOMETRY; + case LogicalTypeId::GEOGRAPHY: + return DUCKDB_TYPE_GEOGRAPHY; case LogicalTypeId::VARIANT: return DUCKDB_TYPE_VARIANT; default: // LCOV_EXCL_START diff --git a/src/duckdb/src/main/capi/v1/logical_types-c.cpp b/src/duckdb/src/main/capi/v1/logical_types-c.cpp index 21c09dede..574ebd30c 100644 --- a/src/duckdb/src/main/capi/v1/logical_types-c.cpp +++ b/src/duckdb/src/main/capi/v1/logical_types-c.cpp @@ -438,7 +438,8 @@ duckdb_state duckdb_register_logical_type(duckdb_connection connection, duckdb_l } char *duckdb_geometry_type_get_crs(duckdb_logical_type type) { - if (!AssertLogicalTypeId(type, duckdb::LogicalTypeId::GEOMETRY)) { + if (!AssertLogicalTypeId(type, duckdb::LogicalTypeId::GEOMETRY) && + !AssertLogicalTypeId(type, duckdb::LogicalTypeId::GEOGRAPHY)) { return nullptr; } auto &logical_type = *(reinterpret_cast(type)); diff --git a/src/duckdb/src/main/capi/v1/scalar_function-c.cpp b/src/duckdb/src/main/capi/v1/scalar_function-c.cpp index e66626616..2325ca3ab 100644 --- a/src/duckdb/src/main/capi/v1/scalar_function-c.cpp +++ b/src/duckdb/src/main/capi/v1/scalar_function-c.cpp @@ -89,13 +89,13 @@ struct CScalarFunctionLocalState : public FunctionLocalState { }; struct CScalarFunctionInternalInitInfo { - CScalarFunctionInternalInitInfo(ClientContext &context, CScalarFunctionBindData &bind_data, + CScalarFunctionInternalInitInfo(ClientContext &context, const CScalarFunctionBindData &bind_data, CScalarFunctionLocalState &local_state) : context(context), bind_data(bind_data), local_state(local_state) { } ClientContext &context; - CScalarFunctionBindData &bind_data; + const CScalarFunctionBindData &bind_data; CScalarFunctionLocalState &local_state; bool success = true; @@ -177,7 +177,7 @@ unique_ptr CScalarFunctionBind(BindScalarFunctionInput &input) { } unique_ptr CScalarFunctionInit(ExpressionState &state, const BoundFunctionExpression &expr, - FunctionData *bind_data) { + optional_ptr bind_data) { auto &function = expr.Function(); auto &info = function.GetExtraFunctionInfo().Cast(); D_ASSERT(info.function); diff --git a/src/duckdb/src/main/capi/v2/capi_v2.cpp b/src/duckdb/src/main/capi/v2/capi_v2.cpp index eeee4e7f4..9e33e35b0 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2.cpp @@ -403,7 +403,7 @@ static unique_ptr PopulateOptionFromCore(const ConfigurationOption &o out->name = option.name ? option.name : ""; out->description = option.description ? option.description : ""; PopulateOptionScopes(out, option); - if (!DBConfig::TryGetDefaultValue(&option, out->default_value)) { + if (!source.GetConfig().TryGetDefaultValue(&option, out->default_value)) { out->default_value = Value(); } out->aliases.clear(); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_arrow.cpp b/src/duckdb/src/main/capi/v2/capi_v2_arrow.cpp index e8f64b6c2..66b383f15 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_arrow.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_arrow.cpp @@ -359,7 +359,7 @@ using namespace duckdb::capiv2; // arrow_importer //---------------------------------------------------------------------------------------------------------------------- -DUCKDB_V2_ERROR duckdb_v2_arrow_importer_create(duckdb_v2_context_handle context, struct ArrowSchema *schema, +DUCKDB_V2_ERROR duckdb_v2_arrow_importer_create(duckdb_v2_context_handle context, const struct ArrowSchema *schema, idx_t batch_size, duckdb_v2_arrow_importer_handle *out_importer, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(context); @@ -495,7 +495,7 @@ DUCKDB_V2_ERROR duckdb_v2_arrow_importer_destroy(duckdb_v2_arrow_importer_handle //---------------------------------------------------------------------------------------------------------------------- DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_create(duckdb_v2_context_handle context, - const duckdb_v2_logical_type_handle *types, const char **names, + const duckdb_v2_logical_type_handle *types, const char *const *names, const idx_t *names_lengths, idx_t count, idx_t batch_size, duckdb_v2_arrow_exporter_handle *out_exporter, duckdb_v2_error_info_handle *err) { @@ -613,12 +613,10 @@ DUCKDB_V2_ERROR duckdb_v2_arrow_exporter_destroy(duckdb_v2_arrow_exporter_handle // arrow_result //---------------------------------------------------------------------------------------------------------------------- -DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow(duckdb_v2_connection_handle conn, - duckdb_v2_sql_statement_handle statement, - const char **parameter_names, const idx_t *parameter_names_lengths, - const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, - idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_statement_execute_arrow( + duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(out_result); *out_result = nullptr; DUCKDB_CHECK_ARG(conn); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_aggregate.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_aggregate.cpp index bef5544d8..7eff82d6b 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_aggregate.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_aggregate.cpp @@ -523,6 +523,29 @@ DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_property(duckdb_v2_aggregate_fu return WithErrorHandler(err, [&]() { SetAggregateFunctionProperty(Convert(function)->properties, key, value); }); } +DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_generic_property(duckdb_v2_aggregate_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_STR_ARG(name, name_length); + DUCKDB_CHECK_ARG(value); + return WithErrorHandler( + err, [&]() { SetGenericFunctionProperty(Convert(function)->properties, name, name_length, *Convert(value)); }); +} + +DUCKDB_V2_ERROR duckdb_v2_aggregate_function_get_generic_property(duckdb_v2_aggregate_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_STR_ARG(name, name_length); + DUCKDB_CHECK_ARG(out_value); + *out_value = nullptr; + return WithErrorHandler( + err, [&]() { *out_value = GetGenericFunctionProperty(Convert(function)->properties, name, name_length); }); +} + DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_bind_callback(duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_bind_callback_fn callback, duckdb_v2_error_info_handle *err) { diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp index 2bafecc30..5722794d4 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp @@ -393,7 +393,7 @@ static auto CV2CopyToBind(ClientContext &context, CopyFunctionBindInput &input, return std::move(result); } -static auto CV2CopyToBatchSize(ClientContext &context, FunctionData &bind_data) -> optional_idx { +static auto CV2CopyToBatchSize(ClientContext &context, const FunctionData &bind_data) -> optional_idx { const auto &info = GetFunctionInfo(bind_data); CV2CopyToBatchSizeInfo args = {}; @@ -414,7 +414,7 @@ static auto CV2CopyToBatchSize(ClientContext &context, FunctionData &bind_data) return args.out_target; } -static auto CV2CopyToInitGlobal(ClientContext &context, FunctionData &bind_data, const string &file_path) +static auto CV2CopyToInitGlobal(ClientContext &context, const FunctionData &bind_data, const string &file_path) -> unique_ptr { const auto &info = GetFunctionInfo(bind_data); @@ -443,7 +443,7 @@ static auto CV2CopyToInitGlobal(ClientContext &context, FunctionData &bind_data, return std::move(result); } -static auto CV2CopyToPrepareBatch(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +static auto CV2CopyToPrepareBatch(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, unique_ptr collection) -> unique_ptr { const auto &info = GetFunctionInfo(bind_data); @@ -470,7 +470,7 @@ static auto CV2CopyToPrepareBatch(ClientContext &context, FunctionData &bind_dat return std::move(result); } -static auto CV2CopyToFlushBatch(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +static auto CV2CopyToFlushBatch(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, PreparedBatchData &batch) -> void { const auto &info = GetFunctionInfo(bind_data); @@ -490,8 +490,8 @@ static auto CV2CopyToFlushBatch(ClientContext &context, FunctionData &bind_data, } } -static auto CV2CopyToReportStatistics(ClientContext &context, FunctionData &bind_data, CV2CopyToGlobalState &gstate) - -> void { +static auto CV2CopyToReportStatistics(ClientContext &context, const FunctionData &bind_data, + CV2CopyToGlobalState &gstate) -> void { const auto &info = GetFunctionInfo(bind_data); CV2CopyToStatisticsInfo args = {}; @@ -511,7 +511,8 @@ static auto CV2CopyToReportStatistics(ClientContext &context, FunctionData &bind gstate.written_statistics->file_size_bytes = args.out_file_size_bytes; } -static auto CV2CopyToFinalize(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate_p) -> void { +static auto CV2CopyToFinalize(ClientContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate_p) + -> void { const auto &info = GetFunctionInfo(bind_data); auto &gstate = gstate_p.Cast(); @@ -538,8 +539,8 @@ static auto CV2CopyToFinalize(ClientContext &context, FunctionData &bind_data, G } //! The engine asks where to report the statistics of a file right after creating it, before anything is written to it -static auto CV2CopyToGetWrittenStatistics(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, - CopyFunctionFileStatistics &statistics) -> void { +static auto CV2CopyToGetWrittenStatistics(ClientContext &context, const FunctionData &bind_data, + GlobalFunctionData &gstate, CopyFunctionFileStatistics &statistics) -> void { gstate.Cast().written_statistics = &statistics; } @@ -549,11 +550,12 @@ static auto CV2CopyToGetWrittenStatistics(ClientContext &context, FunctionData & // COPY TO itself drives the function through its batch interface. These hooks serve callers that write a file through // the copy function directly, sinking chunks into it one at a time - every chunk is written as a batch of its own. -static auto CV2CopyToInitLocal(ExecutionContext &context, FunctionData &bind_data) -> unique_ptr { +static auto CV2CopyToInitLocal(ExecutionContext &context, const FunctionData &bind_data) + -> unique_ptr { return make_uniq(); } -static auto CV2CopyToSink(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +static auto CV2CopyToSink(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate, DataChunk &input) -> void { if (input.size() == 0) { return; @@ -566,7 +568,7 @@ static auto CV2CopyToSink(ExecutionContext &context, FunctionData &bind_data, Gl CV2CopyToFlushBatch(context.client, bind_data, gstate, *prepared); } -static auto CV2CopyToCombine(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate, +static auto CV2CopyToCombine(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate) -> void { } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_properties.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_properties.cpp index 74a4134fe..1319a2ad1 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_properties.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_properties.cpp @@ -165,4 +165,25 @@ void SetAggregateFunctionProperty(AggregateFunctionProperties &props, DUCKDB_V2_ throw InvalidInputException("Function property key " + ToHex(AsU32(key)) + " is not valid for aggregate functions"); } +static auto GenericPropertyName(const char *name, idx_t name_length) -> string { + auto result = ConvertIdentifierName(name, name_length); + if (result.empty()) { + throw InvalidInputException("Function property name cannot be empty"); + } + return string(result); +} + +void SetGenericFunctionProperty(FunctionProperties &props, const char *name, idx_t name_length, const Value &value) { + props.SetProperty(GenericPropertyName(name, name_length), value); +} + +auto GetGenericFunctionProperty(const FunctionProperties &props, const char *name, idx_t name_length) + -> duckdb_v2_value_handle { + auto value = props.GetProperty(GenericPropertyName(name, name_length)); + if (!value) { + return nullptr; + } + return Convert(new Value(*value)); +} + } // namespace duckdb::capiv2 diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_scalar.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_scalar.cpp index 3780432ff..e6079fec3 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_scalar.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_scalar.cpp @@ -190,8 +190,8 @@ static auto CV2ScalarBind(BindScalarFunctionInput &input) -> unique_ptr unique_ptr { +static auto CV2ScalarInit(ExpressionState &state, const BoundFunctionExpression &expr, + optional_ptr bind_data) -> unique_ptr { const auto &info = expr.Function().GetExtraFunctionInfo().Cast(); auto user_bind_data = bind_data ? bind_data->Cast().handle : nullptr; @@ -348,6 +348,8 @@ class CV2ScalarFunction { CV2FunctionDocs docs; CV2ScalarFunctionInfo info; Identifier name; + //! The schema of the system catalog the function is registered in + Identifier schema = Identifier::DefaultSchema(); FunctionProperties properties; }; @@ -378,6 +380,19 @@ DUCKDB_V2_ERROR duckdb_v2_scalar_function_create(duckdb_v2_factory_handle factor }); } +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_CHECK_ARG(function); + DUCKDB_CHECK_STR_ARG(schema, schema_length); + return WithErrorHandler(err, [&]() { + auto name = ConvertIdentifierName(schema, schema_length); + if (name.empty()) { + throw duckdb::InvalidInputException("Schema name cannot be empty."); + } + Convert(function)->schema = duckdb::Identifier(name); + }); +} + DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_name(duckdb_v2_scalar_function_handle function, const char *name, idx_t name_length, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); @@ -420,6 +435,29 @@ DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_property(duckdb_v2_scalar_function return WithErrorHandler(err, [&]() { SetScalarFunctionProperty(Convert(function)->properties, key, value); }); } +DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_generic_property(duckdb_v2_scalar_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_STR_ARG(name, name_length); + DUCKDB_CHECK_ARG(value); + return WithErrorHandler( + err, [&]() { SetGenericFunctionProperty(Convert(function)->properties, name, name_length, *Convert(value)); }); +} + +DUCKDB_V2_ERROR duckdb_v2_scalar_function_get_generic_property(duckdb_v2_scalar_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + DUCKDB_CHECK_STR_ARG(name, name_length); + DUCKDB_CHECK_ARG(out_value); + *out_value = nullptr; + return WithErrorHandler( + err, [&]() { *out_value = GetGenericFunctionProperty(Convert(function)->properties, name, name_length); }); +} + DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_resolve_types_callback(duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_resolve_types_callback_fn callback, @@ -647,6 +685,8 @@ DUCKDB_V2_ERROR duckdb_v2_connection_register_scalar_function(duckdb_v2_connecti context.RunFunctionInTransaction([&]() { auto &self = *Convert(function); auto info = duckdb::CreateScalarFunctionInfo(self.Build(*context.db)); + info.SetQualifiedName( + duckdb::QualifiedName(info.GetQualifiedName().Catalog(), self.schema, info.GetFunctionName())); self.docs.AddTo(self.signature, info); info.on_conflict = duckdb::OnCreateConflict::ALTER_ON_CONFLICT; auto &catalog = duckdb::Catalog::GetSystemCatalog(context); @@ -664,6 +704,8 @@ DUCKDB_V2_ERROR duckdb_v2_extension_register_scalar_function(duckdb_v2_extension auto &self = *Convert(function); auto &loader = GetExtensionLoader(extension); duckdb::CreateScalarFunctionInfo info(self.Build(loader.GetDatabaseInstance())); + info.SetQualifiedName( + duckdb::QualifiedName(info.GetQualifiedName().Catalog(), self.schema, info.GetFunctionName())); self.docs.AddTo(self.signature, info); info.on_conflict = duckdb::OnCreateConflict::ALTER_ON_CONFLICT; loader.RegisterFunction(std::move(info)); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp index 5053d914c..c11174849 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp @@ -437,6 +437,7 @@ class CV2TableFunctionInfo : public TableFunctionInfo { duckdb_v2_table_function_claim_batch_callback_fn claim_batch_cb = nullptr; duckdb_v2_table_function_get_bind_info_callback_fn get_bind_info_cb = nullptr; duckdb_v2_table_function_metrics_callback_fn metrics_cb = nullptr; + duckdb_v2_table_function_to_string_callback_fn to_string_cb = nullptr; shared_ptr user_data = nullptr; bool projection_pushdown = false; //! Whether the function sees the filters of the scan: it has a filter pushdown callback and projection pushdown @@ -495,6 +496,44 @@ static auto CV2TableGetBindInfo(TableFunctionGetBindInfoInput &input) -> BindInf return std::move(args.out_bind_info); } +//! What the "to string" callback describes a bound call with in a query plan +class CV2TableToStringInfo { +public: + void *in_user_data = nullptr; + void *in_bind_data = nullptr; + + InsertionOrderPreservingMap out_entries; +}; + +static auto Convert(duckdb_v2_table_function_to_string_info_handle info) -> CV2TableToStringInfo * { + return reinterpret_cast(info); +} +static auto Convert(CV2TableToStringInfo *info) -> duckdb_v2_table_function_to_string_info_handle { + return reinterpret_cast(info); +} + +static auto CV2TableToString(TableFunctionToStringInput &input) -> InsertionOrderPreservingMap { + if (!input.bind_data) { + return InsertionOrderPreservingMap(); + } + const auto &bind_data = input.bind_data->Cast(); + const auto &info = *bind_data.info; + + CV2TableToStringInfo args; + args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + + CV2ErrorInfo err = {}; + auto err_ptr = Convert(&err); + info.to_string_cb(Convert(&args), &err_ptr); + + if (err.HasError()) { + err.ThrowAsException(); + } + + return std::move(args.out_entries); +} + static auto CV2TableBind(ClientContext &context, TableFunctionBindInput &input, vector &return_types, vector &names) -> unique_ptr { const auto &info = input.info->Cast(); @@ -901,7 +940,7 @@ static auto CV2TableExecBatch(ClientContext &context, TableFunctionInput &input, } // Nothing of this batch passed, but an empty chunk means that the batch is exhausted output.Reset(); - context.InterruptCheck(); + context.FastInterruptCheck(); } } @@ -1063,7 +1102,8 @@ static auto CV2TableGetFileRowNumberColumn(ClientContext &, optional_ptr bind_data_p, vector> &filters) -> void { if (filters.empty()) { return; @@ -1246,6 +1286,9 @@ class CV2TableFunction { if (info.get_bind_info_cb) { function.get_bind_info = CV2TableGetBindInfo; } + if (info.to_string_cb) { + function.to_string = CV2TableToString; + } // a function registered through the C API makes no stability promise unless one was declared function.stability = stability; @@ -2219,6 +2262,47 @@ duckdb_v2_table_function_get_bind_info_set_option(duckdb_v2_table_function_get_b }); } +//---------------------------------------------------------------------------------------------------------------------- +// To string +//---------------------------------------------------------------------------------------------------------------------- + +DUCKDB_V2_ERROR +duckdb_v2_table_function_set_to_string_callback(duckdb_v2_table_function_handle function, + duckdb_v2_table_function_to_string_callback_fn callback, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { Convert(function)->info.to_string_cb = callback; }); +} + +DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_get_user_data(duckdb_v2_table_function_to_string_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_get_bind_data(duckdb_v2_table_function_to_string_info_handle info, + void **data, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(info)->in_bind_data; }); +} + +DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_set(duckdb_v2_table_function_to_string_info_handle info, + const char *key, idx_t key_length, const char *value, + idx_t value_length, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_STR_ARG(value, value_length); + return WithErrorHandler(err, [&]() { + if (key_length == 0) { + throw duckdb::InvalidInputException("duckdb_v2_table_function_to_string_set: the key cannot be empty"); + } + Convert(info)->out_entries[duckdb::string(Convert(key, key_length))] = + duckdb::string(Convert(value, value_length)); + }); +} + //---------------------------------------------------------------------------------------------------------------------- // Multi-file functions //---------------------------------------------------------------------------------------------------------------------- diff --git a/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp b/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp index 402d5905e..95ff8da45 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_instance.cpp @@ -19,6 +19,11 @@ CV2Instance::CV2Instance(CV2Environment &env, DBConfig &startup_config) file_system(FileSystem::GetFileSystem(*database->instance), QueryContext()) { } +CV2Instance::CV2Instance(CV2Environment &env, shared_ptr shared_database) + : database(std::move(shared_database)), env(env), factory(*this), config_handle(*this), + file_system(FileSystem::GetFileSystem(*database->instance), QueryContext()) { +} + DatabaseInstance &CV2InstanceFactory::GetDatabase() { return *instance.GetDatabase().instance; } @@ -105,16 +110,28 @@ void CV2Instance::SetDefault(const Identifier &name) { using namespace duckdb::capiv2; +//! Applies the startup options of instance_create_with_options and instance_open_shared. +static void SetStartupOptions(duckdb::DBConfig &startup_config, const char *const *option_names, + const idx_t *option_names_lengths, const char *const *option_values, + const idx_t *option_values_lengths, idx_t option_count) { + string_view_array names(option_names, option_names_lengths, option_count); + string_view_array values(option_values, option_values_lengths, option_count); + for (idx_t i = 0; i < option_count; i++) { + startup_config.SetOptionByName(duckdb::Identifier(duckdb::string(names[i])), + duckdb::Value(duckdb::string(values[i]))); + } +} + DUCKDB_V2_ERROR duckdb_v2_instance_create(duckdb_v2_environment_handle env, duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err) { return duckdb_v2_instance_create_with_options(env, nullptr, nullptr, nullptr, nullptr, 0, out_instance, err); } -DUCKDB_V2_ERROR duckdb_v2_instance_create_with_options(duckdb_v2_environment_handle env, const char **option_names, - const idx_t *option_names_lengths, const char **option_values, - const idx_t *option_values_lengths, idx_t option_count, - duckdb_v2_instance_handle *out_instance, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR +duckdb_v2_instance_create_with_options(duckdb_v2_environment_handle env, const char *const *option_names, + const idx_t *option_names_lengths, const char *const *option_values, + const idx_t *option_values_lengths, idx_t option_count, + duckdb_v2_instance_handle *out_instance, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(env); DUCKDB_CHECK_ARG(out_instance); *out_instance = nullptr; @@ -126,12 +143,8 @@ DUCKDB_V2_ERROR duckdb_v2_instance_create_with_options(duckdb_v2_environment_han } return WithErrorHandler(err, [&]() { duckdb::DBConfig startup_config; - string_view_array names(option_names, option_names_lengths, option_count); - string_view_array values(option_values, option_values_lengths, option_count); - for (idx_t i = 0; i < option_count; i++) { - startup_config.SetOptionByName(duckdb::Identifier(duckdb::string(names[i])), - duckdb::Value(duckdb::string(values[i]))); - } + SetStartupOptions(startup_config, option_names, option_names_lengths, option_values, option_values_lengths, + option_count); auto *env_wrapper = Convert(env); auto wrapper = duckdb::make_uniq(*env_wrapper, startup_config); env_wrapper->instance_count.fetch_add(1, std::memory_order_release); @@ -139,6 +152,112 @@ DUCKDB_V2_ERROR duckdb_v2_instance_create_with_options(duckdb_v2_environment_han }); } +//! The startup options of `config` by the canonical names of the options, with the values in the options' types. +static duckdb::identifier_map_t CanonicalStartupOptions(const duckdb::DBConfig &config, + const duckdb::DBConfig &option_source) { + duckdb::identifier_map_t result; + for (auto &entry : config.options.user_options) { + auto name = entry.first; + auto value = entry.second; + duckdb::LogicalType type; + duckdb::ExtensionOption extension_option; + auto option = duckdb::DBConfig::GetOptionByName(entry.first); + if (option) { + name = duckdb::Identifier(duckdb::string(option->name)); + type = duckdb::DBConfig::ParseLogicalType(option->parameter_type); + } else if (option_source.TryGetExtensionOption(entry.first, extension_option)) { + type = extension_option.type; + } + if (type.id() == duckdb::LogicalTypeId::VARCHAR) { + // text compares regardless of case, as enumerations such as access_mode are parsed + value = duckdb::Value(duckdb::StringUtil::Lower(value.ToString())); + } else if (type.id() != duckdb::LogicalTypeId::INVALID) { + auto converted = value.DefaultTryCastAs(type); + if (converted) { + value = std::move(*converted); + } + } + result[name] = std::move(value); + } + return result; +} + +//! Whether a request for the startup options of `requested` can share an instance created with those of `existing`. +static bool IsSameStartupConfig(const duckdb::DBConfig &existing, const duckdb::DBConfig &requested) { + if (existing.options.configuration_env != requested.options.configuration_env) { + return false; + } + auto existing_options = CanonicalStartupOptions(existing, existing); + auto requested_options = CanonicalStartupOptions(requested, existing); + if (existing_options.size() != requested_options.size()) { + return false; + } + for (auto &entry : requested_options) { + auto existing_entry = existing_options.find(entry.first); + if (existing_entry == existing_options.end() || + !duckdb::Value::NotDistinctFrom(existing_entry->second, entry.second)) { + return false; + } + } + return true; +} + +DUCKDB_V2_ERROR duckdb_v2_instance_open_shared(duckdb_v2_environment_handle env, const char *path, idx_t path_length, + const char *const *option_names, const idx_t *option_names_lengths, + const char *const *option_values, const idx_t *option_values_lengths, + idx_t option_count, duckdb_v2_instance_init_callback_fn init, + void *init_user_data, duckdb_v2_instance_handle *out_instance, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(env); + DUCKDB_CHECK_ARG(out_instance); + *out_instance = nullptr; + DUCKDB_CHECK_STR_ARG(path, path_length); + if (option_count > 0 && !option_names) { + return NullArgumentError(err, __func__, "option_names"); + } + if (option_count > 0 && !option_values) { + return NullArgumentError(err, __func__, "option_values"); + } + return WithErrorHandler(err, [&]() { + duckdb::DBConfig startup_config; + SetStartupOptions(startup_config, option_names, option_names_lengths, option_values, option_values_lengths, + option_count); + auto *env_wrapper = Convert(env); + bool initializing = false; + std::function on_create; + if (init) { + on_create = [&](duckdb::DuckDB &created) { + initializing = true; + // a borrowed handle for the callback, not counted in the environment + CV2Instance borrowed(*env_wrapper, duckdb::make_shared_ptr(*created.instance)); + CV2ErrorInfo init_err = {}; + auto init_err_ptr = Convert(&init_err); + init(Convert(&borrowed), init_user_data, &init_err_ptr); + if (init_err.HasError()) { + init_err.ThrowAsException(); + } + initializing = false; + }; + } + duckdb::shared_ptr database; + try { + // an unnamed in-memory database is never cached: every call opens a new one + database = env_wrapper->cache->GetOrCreateInstance( + path ? duckdb::string(path, path_length) : duckdb::string(), startup_config, + duckdb::CacheBehavior::AUTOMATIC, on_create, IsSameStartupConfig); + } catch (duckdb::ConnectionException &ex) { + if (initializing) { + throw; + } + // the file is open in an instance with a different configuration + throw duckdb::ResourceInUseException(duckdb::ErrorData(ex).RawMessage()); + } + auto wrapper = duckdb::make_uniq(*env_wrapper, std::move(database)); + env_wrapper->instance_count.fetch_add(1, std::memory_order_release); + *out_instance = Convert(wrapper.release()); + }); +} + DUCKDB_V2_ERROR duckdb_v2_instance_destroy(duckdb_v2_instance_handle *instance) { return WithErrorHandler(nullptr, [&]() { if (!instance) { diff --git a/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp b/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp index 9baa2b367..34aba23b2 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp @@ -26,7 +26,7 @@ namespace { // - the remaining bind-time-only ids (SQLNULL, UNKNOWN) which only exist // inside the planner / UDF binding paths, // - parameterised types (DECIMAL, LIST, STRUCT, TUPLE, MAP, ARRAY, UNION, -// ENUM, VARIANT, GEOMETRY), which need parameters to bind. +// ENUM, VARIANT, GEOMETRY, GEOGRAPHY), which need parameters to bind. bool IsPrimitiveCreatable(LogicalTypeId id) { switch (id) { case LogicalTypeId::ANY: @@ -168,6 +168,7 @@ idx_t TypeParamCount(const LogicalType &type) { case LogicalTypeId::VARCHAR: return StringType::GetCollation(type).empty() ? 0 : 1; case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: return GeoType::HasCRS(type) ? 1 : 0; default: return 0; @@ -207,6 +208,7 @@ Value TypeParamValue(const LogicalType &type, idx_t index, std::string_view &out out_name = "collation"; return Value(StringType::GetCollation(type)); case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: return Value(GeoType::GetCRS(type).GetDefinition()); default: throw InternalException("TypeParamValue called for a kind without parameters"); @@ -287,7 +289,7 @@ static void CreateLogicalTypeFromIdV2(CV2Factory &factory, DUCKDB_V2_LOGICAL_TYP } DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id(duckdb_v2_factory_handle factory, - DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char **param_names, + DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char *const *param_names, const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, @@ -342,7 +344,8 @@ static void CreateLogicalTypeFromArgsV2(CV2Factory &factory, duckdb_v2_qname_han } DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_name(duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, - const char **param_names, const idx_t *param_names_lengths, + const char *const *param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err) { diff --git a/src/duckdb/src/main/capi/v2/capi_v2_object_cache.cpp b/src/duckdb/src/main/capi/v2/capi_v2_object_cache.cpp new file mode 100644 index 000000000..5f6199760 --- /dev/null +++ b/src/duckdb/src/main/capi/v2/capi_v2_object_cache.cpp @@ -0,0 +1,211 @@ +#include "duckdb/main/capi_v2/capi_v2_internal.hpp" + +#include "duckdb/main/database.hpp" +#include "duckdb/storage/object_cache.hpp" + +namespace duckdb::capiv2 { + +//---------------------------------------------------------------------------------------------------------------------- +// Object cache +//---------------------------------------------------------------------------------------------------------------------- + +//! An entry of the object cache created through the C API: opaque data plus the memory it is accounted as. +class CV2ObjectCacheEntry final : public ObjectCacheEntry { +public: + //! Wraps data that already exists. + CV2ObjectCacheEntry(CV2UserData data_p, idx_t size_bytes, idx_t max_size) + : data(std::move(data_p)), size_bytes(size_bytes) { + CheckSize(max_size); + } + + //! Creates the data through a callback. + CV2ObjectCacheEntry(duckdb_v2_object_cache_create_callback_fn create, void *create_user_data, idx_t max_size) { + duckdb_v2_opaque created = {nullptr, nullptr, nullptr}; + idx_t created_size = 0; + try { + InvokeWithErrorSlot( + [&](duckdb_v2_error_info_handle *err) { create(create_user_data, &created, &created_size, err); }); + } catch (...) { + // whatever the callback created before failing goes with it + CV2UserData release(created.ptr, created.destroy, created.equals); + throw; + } + data = CV2UserData(created.ptr, created.destroy, created.equals); + size_bytes = created_size; + CheckSize(max_size); + } + + static string ObjectType() { + return "capi_v2"; + } + string GetObjectType() override { + return ObjectType(); + } + optional_idx GetEstimatedCacheMemory() const override { + // no size pins the entry + return size_bytes == 0 ? optional_idx() : optional_idx(size_bytes); + } + void *GetData() const { + return data.GetData(); + } + +private: + void CheckSize(idx_t max_size) const { + if (size_bytes > max_size) { + throw InvalidInputException("Object cache entry of %llu bytes exceeds the cache capacity of %llu bytes", + size_bytes, max_size); + } + } + +private: + CV2UserData data; + idx_t size_bytes = 0; +}; + +//! The handle of an entry held by a caller: pins the data beyond the cache's own hold on it. +struct CV2ObjectCacheEntryHandle { + shared_ptr entry; +}; + +static auto Convert(duckdb_v2_object_cache_entry_handle entry) -> CV2ObjectCacheEntryHandle * { + return reinterpret_cast(entry); +} +static auto Convert(CV2ObjectCacheEntryHandle *entry) -> duckdb_v2_object_cache_entry_handle { + return reinterpret_cast(entry); +} + +static auto Convert(duckdb_v2_object_cache_handle cache) -> ObjectCache * { + return reinterpret_cast(cache); +} +static auto Convert(ObjectCache *cache) -> duckdb_v2_object_cache_handle { + return reinterpret_cast(cache); +} + +//! Entries are looked up by type and key together; the length prefix keeps the two apart, and the C API prefix keeps +//! them apart from the cache's other users. +static auto CacheKey(const char *type, idx_t type_length, const char *key, idx_t key_length) -> string { + return StringUtil::Format("capi_v2:%llu:%s:%s", type_length, string(type, type_length), string(key, key_length)); +} + +static auto CheckedEntry(shared_ptr entry) -> shared_ptr { + if (!entry || entry->GetObjectType() != CV2ObjectCacheEntry::ObjectType()) { + throw InvalidInputException("The object cache holds another kind of entry under this key"); + } + return shared_ptr_cast(std::move(entry)); +} + +static void GiveEntryToCaller(shared_ptr entry, duckdb_v2_object_cache_entry_handle *out) { + if (!entry) { + return; + } + auto handle = make_uniq(); + handle->entry = std::move(entry); + *out = Convert(handle.release()); +} + +} // namespace duckdb::capiv2 + +//---------------------------------------------------------------------------------------------------------------------- +// Public Functions +//---------------------------------------------------------------------------------------------------------------------- + +using namespace duckdb::capiv2; + +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_CHECK_ARG(instance); + DUCKDB_CHECK_ARG(cache); + *cache = nullptr; + return WithErrorHandler(err, + [&]() { *cache = Convert(&Convert(instance)->GetDatabase().instance->GetObjectCache()); }); +} + +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_CHECK_ARG(context); + DUCKDB_CHECK_ARG(cache); + *cache = nullptr; + return WithErrorHandler(err, [&]() { + *cache = Convert(&duckdb::DatabaseInstance::GetDatabase(Convert(context)->context).GetObjectCache()); + }); +} + +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_CHECK_ARG(data); + // owned from here, so every failure below destroys the data + CV2UserData owned(data->ptr, data->destroy, data->equals); + DUCKDB_CHECK_ARG(cache); + DUCKDB_CHECK_STR_ARG(type, type_length); + DUCKDB_CHECK_STR_ARG(key, key_length); + return WithErrorHandler(err, [&]() { + auto &object_cache = *Convert(cache); + auto entry = + duckdb::make_shared_ptr(std::move(owned), size_bytes, object_cache.GetMaxMemory()); + object_cache.Put(CacheKey(type, type_length, key, key_length), std::move(entry)); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_object_cache_get(duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, + const char *key, idx_t key_length, + duckdb_v2_object_cache_entry_handle *entry, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(cache); + DUCKDB_CHECK_STR_ARG(type, type_length); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_ARG(entry); + *entry = nullptr; + return WithErrorHandler(err, [&]() { + auto found = Convert(cache)->Get(CacheKey(type, type_length, key, key_length)); + GiveEntryToCaller(std::move(found), entry); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_object_cache_get_or_create(duckdb_v2_object_cache_handle cache, const char *type, + idx_t type_length, const char *key, idx_t key_length, + duckdb_v2_object_cache_create_callback_fn create, + void *create_user_data, duckdb_v2_object_cache_entry_handle *entry, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(cache); + DUCKDB_CHECK_STR_ARG(type, type_length); + DUCKDB_CHECK_STR_ARG(key, key_length); + DUCKDB_CHECK_ARG(create); + DUCKDB_CHECK_ARG(entry); + *entry = nullptr; + return WithErrorHandler(err, [&]() { + auto &object_cache = *Convert(cache); + auto cache_key = CacheKey(type, type_length, key, key_length); + auto found = object_cache.GetOrCreateObject(cache_key, [&]() -> duckdb::shared_ptr { + return duckdb::make_shared_ptr(create, create_user_data, object_cache.GetMaxMemory()); + }); + GiveEntryToCaller(CheckedEntry(std::move(found)), entry); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_object_cache_delete(duckdb_v2_object_cache_handle cache, const char *type, idx_t type_length, + const char *key, idx_t key_length, duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(cache); + DUCKDB_CHECK_STR_ARG(type, type_length); + DUCKDB_CHECK_STR_ARG(key, key_length); + return WithErrorHandler(err, [&]() { Convert(cache)->Delete(CacheKey(type, type_length, key, key_length)); }); +} + +DUCKDB_V2_ERROR duckdb_v2_object_cache_entry_get_data(duckdb_v2_object_cache_entry_handle entry, void **data, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(entry); + DUCKDB_CHECK_ARG(data); + return WithErrorHandler(err, [&]() { *data = Convert(entry)->entry->GetData(); }); +} + +DUCKDB_V2_ERROR duckdb_v2_object_cache_entry_destroy(duckdb_v2_object_cache_entry_handle *entry) { + if (!entry) { + return DUCKDB_V2_ERROR_NONE; + } + return WithErrorHandler(nullptr, [&]() { + duckdb::unique_ptr owned(Convert(*entry)); + *entry = nullptr; + }); +} diff --git a/src/duckdb/src/main/capi/v2/capi_v2_prepared_statement.cpp b/src/duckdb/src/main/capi/v2/capi_v2_prepared_statement.cpp index 9cd4e5721..8512ea621 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_prepared_statement.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_prepared_statement.cpp @@ -71,7 +71,8 @@ DUCKDB_V2_ERROR duckdb_v2_prepared_statement_create(duckdb_v2_connection_handle } DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute(duckdb_v2_prepared_statement_handle prepared, - const char **parameter_names, const idx_t *parameter_names_lengths, + const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err) { @@ -95,9 +96,9 @@ DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute(duckdb_v2_prepared_statemen } DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute_arrow( - duckdb_v2_prepared_statement_handle prepared, const char **parameter_names, const idx_t *parameter_names_lengths, - const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, idx_t batch_size, - duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err) { + duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + idx_t batch_size, duckdb_v2_arrow_result_handle *out_result, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(out_result); *out_result = nullptr; DUCKDB_CHECK_ARG(prepared); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_qname.cpp b/src/duckdb/src/main/capi/v2/capi_v2_qname.cpp index 571fe9e74..ee41f1aae 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_qname.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_qname.cpp @@ -42,7 +42,7 @@ DUCKDB_V2_ERROR duckdb_v2_qname_parse(const char *text, idx_t text_length, duckd }); } -DUCKDB_V2_ERROR duckdb_v2_qname_create(const char **parts, const idx_t *parts_lengths, idx_t part_count, +DUCKDB_V2_ERROR duckdb_v2_qname_create(const char *const *parts, const idx_t *parts_lengths, idx_t part_count, duckdb_v2_qname_handle *out_name, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(out_name); *out_name = nullptr; diff --git a/src/duckdb/src/main/capi/v2/capi_v2_replacement_scan.cpp b/src/duckdb/src/main/capi/v2/capi_v2_replacement_scan.cpp index 3ee93d148..56ea79a76 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_replacement_scan.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_replacement_scan.cpp @@ -257,8 +257,9 @@ DUCKDB_V2_ERROR duckdb_v2_replacement_scan_add_named_argument(duckdb_v2_replacem DUCKDB_V2_ERROR duckdb_v2_replacement_scan_set_collection(duckdb_v2_replacement_scan_info_handle info, duckdb_v2_column_data_collection_handle collection, - const char **column_names, const idx_t *column_names_lengths, - idx_t column_count, duckdb_v2_error_info_handle *err) { + const char *const *column_names, + const idx_t *column_names_lengths, idx_t column_count, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); DUCKDB_CHECK_ARG(collection); return WithErrorHandler(err, [&]() { diff --git a/src/duckdb/src/main/capi/v2/capi_v2_result.cpp b/src/duckdb/src/main/capi/v2/capi_v2_result.cpp index ab9a72567..96451d1e3 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_result.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_result.cpp @@ -431,7 +431,7 @@ auto ExecuteStatementV2(const shared_ptr &context, const SQLState using namespace duckdb::capiv2; DUCKDB_V2_ERROR duckdb_v2_statement_execute(duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, - const char **parameter_names, const idx_t *parameter_names_lengths, + const char *const *parameter_names, const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err) { // The refusals here never reach the engine and leave the statement intact diff --git a/src/duckdb/src/main/capi/v2/capi_v2_statement.cpp b/src/duckdb/src/main/capi/v2/capi_v2_statement.cpp index eafdc30e0..d5453fad4 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_statement.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_statement.cpp @@ -213,7 +213,7 @@ DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_name(duckdb_v2_sql_stateme DUCKDB_V2_ERROR duckdb_v2_statement_add_collection(duckdb_v2_sql_statement_handle statement, const char *name, idx_t name_length, duckdb_v2_column_data_collection_handle collection, - const char **column_names, const idx_t *column_names_lengths, + const char *const *column_names, const idx_t *column_names_lengths, idx_t column_count, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(statement); DUCKDB_CHECK_STR_ARG(name, name_length); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp index a0cec44f9..f90c79071 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp @@ -105,8 +105,8 @@ LogicalType RequireValueType(duckdb_v2_logical_type_handle type) { // The DECIMAL storage tier follows from the width, and the engine's hugeint // constructor covers only the widest one, so the narrower tiers go through the -// int64 form. Width and scale are gated here: an out-of-range pair would build -// a broken type rather than a bad value. The uint8_t parameters reach widths +// int64 form. Width, scale and the value's digit count are gated here: either +// would otherwise build a broken value. The uint8_t parameters reach widths // up to 255; wider decimals are built through value_cast. Value BuildDecimal(const duckdb_v2_hugeint_t *in_value, uint8_t width, uint8_t scale) { if (width < 1) { @@ -116,16 +116,17 @@ Value BuildDecimal(const duckdb_v2_hugeint_t *in_value, uint8_t width, uint8_t s throw InvalidInputException(": DECIMAL scale cannot exceed the width"); } auto value = Convert(in_value); + // a 128-bit value has at most 39 digits, so only narrower widths can be exceeded + if (width < Hugeint::CACHED_POWERS_OF_TEN && + (value >= Hugeint::POWERS_OF_TEN[width] || value <= -Hugeint::POWERS_OF_TEN[width])) { + throw InvalidInputException("value does not fit the declared DECIMAL width"); + } auto type = LogicalType::DECIMAL(width, scale); if (type.InternalType() == PhysicalType::INT128 || type.InternalType() == PhysicalType::VARCHAR) { // the hugeint constructor also builds the BIGNUM storage of a wide decimal (width > 38) return Value::DECIMAL(value, width, scale); } - int64_t narrow = 0; - if (!Hugeint::TryCast(value, narrow)) { - throw InvalidInputException("value does not fit the storage tier of the declared width"); - } - return Value::DECIMAL(narrow, width, scale); + return Value::DECIMAL(Hugeint::Cast(value), width, scale); } // BIT carries a mandatory padding-header byte, BIGNUM a header plus at least @@ -819,7 +820,7 @@ duckdb::Value BuildArray(CV2Factory &factory, duckdb_v2_logical_type_handle chil return duckdb::Value::ARRAY(type, std::move(values)); } -duckdb::Value BuildStruct(const char **names, const idx_t *names_lengths, const duckdb_v2_value_handle *children, +duckdb::Value BuildStruct(const char *const *names, const idx_t *names_lengths, const duckdb_v2_value_handle *children, idx_t field_count) { if (field_count > 0 && !names) { throw duckdb::InvalidInputException("'names' cannot be null when field_count > 0"); @@ -878,7 +879,7 @@ DUCKDB_V2_ERROR duckdb_v2_value_create_array(duckdb_v2_factory_handle factory, d err, [&]() { *out_value = Emit(BuildArray(*Convert(factory), child_type, children, child_count)); }); } -DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, const char **names, +DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, const char *const *names, const idx_t *names_lengths, const duckdb_v2_value_handle *children, idx_t field_count, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err) { diff --git a/src/duckdb/src/main/client_config.cpp b/src/duckdb/src/main/client_config.cpp index 40f9da0da..6e3e9d3ca 100644 --- a/src/duckdb/src/main/client_config.cpp +++ b/src/duckdb/src/main/client_config.cpp @@ -29,14 +29,4 @@ void ClientConfig::ResetUserVariable(const String &name) { user_variables.erase(StringToIdentifier(name)); } -void ClientConfig::SetDefaultStreamingBufferSize() { - auto memory = FileSystem::GetAvailableMemory(); - auto default_size = ClientConfig().max_streaming_buffer_size; - if (!memory.IsValid()) { - max_streaming_buffer_size = default_size; - return; - } - max_streaming_buffer_size = MinValue(memory.GetIndex(), default_size); -} - } // namespace duckdb diff --git a/src/duckdb/src/main/client_context.cpp b/src/duckdb/src/main/client_context.cpp index 902dfbb01..5e3c1343d 100644 --- a/src/duckdb/src/main/client_context.cpp +++ b/src/duckdb/src/main/client_context.cpp @@ -26,7 +26,6 @@ #include "duckdb/main/prepared_statement_data.hpp" #include "duckdb/main/query_profiler.hpp" #include "duckdb/main/query_result.hpp" -#include "duckdb/main/relation.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/parser/expression/star_expression.hpp" @@ -38,7 +37,6 @@ #include "duckdb/parser/statement/explain_statement.hpp" #include "duckdb/parser/statement/passthrough_statement.hpp" #include "duckdb/parser/statement/prepare_statement.hpp" -#include "duckdb/parser/statement/relation_statement.hpp" #include "duckdb/parser/statement/select_statement.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/logical_plan_verifier.hpp" @@ -157,17 +155,34 @@ ClientContext::ClientContext(shared_ptr database) #endif } -ClientContext::~ClientContext() { - if (Exception::UncaughtException()) { +void ClientContext::RollbackActiveTransaction() { + if (!transaction.HasActiveTransaction()) { return; } - // destroy the client context and rollback if there is an active transaction - // but only if we are not destroying this client context as part of an exception stack unwind + // a destructor cannot throw: once the database is invalidated, the rollback can fail as well try { - Destroy(); - } catch (...) { - // a destructor cannot throw, and locking the context allocates + transaction.Rollback(nullptr); + } catch (std::exception &ex) { + // building the error message allocates + try { + ErrorData data(ex); + DUCKDB_LOG_ERROR(*this, "ClientContext::RollbackActiveTransaction()\t\t" + data.Message()); + } catch (...) { // NOLINT + } + } catch (...) { // NOLINT + } +} + +ClientContext::~ClientContext() { + // no clean-up while unwinding an exception stack, but the transaction must not outlive the connection + if (!Exception::UncaughtException()) { + try { + Destroy(); + } catch (...) { + // a destructor cannot throw, and ending the active query allocates + } } + RollbackActiveTransaction(); } unique_ptr ClientContext::LockContext() { @@ -218,18 +233,11 @@ static unique_ptr WrapAsSelect(unique_ptr from_ref) { } void ClientContext::Destroy() { - auto lock = LockContext(); - if (transaction.HasActiveTransaction()) { - transaction.ResetActiveQuery(); - if (!transaction.IsAutoCommit()) { - // a destructor cannot throw: once the database is invalidated, the rollback can fail as well - try { - transaction.Rollback(nullptr); - } catch (...) { // NOLINT - } - } - } - CleanupInternal(*lock); + // the destructor runs this when the heap may be exhausted: lock on the stack, so the tasks of an active query are + // still drained before their executor goes away + ClientContextLock lock(context_lock); + transaction.ResetActiveQuery(); + CleanupInternal(lock); } void ClientContext::ProcessError(ErrorData &error, const string &query) const { @@ -449,7 +457,7 @@ void ClientContext::CheckIfPreparedStatementIsExecutable(PreparedStatementData & "Cannot execute statement of type \"%s\" on database %s which is attached in read-only mode!", StatementTypeToString(statement.statement_type), modified_database)); } - meta_transaction.ModifyDatabase(*entry, it.second.modifications); + meta_transaction.ModifyDatabase(*this, *entry, it.second.modifications); } } @@ -1175,7 +1183,7 @@ void ClientContext::SuppressInterrupts() { interrupt_state = ClientInterruptState::INTERRUPTS_SUPPRESSED; } -void ClientContext::InterruptCheck() const { +void ClientContext::FastInterruptCheck() const { // Counter for throttling timeout checks - only check every N iterations static constexpr uint32_t TIMEOUT_CHECK_INTERVAL = 256; thread_local uint32_t timeout_check_counter = 0; @@ -1185,11 +1193,11 @@ void ClientContext::InterruptCheck() const { } // Only check timeout every N calls to avoid expensive steady_clock::now() syscall if (HasQueryDeadline() && ++timeout_check_counter % TIMEOUT_CHECK_INTERVAL == 0) { - BlockingInterruptCheck(); + InterruptCheck(); } } -void ClientContext::BlockingInterruptCheck() const { +void ClientContext::InterruptCheck() const { if (IsInterrupted()) { throw InterruptException(); } @@ -1273,7 +1281,7 @@ void ClientContext::RunTransactionStatementInternal(const TransactionInfo &info) if (ValidChecker::IsInvalidated(*attached)) { continue; } - transaction.ActiveTransaction().GetTransaction(*attached); + transaction.ActiveTransaction().GetTransaction(*this, *attached); } } break; @@ -1413,26 +1421,6 @@ void ClientContext::Append(TableDescription &description, ColumnDataCollection & Append(std::move(stmt)); } -void ClientContext::InternalTryBindRelation(Relation &relation, vector &result_columns) { - // bind the expressions - auto binder = Binder::CreateBinder(*this); - auto result = relation.Bind(*binder); - D_ASSERT(result.names.size() == result.types.size()); - - result_columns.reserve(result_columns.size() + result.names.size()); - for (idx_t i = 0; i < result.names.size(); i++) { - result_columns.emplace_back(result.names[i], result.types[i]); - } -} - -void ClientContext::TryBindRelation(Relation &relation, vector &result_columns) { -#ifdef DEBUG - D_ASSERT(!relation.GetAlias().empty()); - D_ASSERT(!relation.ToString().empty()); -#endif - RunFunctionInTransaction([&]() { InternalTryBindRelation(relation, result_columns); }); -} - unordered_set ClientContext::GetTableNames(const string &query, const bool qualified) { auto lock = LockContext(); @@ -1457,77 +1445,6 @@ unordered_set ClientContext::GetTableNames(const string &query, const bo return result; } -unique_ptr ClientContext::SubmitInternal(ClientContextLock &lock, const shared_ptr &relation, - const QueryParameters &query_parameters) { - if (auto refusal = InitialCleanup(lock)) { - return refusal; - } - -#ifdef DEBUG - // run the ToString method of any relation we run, mostly to ensure it doesn't crash - relation->ToString(); - relation->GetAlias(); -#endif - - auto relation_stmt = make_uniq(relation); - return SubmitInternal(lock, std::move(relation_stmt), query_parameters); -} - -unique_ptr ClientContext::Submit(const shared_ptr &relation, - const QueryParameters &query_parameters) { - auto lock = LockContext(); - return SubmitInternal(*lock, relation, query_parameters); -} - -unique_ptr ClientContext::Execute(const shared_ptr &relation) { - auto lock = LockContext(); - auto &expected_columns = relation->Columns(); - if (auto refusal = InitialCleanup(*lock)) { - return refusal; - } - - auto relation_stmt = make_uniq(relation); - QueryParameters parameters; - auto result = SubmitInternal(*lock, std::move(relation_stmt), parameters, true, Retention::RETAINED_AT_SUBMISSION); - if (result->HasError()) { - return result; - } - result = CompleteInternal(*lock, std::move(result)); - if (result->HasError()) { - return result; - } - // verify that the result types and result names of the query match the expected result types/names - if (result->GetTypes().size() == expected_columns.size()) { - bool mismatch = false; - for (idx_t i = 0; i < result->GetTypes().size(); i++) { - if (result->GetTypes()[i] != expected_columns[i].Type() || - result->ColumnName(i) != expected_columns[i].Name()) { - mismatch = true; - break; - } - } - if (!mismatch) { - // all is as expected: return the result - return result; - } - } - // result mismatch - string err_str = "Result mismatch in query!\nExpected the following columns: ["; - for (idx_t i = 0; i < expected_columns.size(); i++) { - if (i > 0) { - err_str += ", "; - } - err_str += expected_columns[i].Name() + " " + expected_columns[i].Type().ToString(); - } - err_str += "]\nBut result contained the following: "; - for (idx_t i = 0; i < result->GetTypes().size(); i++) { - err_str += i == 0 ? "[" : ", "; - err_str += result->ColumnName(i) + " " + result->GetTypes()[i].ToString(); - } - err_str += "]"; - return ErrorResult(ErrorData(err_str)); -} - SettingLookupResult ClientContext::TryGetCurrentSetting(const Identifier &key, Value &result) const { optional_ptr option; // try to get the setting index diff --git a/src/duckdb/src/main/client_context_execution.cpp b/src/duckdb/src/main/client_context_execution.cpp index cd44cfc4d..ac1260ec9 100644 --- a/src/duckdb/src/main/client_context_execution.cpp +++ b/src/duckdb/src/main/client_context_execution.cpp @@ -424,7 +424,7 @@ QueryResultState ClientContext::ExecuteTaskInternal(ClientContextLock &lock, Bas D_ASSERT(active_query); D_ASSERT(active_query->IsOpenResult(result)); try { - // Surface a pending interrupt even when this thread runs no task that reaches InterruptCheck. + // Surface a pending interrupt even when this thread runs no task that reaches an InterruptCheck. // IsInterrupted() rather than InterruptCheck(): we must not enforce query_deadline here. // Skip when the executor already has an error: ExecuteTask rethrows that with its original type. if (IsInterrupted() && !active_query->executor->HasError()) { diff --git a/src/duckdb/src/main/client_context_wrapper.cpp b/src/duckdb/src/main/client_context_wrapper.cpp deleted file mode 100644 index 74783c79d..000000000 --- a/src/duckdb/src/main/client_context_wrapper.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "duckdb/main/client_context_wrapper.hpp" -#include "duckdb/main/client_context.hpp" - -namespace duckdb { - -ClientContextWrapper::ClientContextWrapper(const shared_ptr &context) : client_context(context) { -} - -shared_ptr ClientContextWrapper::TryGetContext() { - auto actual_context = client_context.lock(); - return actual_context; -} - -shared_ptr ClientContextWrapper::GetContext() { - auto actual_context = TryGetContext(); - if (!actual_context) { - throw ConnectionException("Connection has already been closed"); - } - return actual_context; -} - -void ClientContextWrapper::TryBindRelation(Relation &relation, vector &columns) { - GetContext()->TryBindRelation(relation, columns); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/client_data.cpp b/src/duckdb/src/main/client_data.cpp index 6b3d3c14c..d24a9a8d2 100644 --- a/src/duckdb/src/main/client_data.cpp +++ b/src/duckdb/src/main/client_data.cpp @@ -31,6 +31,7 @@ ClientData::~ClientData() { // This needs to be destroyed first because PreparedStatementData holds a PhysicalPlan, // and the PhysicalPlan holds objects that might rely on the client file opener/file system/buffer manager prepared_statements.clear(); + temporary_objects->Close(DatabaseCloseAction::SKIP_CHECKPOINT); } ClientData &ClientData::Get(ClientContext &context) { diff --git a/src/duckdb/src/main/client_verify.cpp b/src/duckdb/src/main/client_verify.cpp index fa3c18a54..81aee9c96 100644 --- a/src/duckdb/src/main/client_verify.cpp +++ b/src/duckdb/src/main/client_verify.cpp @@ -88,10 +88,6 @@ void ClientContext::StatementVerification(ClientContextLock &lock, unique_ptrCopy()); } else if (verification == DebugStatementVerification::REPARSE_STATEMENT) { - if (statement->type == StatementType::RELATION_STATEMENT) { - // reparsing not supported for relation statements - return; - } // ToString() writes identifiers as they were folded when the statement was first parsed, so folding // them a second time would corrupt any identifier that was quoted in the original statement Parser parser(*this, IdentifierCaseMode::PRESERVE_CASE); diff --git a/src/duckdb/src/main/config.cpp b/src/duckdb/src/main/config.cpp index 5ab0b5cd7..aae1fdb15 100644 --- a/src/duckdb/src/main/config.cpp +++ b/src/duckdb/src/main/config.cpp @@ -42,6 +42,12 @@ DebugVerificationMode DBConfigOptions::global_verification_mode = DebugVerificat _PARAM::Scope, _PARAM::DefaultValue, _PARAM::OnSet, _PARAM::SettingIndex, _PARAM::IsDebug, \ _PARAM::IsDeprecated, Settings::GetDefaultValue<_PARAM> \ } +#define DUCKDB_SETTING_DEFAULT_FUNCTION(_PARAM) \ + { \ + _PARAM::Name, _PARAM::Description, _PARAM::InputType, nullptr, nullptr, nullptr, nullptr, nullptr, \ + _PARAM::Scope, nullptr, _PARAM::OnSet, _PARAM::SettingIndex, _PARAM::IsDebug, _PARAM::IsDeprecated, \ + nullptr, _PARAM::GetDefaultValue \ + } #define DUCKDB_GLOBAL(_PARAM) \ { \ _PARAM::Name, _PARAM::Description, _PARAM::InputType, _PARAM::SetGlobal, nullptr, _PARAM::ResetGlobal, \ @@ -94,7 +100,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING(ArrowOutputListViewSetting), DUCKDB_SETTING_CALLBACK(ArrowOutputVersionSetting), DUCKDB_SETTING(AsofLoopJoinThresholdSetting), - DUCKDB_GLOBAL(AsyncThreadsSetting), + DUCKDB_SETTING_DEFAULT_FUNCTION(AsyncThreadsSetting), DUCKDB_SETTING(AutoCheckpointSkipWalThresholdSetting), DUCKDB_SETTING(AutoinstallExtensionRepositorySetting), DUCKDB_SETTING(AutoinstallKnownExtensionsSetting), @@ -120,6 +126,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING(DebugEvictionQueueSleepMicroSecondsSetting), DUCKDB_SETTING(DebugFileDescriptorLimitSetting), DUCKDB_SETTING_CALLBACK(ForceBitpackingModeSetting), + DUCKDB_SETTING(DebugForceBloomFilterReplicationSetting), DUCKDB_SETTING(DebugForceCheckpointSetting), DUCKDB_SETTING(DebugForceCommitFailureSetting), DUCKDB_SETTING(DebugForceCommitRevertFailureSetting), @@ -201,7 +208,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING(GeometryMinimumShreddingSize), DUCKDB_SETTING_CALLBACK(HomeDirectorySetting), DUCKDB_GLOBAL(HTTPClientPoolCapacitySetting), - DUCKDB_GLOBAL(HTTPProxySetting), + DUCKDB_SETTING_DEFAULT_FUNCTION(HTTPProxySetting), DUCKDB_SETTING(HTTPProxyPasswordSetting), DUCKDB_SETTING(HTTPProxyUsernameSetting), DUCKDB_SETTING(HTTPRetryQuotaThrottledSetting), @@ -227,8 +234,8 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING(MaxDecimalWidthSetting), DUCKDB_SETTING(MaxExecutionTimeSetting), DUCKDB_SETTING(MaxExpressionDepthSetting), - DUCKDB_GLOBAL(MaxMemorySetting), - DUCKDB_LOCAL(MaxStreamingBufferSizeSetting), + DUCKDB_SETTING_DEFAULT_FUNCTION(MaxMemorySetting), + DUCKDB_SETTING_CALLBACK(MaxStreamingBufferSizeSetting), DUCKDB_GLOBAL(MaxTempDirectorySizeSetting), DUCKDB_SETTING(MaxVacuumTasksSetting), DUCKDB_SETTING(MergeJoinThresholdSetting), @@ -265,11 +272,11 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING_CALLBACK(ShowBehaviorSetting), DUCKDB_GLOBAL(StandardVectorSizeSetting), DUCKDB_SETTING_CALLBACK(StorageBlockPrefetchSetting), - DUCKDB_GLOBAL(StorageCompatibilityVersionSetting), + DUCKDB_SETTING_CALLBACK(StorageCompatibilityVersionSetting), DUCKDB_SETTING_CALLBACK(TableFunctionIdentifierConversionSetting), DUCKDB_GLOBAL(TempDirectorySetting), DUCKDB_SETTING_CALLBACK(TempFileEncryptionSetting), - DUCKDB_GLOBAL(ThreadsSetting), + DUCKDB_SETTING_DEFAULT_FUNCTION(ThreadsSetting), DUCKDB_SETTING_CALLBACK(TrackedMetricsSetting), DUCKDB_SETTING(TrimFreeBlocksSetting), DUCKDB_SETTING(UsernameSetting), @@ -396,7 +403,8 @@ idx_t DBConfig::GetWriteBufferMemoryLimit() const { if (options.write_buffer_row_group_memory_limit.IsValid()) { return options.write_buffer_row_group_memory_limit.GetIndex(); } - return options.maximum_memory / 5 / (options.maximum_threads + 1); + auto threads = NumericCast(Settings::Get(*this)); + return options.maximum_memory / 5 / (threads + 1); } vector DBConfig::GetExtensionDirectories() const { @@ -437,7 +445,7 @@ void DBConfig::SetOptionsByName(const identifier_map_t &values) { void DBConfig::SetOption(optional_ptr db, const ConfigurationOption &option, const Value &value) { Value input = value.DefaultCastAs(ParseLogicalType(option.parameter_type)); - if (option.default_value) { + if (option.IsGeneric()) { // generic option SettingCallbackInfo info(*this, db); if (option.set_callback) { @@ -459,12 +467,12 @@ void DBConfig::SetOption(optional_ptr db, const ConfigurationO } void DBConfig::ResetOption(optional_ptr db, const ConfigurationOption &option) { - if (option.default_value) { + if (option.IsGeneric()) { // generic option if (option.set_callback) { + auto reset_value = option.GetDefaultValue(*this).DefaultCastAs(ParseLogicalType(option.parameter_type)); SettingCallbackInfo info(*this, db); info.is_reset = true; - auto reset_value = Value(option.default_value).DefaultCastAs(ParseLogicalType(option.parameter_type)); option.set_callback(info, reset_value); } user_settings.ClearSetting(option.setting_idx.GetIndex()); @@ -478,6 +486,14 @@ void DBConfig::ResetOption(optional_ptr db, const Configuratio option.reset_global(db.get(), *this); } +Value ConfigurationOption::GetDefaultValue(const DBConfig &config) const { + D_ASSERT(IsGeneric()); + if (default_function) { + return default_function(config); + } + return Value(default_value); +} + void DBConfig::SetOption(idx_t setting_index, Value value) { user_settings.SetUserSetting(setting_index, std::move(value)); } @@ -677,15 +693,28 @@ IndexTypeSet &DBConfig::GetIndexTypes() { return *index_types; } -void DBConfig::SetDefaultMaxMemory() { +idx_t DBConfig::GetDefaultMaxMemory() const { + auto default_memory = default_max_memory.load(); + if (default_memory != 0) { + return default_memory; + } auto memory = GetSystemAvailableMemory(*file_system); if (memory == DBConfigOptions().maximum_memory) { // If GetSystemAvailableMemory returned the default, use it as is - options.maximum_memory = memory; + default_memory = memory; } else { // Otherwise, use 80% of the available memory - options.maximum_memory = memory * 8 / 10; + default_memory = memory * 8 / 10; + } + // a user config does not have its final file system yet + if (!is_user_config) { + default_max_memory = default_memory; } + return default_memory; +} + +void DBConfig::SetDefaultMaxMemory() { + options.maximum_memory = GetDefaultMaxMemory(); } void DBConfig::SetDefaultTempDirectory() { @@ -740,14 +769,35 @@ idx_t DBConfig::GetSystemMaxThreads(FileSystem &fs) { #endif } -idx_t DBConfig::GetSystemMaxAsyncThreads(FileSystem &fs) { +static idx_t AsyncThreadsForThreads(idx_t threads) { #ifdef DUCKDB_NO_THREADS return 0; #else - return MinValue(4 * GetSystemMaxThreads(fs), 256); + return MinValue(4 * threads, 256); #endif } +idx_t DBConfig::GetSystemMaxAsyncThreads(FileSystem &fs) { + return AsyncThreadsForThreads(GetSystemMaxThreads(fs)); +} + +idx_t DBConfig::GetDefaultThreads() const { + auto threads = default_threads.load(); + if (threads != 0) { + return threads; + } + threads = GetSystemMaxThreads(*file_system); + // a user config does not have its final file system yet + if (!is_user_config) { + default_threads = threads; + } + return threads; +} + +idx_t DBConfig::GetDefaultAsyncThreads() const { + return AsyncThreadsForThreads(GetDefaultThreads()); +} + idx_t DBConfig::GetSystemAvailableMemory(FileSystem &fs) { // System memory detection auto memory = FileSystem::GetAvailableMemory(); @@ -881,10 +931,14 @@ SettingLookupResult DBConfig::TryGetCurrentUserSetting(idx_t setting_index, Valu return user_settings.TryGetSetting(setting_index, result); } -SettingLookupResult DBConfig::TryGetDefaultValue(optional_ptr option, Value &result) { - if (!option || !option->default_value) { +SettingLookupResult DBConfig::TryGetDefaultValue(optional_ptr option, Value &result) const { + if (!option || !option->IsGeneric()) { return SettingLookupResult(); } + if (option->default_function) { + result = option->default_function(*this); + return SettingLookupResult(SettingScope::GLOBAL); + } if (!option->get_default_value) { throw InternalException("Generic setting \"%s\" has no typed default value", option->name); } diff --git a/src/duckdb/src/main/connection.cpp b/src/duckdb/src/main/connection.cpp index 3ce1fb199..b045a6bd1 100644 --- a/src/duckdb/src/main/connection.cpp +++ b/src/duckdb/src/main/connection.cpp @@ -1,21 +1,12 @@ #include "duckdb/main/connection.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" -#include "duckdb/function/table/read_csv.hpp" #include "duckdb/main/appender.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/connection_manager.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/query_profiler.hpp" -#include "duckdb/main/relation/query_relation.hpp" -#include "duckdb/main/relation/read_csv_relation.hpp" -#include "duckdb/main/relation/table_function_relation.hpp" -#include "duckdb/main/relation/table_relation.hpp" -#include "duckdb/main/relation/value_relation.hpp" -#include "duckdb/main/relation/view_relation.hpp" #include "duckdb/parser/parsed_data/transaction_info.hpp" -#include "duckdb/parser/parser.hpp" -#include "duckdb/planner/binder.hpp" #include "duckdb/planner/logical_operator.hpp" #include "duckdb/main/statement_iterator.hpp" @@ -208,134 +199,10 @@ void Connection::Append(TableDescription &description, ColumnDataCollection &col context->Append(description, collection); } -shared_ptr Connection::Table(const Identifier &table_name) { - return Table(Identifier::DefaultSchema(), table_name); -} - -shared_ptr Connection::Table(const Identifier &schema_name, const Identifier &table_name) { - return Table(Identifier::InvalidCatalog(), schema_name, table_name); -} - -shared_ptr Connection::Table(const Identifier &catalog_name, const Identifier &schema_name, - const Identifier &table_name) { - auto catalog = catalog_name; - auto schema = schema_name; - if (IsInvalidCatalog(catalog) && !IsInvalidSchema(schema)) { - context->RunFunctionInTransaction([&]() { Binder::BindSchemaOrCatalog(*context, catalog, schema); }); - } - auto table_info = TableInfo(catalog, schema, table_name); - if (!table_info) { - throw CatalogException("Table %s does not exist!", - QualifiedName(catalog_name, schema_name, table_name) - .ToString(QualifiedNameToStringMode::HIDE_DEFAULT_SCHEMA)); - } - return make_shared_ptr(context, std::move(table_info)); -} - -shared_ptr Connection::View(const Identifier &tname) { - return View(Identifier::DefaultSchema(), tname); -} - -shared_ptr Connection::View(const Identifier &schema_name, const Identifier &table_name) { - return make_shared_ptr(context, schema_name, table_name); -} - -shared_ptr Connection::TableFunction(const string &fname) { - vector values; - named_parameter_map_t named_parameters; - return TableFunction(fname, values, named_parameters); -} - -shared_ptr Connection::TableFunction(const string &fname, const vector &values, - const named_parameter_map_t &named_parameters) { - return make_shared_ptr(context, fname, values, named_parameters); -} - -shared_ptr Connection::TableFunction(const string &fname, const vector &values, - const named_parameter_map_t &named_parameters, - shared_ptr bind_info) { - return make_shared_ptr(context, fname, values, named_parameters, nullptr, true, - std::move(bind_info)); -} - -shared_ptr Connection::TableFunction(const string &fname, const vector &values) { - return make_shared_ptr(context, fname, values); -} - -shared_ptr Connection::Values(const vector> &values) { - vector column_names; - return Values(values, column_names); -} - -shared_ptr Connection::Values(vector>> &&expressions) { - vector column_names; - return make_shared_ptr(context, std::move(expressions), column_names); -} - -shared_ptr Connection::Values(const vector> &values, const vector &column_names, - const string &alias) { - return make_shared_ptr(context, values, column_names, alias); -} - -shared_ptr Connection::Values(const string &values) { - vector column_names; - return Values(values, column_names); -} - -shared_ptr Connection::Values(const string &values, const vector &column_names, const string &alias) { - return make_shared_ptr(context, values, column_names, alias); -} - -shared_ptr Connection::ReadCSV(const string &csv_file) { - named_parameter_map_t options; - return ReadCSV(csv_file, std::move(options)); -} - -shared_ptr Connection::ReadCSV(const vector &csv_input, named_parameter_map_t &&options) { - return make_shared_ptr(context, csv_input, std::move(options)); -} - -shared_ptr Connection::ReadCSV(const string &csv_input, named_parameter_map_t &&options) { - vector csv_files = {csv_input}; - return ReadCSV(csv_files, std::move(options)); -} - -shared_ptr Connection::ReadCSV(const string &csv_file, const vector &columns) { - // parse columns - named_parameter_map_t options; - child_list_t column_list; - for (auto &column : columns) { - auto col_list = Parser(*context).ParseColumnList(column); - if (col_list.LogicalColumnCount() != 1) { - throw ParserException("Expected a single column definition"); - } - auto &col_def = col_list.GetColumnMutable(LogicalIndex(0)); - column_list.emplace_back(col_def.GetName().GetIdentifierName(), col_def.GetType().ToString()); - } - vector files {csv_file}; - return make_shared_ptr(context, files, std::move(options)); -} - -shared_ptr Connection::ReadParquet(const string &parquet_file, bool binary_as_string) { - vector params; - params.emplace_back(parquet_file); - named_parameter_map_t named_parameters({{"binary_as_string", Value::BOOLEAN(binary_as_string)}}); - return TableFunction("parquet_scan", params, named_parameters)->Alias(parquet_file); -} - unordered_set Connection::GetTableNames(const string &query, const bool qualified) { return context->GetTableNames(query, qualified); } -shared_ptr Connection::RelationFromQuery(const string &query, const string &alias, const string &error) { - return RelationFromQuery(QueryRelation::ParseStatement(*context, query, error), alias); -} - -shared_ptr Connection::RelationFromQuery(unique_ptr select_stmt, const string &alias, - const string &query_p) { - return make_shared_ptr(context, std::move(select_stmt), alias, query_p); -} - void Connection::BeginTransaction() { TransactionInfo info(TransactionType::BEGIN_TRANSACTION); context->RunTransactionStatement(info); diff --git a/src/duckdb/src/main/context.cpp b/src/duckdb/src/main/context.cpp index 41d8e0d80..0ffa64af4 100644 --- a/src/duckdb/src/main/context.cpp +++ b/src/duckdb/src/main/context.cpp @@ -274,6 +274,12 @@ optional_ptr Context::TryGetQueryProfiler(optional_ptr c return context->TryGetQueryProfiler(); } +void Context::FastInterruptCheck() const { + if (context) { + context->FastInterruptCheck(); + } +} + void Context::InterruptCheck() const { if (context) { context->InterruptCheck(); diff --git a/src/duckdb/src/main/database.cpp b/src/duckdb/src/main/database.cpp index f4abcee00..d04e109ea 100644 --- a/src/duckdb/src/main/database.cpp +++ b/src/duckdb/src/main/database.cpp @@ -56,9 +56,8 @@ namespace duckdb { DBConfig::DBConfig() { + file_system = make_uniq(); compression_functions = make_uniq(); - encoding_functions = make_uniq(); - encoding_functions->Initialize(*this); arrow_extensions = make_uniq(); arrow_extensions->Initialize(*this); type_manager = make_uniq(*this); @@ -335,8 +334,9 @@ void DatabaseInstance::InitializeEmpty(DBConfig *user_config) { } void DatabaseInstance::StartScheduler() { - scheduler->SetThreads(config.options.maximum_threads, Settings::Get(config)); - scheduler->SetAsyncThreads(config.options.async_threads); + scheduler->SetThreads(NumericCast(Settings::Get(config)), + Settings::Get(config)); + scheduler->SetAsyncThreads(NumericCast(Settings::Get(config))); scheduler->RelaunchThreads(); } @@ -397,9 +397,6 @@ void DatabaseInstance::InitializeInstance(const char *database_path, DBConfig *u if (!config.options.database_type.empty() && !StringUtil::CIEquals(config.options.database_type, "duckdb")) { // if we are opening an extension database - load the extension - if (!config.file_system) { - throw InternalException("No file system!?"); - } auto storage_extension = StorageExtension::Find(config, config.options.database_type); if (!storage_extension) { ExtensionHelper::LoadExternalExtension(*this, *config.file_system, {config.options.database_type}); @@ -476,18 +473,12 @@ FileSystem &DatabaseInstance::GetLocalFileSystem() { return *local_db_file_system; } -static FileSystem &ResolveLocalFileSystem(DatabaseInstance &db, unique_ptr &owned) { - auto &vfs = static_cast(*db.config.file_system); - auto &default_fs = vfs.GetDefaultFileSystem(); - if (default_fs.IsLocalFileSystem()) { - return default_fs; - } - owned = make_uniq(); - return *owned; +static FileSystem &ResolveLocalFileSystem(DatabaseInstance &db) { + return static_cast(*db.config.file_system).GetLocalFileSystem(); } LocalDatabaseFileSystem::LocalDatabaseFileSystem(DatabaseInstance &db_p) - : db(db_p), local_fs(ResolveLocalFileSystem(db_p, owned_file_system)), database_opener(db_p) { + : db(db_p), local_fs(ResolveLocalFileSystem(db_p)), database_opener(db_p) { } FileSystem &LocalDatabaseFileSystem::GetFileSystem() const { @@ -530,6 +521,8 @@ Allocator &Allocator::Get(AttachedDatabase &db) { } void DatabaseInstance::Configure(DBConfig &new_config, const char *database_path) { + config.file_system = std::move(new_config.file_system); + new_config.file_system = make_uniq(); config.options = new_config.options; config.SetDisabledOptimizers(config.options.disabled_optimizers); config.user_settings = new_config.user_settings; @@ -552,18 +545,9 @@ void DatabaseInstance::Configure(DBConfig &new_config, const char *database_path config.SetDefaultTempDirectory(); } - if (new_config.options.http_proxy.empty()) { - HTTPProxySetting::ResetGlobal(this, config); - } - if (config.options.access_mode == AccessMode::UNDEFINED) { config.options.access_mode = AccessMode::READ_WRITE; } - if (new_config.file_system) { - config.file_system = std::move(new_config.file_system); - } else { - config.file_system = make_uniq(FileSystem::CreateLocal()); - } config.http_transport_manager->Initialize(config); if (database_path && !Settings::Get(*this)) { config.AddAllowedDatabasePath(database_path); @@ -577,12 +561,6 @@ void DatabaseInstance::Configure(DBConfig &new_config, const char *database_path if (config.options.maximum_memory == DConstants::INVALID_INDEX) { config.SetDefaultMaxMemory(); } - if (new_config.options.maximum_threads == DConstants::INVALID_INDEX) { - config.options.maximum_threads = config.GetSystemMaxThreads(*config.file_system); - } - if (new_config.options.async_threads == DConstants::INVALID_INDEX) { - config.options.async_threads = config.GetSystemMaxAsyncThreads(*config.file_system); - } config.allocator = std::move(new_config.allocator); if (!config.allocator) { config.allocator = make_uniq(); diff --git a/src/duckdb/src/main/database_manager.cpp b/src/duckdb/src/main/database_manager.cpp index 0347a3dac..b729292f2 100644 --- a/src/duckdb/src/main/database_manager.cpp +++ b/src/duckdb/src/main/database_manager.cpp @@ -183,7 +183,7 @@ shared_ptr DatabaseManager::AttachDatabase(ClientContext &cont // The database ACTUALLY exists, so we return it. return entry->second; } - context.InterruptCheck(); + context.FastInterruptCheck(); } // Returning in the loop above will also end the timer, otherwise, do it explicitly here. timer.EndTimer(); @@ -251,7 +251,8 @@ optional_ptr DatabaseManager::FinalizeAttach(ClientContext &co auto deleter = detached_db->ExtractDeleter(); meta_transaction.DetachDatabase(*detached_db); detached_db->OnDetach(context); - detached_db.reset(); + detached_db->MarkDetached(AttachedDatabase::GetDetachCloseAction(context)); + AttachedDatabase::InvokeCloseIfLastReference(detached_db, context); // Best-effort teardown: the replacement is already in effect, so a deleter failure must not // abort the statement mid-swap; TryDelete logs it as a warning instead. if (deleter) { @@ -287,6 +288,7 @@ void DatabaseManager::DetachDatabase(ClientContext &context, const Identifier &n auto deleter = attached_db->ExtractDeleter(); MetaTransaction::Get(context).DetachDatabase(*attached_db); attached_db->OnDetach(context); + attached_db->MarkDetached(AttachedDatabase::GetDetachCloseAction(context)); // DetachInternal removes the AttachedDatabase from the list of databases that can be referenced. AttachedDatabase::InvokeCloseIfLastReference(attached_db, context); diff --git a/src/duckdb/src/main/db_instance_cache.cpp b/src/duckdb/src/main/db_instance_cache.cpp index 33e676ae2..a2ae4ba5c 100644 --- a/src/duckdb/src/main/db_instance_cache.cpp +++ b/src/duckdb/src/main/db_instance_cache.cpp @@ -34,12 +34,7 @@ static string GetCacheKey(const string &database_p, const DBConfig &config) { // Currently the cache key is derived directly from the abs path, // but it can apply more transformations to the path if necessary string abs_database_path; - if (config.file_system) { - abs_database_path = GetDBAbsolutePath(database_p, *config.file_system); - } else { - auto tmp_fs = FileSystem::CreateLocal(); - abs_database_path = GetDBAbsolutePath(database_p, *tmp_fs); - } + abs_database_path = GetDBAbsolutePath(database_p, *config.file_system); #if defined(_WIN32) || defined(__APPLE__) return StringUtil::Lower(abs_database_path); #else // !(_WIN32 or __APPLE__) @@ -55,7 +50,8 @@ DBInstanceCache::~DBInstanceCache() { } shared_ptr DBInstanceCache::GetInstanceInternal(const string &database, const DBConfig &config, - std::unique_lock &db_instances_lock) { + std::unique_lock &db_instances_lock, + const db_config_match_t &is_same_config) { D_ASSERT(db_instances_lock.owns_lock()); auto cache_key = GetCacheKey(database, config); auto entry = db_instances.find(cache_key); @@ -96,7 +92,7 @@ shared_ptr DBInstanceCache::GetInstanceInternal(const string &database, return nullptr; } // the database instance exists - check that the config matches - if (db_instance->config != config) { + if (is_same_config ? !is_same_config(db_instance->config, config) : db_instance->config != config) { throw ConnectionException("Can't open a connection to same database file with a different configuration " "than existing connections"); } @@ -114,12 +110,7 @@ shared_ptr DBInstanceCache::CreateInstanceInternal(const string &databas const std::function &on_create) { D_ASSERT(db_instances_lock.owns_lock()); string abs_database_path; - if (config.file_system) { - abs_database_path = GetDBAbsolutePath(database, *config.file_system); - } else { - auto tmp_fs = FileSystem::CreateLocal(); - abs_database_path = GetDBAbsolutePath(database, *tmp_fs); - } + abs_database_path = GetDBAbsolutePath(database, *config.file_system); // Creates new instance string instance_path = abs_database_path; if (abs_database_path.rfind(IN_MEMORY_PATH, 0) == 0) { @@ -143,13 +134,23 @@ shared_ptr DBInstanceCache::CreateInstanceInternal(const string &databas config.db_cache_entry.reset(); throw; } + // before the instance is published: a call that finds the entry waits for the mutex held here + if (on_create) { + try { + on_create(*db_instance); + } catch (...) { + config.db_cache_entry.reset(); + db_instance.reset(); + throw; + } + } cache_entry->instance = db_instance->instance; } else { db_instances_lock.unlock(); db_instance = make_shared_ptr(instance_path, &config); - } - if (on_create) { - on_create(*db_instance); + if (on_create) { + on_create(*db_instance); + } } return db_instance; } @@ -173,7 +174,8 @@ shared_ptr DBInstanceCache::GetOrCreateInstance(const string &database, shared_ptr DBInstanceCache::GetOrCreateInstance(const string &database, DBConfig &config_dict, CacheBehavior cache_behavior, - const std::function &on_create) { + const std::function &on_create, + const db_config_match_t &is_same_config) { unique_lock lock(cache_lock, std::defer_lock); bool cache_instance = cache_behavior == CacheBehavior::ALWAYS_CACHE; if (cache_behavior == CacheBehavior::AUTOMATIC) { @@ -194,7 +196,7 @@ shared_ptr DBInstanceCache::GetOrCreateInstance(const string &database, // find a cache entry (can be done without unlocking) or we find a cache entry and the database is valid as // well (in this case we can return that database) lock.lock(); - auto instance = GetInstanceInternal(database, config_dict, lock); + auto instance = GetInstanceInternal(database, config_dict, lock, is_same_config); if (instance) { return instance; } diff --git a/src/duckdb/src/main/extension.cpp b/src/duckdb/src/main/extension.cpp index 0594ab388..fedae9d9a 100644 --- a/src/duckdb/src/main/extension.cpp +++ b/src/duckdb/src/main/extension.cpp @@ -92,7 +92,7 @@ string ParsedExtensionMetaData::GetInvalidMetadataError() { duckdb_capi_version, major, max_minor, max_patch); } } else { - throw InternalException("Unknown ABI type for extension: '%s'", extension_abi_metadata); + return StringUtil::Format("Unknown ABI type for extension: '%s'", PrettyPrintString(extension_abi_metadata)); } if (engine_platform != platform) { diff --git a/src/duckdb/src/main/extension/extension_helper.cpp b/src/duckdb/src/main/extension/extension_helper.cpp index 45f24d1b3..b8afd2273 100644 --- a/src/duckdb/src/main/extension/extension_helper.cpp +++ b/src/duckdb/src/main/extension/extension_helper.cpp @@ -251,7 +251,8 @@ bool ExtensionHelper::TryAutoLoadAvailableExtension(DatabaseInstance &instance, } static ExtensionUpdateResult UpdateExtensionInternal(ClientContext &context, DatabaseInstance &db, FileSystem &fs, - const string &full_extension_path, const string &extension_name) { + const string &full_extension_path, const string &extension_name, + const string &extension_directory) { ExtensionUpdateResult result; result.extension_name = extension_name; @@ -295,7 +296,7 @@ static ExtensionUpdateResult UpdateExtensionInternal(ClientContext &context, Dat return result; } - // update the extension from the repository it was installed from, so that it is verified against the same keys + // update the extension from the repository it was installed from auto repository_from_info = ExtensionRepository::GetRepositoryByUrl(extension_install_info->repository_url); repository_from_info.type = extension_install_info->repository_type; if (!extension_install_info->repository_name.empty()) { @@ -303,11 +304,38 @@ static ExtensionUpdateResult UpdateExtensionInternal(ClientContext &context, Dat } result.repository = repository_from_info.ToReadableString(); - // Force install the full url found in this file, enabling etags to ensure efficient updating + // an extension from a user-provided repository can only be updated while that repository exists and is trusted + if (extension_install_info->repository_type == ExtensionRepositoryType::USER_PROVIDED && + !extension_install_info->repository_name.empty()) { + ExtensionRepository user_repository; + bool repository_found; + try { + repository_found = ExtensionRepositoryManager::TryGetRepository( + db, fs, extension_install_info->repository_name, user_repository); + } catch (std::exception &) { + result.tag = ExtensionUpdateResultTag::REPOSITORY_UNREADABLE; + result.installed_version = result.prev_version; + return result; + } + if (!repository_found) { + result.tag = ExtensionUpdateResultTag::REPOSITORY_NOT_FOUND; + result.installed_version = result.prev_version; + return result; + } + if (!ExtensionRepositoryManager::TrustsRepository(db, user_repository)) { + result.tag = ExtensionUpdateResultTag::REPOSITORY_NOT_TRUSTED; + result.installed_version = result.prev_version; + return result; + } + repository_from_info = user_repository; + } + + // Force install from the repository ExtensionInstallOptions options; options.repository = repository_from_info; options.force_install = true; - options.use_etags = true; + options.use_etags = repository_from_info.path == extension_install_info->repository_url; + options.extension_directory = extension_directory; unique_ptr install_result; try { @@ -339,20 +367,22 @@ vector ExtensionHelper::UpdateExtensions(ClientContext &c #ifndef WASM_LOADABLE_EXTENSIONS identifier_set_t seen_extensions; - // scan the install directory for installed extensions - auto ext_directory = ExtensionHelper::ExtensionDirectory(db, fs); - fs.ListFiles(ext_directory, [&](const string &path, bool is_directory) { - if (!ExtensionHelper::IsInstalledExtensionFile(path)) { - return; - } + // scan the install directories for installed extensions, each is updated in the directory it was found in + for (auto &ext_directory : ExtensionHelper::GetInstalledExtensionDirectories(db, fs)) { + fs.ListFiles(ext_directory.path, [&](const string &path, bool is_directory) { + if (!ExtensionHelper::IsInstalledExtensionFile(path)) { + return; + } - auto extension_file_name = StringUtil::GetFileName(path); - auto extension_name = StringUtil::Split(extension_file_name, ".")[0]; + auto extension_file_name = StringUtil::GetFileName(path); + auto extension_name = StringUtil::Split(extension_file_name, ".")[0]; - seen_extensions.insert(Identifier(extension_name)); + seen_extensions.insert(Identifier(extension_name)); - result.push_back(UpdateExtensionInternal(context, db, fs, fs.JoinPath(ext_directory, path), extension_name)); - }); + result.push_back(UpdateExtensionInternal(context, db, fs, fs.JoinPath(ext_directory.path, path), + extension_name, ext_directory.extension_directory)); + }); + } #endif return result; @@ -365,7 +395,7 @@ ExtensionUpdateResult ExtensionHelper::UpdateExtension(ClientContext &context, c auto full_extension_path = fs.JoinPath(ext_directory, extension_name + ".duckdb_extension"); - auto update_result = UpdateExtensionInternal(context, db, fs, full_extension_path, extension_name); + auto update_result = UpdateExtensionInternal(context, db, fs, full_extension_path, extension_name, ext_directory); if (update_result.tag == ExtensionUpdateResultTag::NOT_INSTALLED) { throw InvalidInputException("Failed to update the extension '%s', the extension is not installed!", diff --git a/src/duckdb/src/main/extension/extension_install.cpp b/src/duckdb/src/main/extension/extension_install.cpp index efb4a3b1e..81a206813 100644 --- a/src/duckdb/src/main/extension/extension_install.cpp +++ b/src/duckdb/src/main/extension/extension_install.cpp @@ -149,7 +149,7 @@ vector ExtensionHelper::GetInstalledExtensionDirect auto extension_directories = GetExtensionDirectoryPath(db, fs); vector result; for (auto &directory : extension_directories) { - result.push_back({directory, string()}); + result.push_back({directory, string(), directory}); } // Per-repository install folders are discovered on disk, independent of whether their repository is trusted @@ -169,7 +169,7 @@ vector ExtensionHelper::GetInstalledExtensionDirect }); std::sort(repository_names.begin(), repository_names.end()); for (auto &name : repository_names) { - result.push_back({fs.JoinPath(repositories_directory, name), name}); + result.push_back({fs.JoinPath(repositories_directory, name), name, directory}); } } return result; @@ -239,7 +239,7 @@ unique_ptr ExtensionHelper::InstallExtension(DatabaseInsta // Install is currently a no-op return nullptr; #endif - string local_path = ExtensionDirectory(db, fs); + string local_path = options.extension_directory.empty() ? ExtensionDirectory(db, fs) : options.extension_directory; return InstallExtensionInternal(db, fs, local_path, extension, options); } @@ -251,7 +251,7 @@ unique_ptr ExtensionHelper::InstallExtension(ClientContext #endif auto &db = DatabaseInstance::GetDatabase(context); auto &fs = FileSystem::GetFileSystem(context); - string local_path = ExtensionDirectory(context); + string local_path = options.extension_directory.empty() ? ExtensionDirectory(context) : options.extension_directory; return InstallExtensionInternal(db, fs, local_path, extension, options, context); } diff --git a/src/duckdb/src/main/extension/extension_install_dynamic.cpp b/src/duckdb/src/main/extension/extension_install_dynamic.cpp index 1a80383e2..f675ee67b 100644 --- a/src/duckdb/src/main/extension/extension_install_dynamic.cpp +++ b/src/duckdb/src/main/extension/extension_install_dynamic.cpp @@ -341,8 +341,8 @@ InstallFromHttpUrl(DatabaseInstance &db, const string &url, const string &extens } QueryContext query_context(context); - auto fs = FileSystem::CreateLocal(); - WriteExtensionFiles(query_context, *fs, temp_path, local_extension_path, extension_data, extension_size, info, db); + auto &fs = FileSystem::GetLocal(db); + WriteExtensionFiles(query_context, fs, temp_path, local_extension_path, extension_data, extension_size, info, db); return make_uniq(info); } diff --git a/src/duckdb/src/main/extension/extension_loader.cpp b/src/duckdb/src/main/extension/extension_loader.cpp index c99f431c4..94595965d 100644 --- a/src/duckdb/src/main/extension/extension_loader.cpp +++ b/src/duckdb/src/main/extension/extension_loader.cpp @@ -12,7 +12,6 @@ #include "duckdb/parser/parsed_data/create_macro_info.hpp" #include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/table_function_catalog_entry.hpp" -#include "duckdb/parser/parsed_data/create_collation_info.hpp" #include "duckdb/main/extension_install_info.hpp" #include "duckdb/catalog/catalog.hpp" #include "duckdb/main/client_data.hpp" @@ -275,26 +274,6 @@ void ExtensionLoader::RegisterFunction(CreateMacroInfo &info) { system_catalog.CreateFunction(data, info); } -void ExtensionLoader::RegisterCollation(CreateCollationInfo &info) { - info.extension_name = GetRegisteredExtensionName(); - auto &system_catalog = Catalog::GetSystemCatalog(db); - auto data = CatalogTransaction::GetSystemTransaction(db); - if (info.GetQualifiedName().Schema() == DEFAULT_SCHEMA) { - info.SetQualifiedName(QualifiedName(info.GetQualifiedName().Catalog(), loader_info.extension_schema, - info.GetQualifiedName().Name())); - } - info.on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; - system_catalog.CreateCollation(data, info); - - // Also register as a function for serialisation - CreateScalarFunctionInfo finfo(info.function); - finfo.extension_name = GetRegisteredExtensionName(); - finfo.SetQualifiedName(QualifiedName(finfo.GetQualifiedName().Catalog(), loader_info.extension_schema, - finfo.GetQualifiedName().Name())); - finfo.on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; - system_catalog.CreateFunction(data, finfo); -} - void ExtensionLoader::RegisterCoordinateSystem(CreateCoordinateSystemInfo &info) { auto &system_catalog = Catalog::GetSystemCatalog(db); auto data = CatalogTransaction::GetSystemTransaction(db); diff --git a/src/duckdb/src/main/extension/extension_repository_manager.cpp b/src/duckdb/src/main/extension/extension_repository_manager.cpp index 1c44ee509..e88a2bf19 100644 --- a/src/duckdb/src/main/extension/extension_repository_manager.cpp +++ b/src/duckdb/src/main/extension/extension_repository_manager.cpp @@ -295,34 +295,48 @@ bool ExtensionRepositoryManager::TrustsRepository(DatabaseInstance &db, const Ex void ExtensionRepositoryManager::CheckNotLocked(DatabaseInstance &db) { // modifying the trusted repositories changes the set of keys that are trusted to sign extensions, so it is gated // by the configuration lock: a locked configuration freezes the trust store + if (Settings::Get(db)) { + throw InvalidInputException("Cannot add or drop extension repositories while the configuration is locked " + "(lock_configuration is true): they decide which signing keys are trusted, so they " + "are part of the configuration"); + } db.config.CheckLock(AllowExtensionRepositoriesSetting::Name); } -void ExtensionRepositoryManager::CheckCanCreate(DatabaseInstance &db, bool from_host) { +static constexpr const char *REPOSITORIES_DOCS = "https://duckdb.org/docs/stable/extensions/extension_repositories"; + +void ExtensionRepositoryManager::CheckCanCreate(DatabaseInstance &db, const string &name, bool from_host) { CheckNotLocked(db); // adding a repository adds a new trusted signing key, so the user must explicitly opt in first - except for a // repository resolved from its host: the name says who is trusted, and the host's own file says what, so the // 'hosts' default lets it through - switch (GetAccess(db)) { - case ExtensionRepositoryAccess::ALLOWED: + auto access = GetAccess(db); + if (access == ExtensionRepositoryAccess::ALLOWED || (from_host && access != ExtensionRepositoryAccess::FORBIDDEN)) { return; - case ExtensionRepositoryAccess::FORBIDDEN: - throw PermissionException("Adding extension repositories has been forbidden through configuration"); - case ExtensionRepositoryAccess::HOSTS_ONLY: - if (from_host) { - return; - } - throw PermissionException("Adding extension repositories by prefix is not permitted while " - "allow_extension_repositories='hosts_only': use `CREATE EXTENSION REPOSITORY ` " - "without a prefix, so that the host names its repository"); - default: - if (from_host) { - return; + } + string message; + if (access == ExtensionRepositoryAccess::FORBIDDEN) { + message = StringUtil::Format("Cannot create extension repository '%s': allow_extension_repositories is " + "'forbidden', which does not allow adding any repository.", + name); + } else { + // 'hosts' or 'hosts_only', and a prefix was given + message = StringUtil::Format("Cannot create extension repository '%s': allow_extension_repositories is '%s', " + "which does not allow adding arbitrary repositories, only repositories named by " + "their host.", + name, AccessToString(access)); + auto host_form = IsHostName(name) + ? StringUtil::Format("`CREATE EXTENSION REPOSITORY %s` without a prefix", name) + : string("`CREATE EXTENSION REPOSITORY ` without a prefix"); + if (access == ExtensionRepositoryAccess::HOSTS) { + // the default can still be opened up; 'hosts_only' cannot, the setting only tightens + message += "\nConsider changing the setting, or creating the repository by its host: " + host_form + "."; + } else { + message += "\nConsider creating the repository by its host: " + host_form + "."; } - throw PermissionException("Adding extension repositories is not enabled: set " - "allow_extension_repositories='allowed' to opt in, or use `CREATE EXTENSION " - "REPOSITORY ` without a prefix, so that the host names its repository"); } + message += StringUtil::Format("\nCheck the docs: %s", REPOSITORIES_DOCS); + throw PermissionException(message); } bool ExtensionRepositoryManager::TryNormalizeRepositoryName(const string &name, string &result) { @@ -352,10 +366,17 @@ static string RepositoryNameOfFile(const string &file_name) { string ExtensionRepositoryManager::NormalizeRepositoryName(const string &name) { string result; if (!TryNormalizeRepositoryName(name, result)) { + string hint; + for (auto c : name) { + if (static_cast(c) >= 0x80) { + hint = "\nAn internationalised host is spelled in its punycode form, 'xn--...', in quotes"; + break; + } + } throw InvalidInputException("Invalid extension repository name '%s': names cannot be empty and can only " "contain letters, digits, '_', '-' and '.' (not at the start or the end, and not " - "two in a row)", - name); + "two in a row)%s", + name, hint); } return result; } @@ -376,29 +397,49 @@ static constexpr const idx_t METADATA_FORMAT_VERSION = 1; //! and not localhost. A single word is not a host: it would be resolved through search domains to a host the user did //! not name. There is no stricter test short of the public suffix list; this one keeps out what is certainly not a //! public host -bool ExtensionRepositoryManager::IsHostName(const string &text) { - idx_t label_count = 0; - idx_t label_start = 0; - for (idx_t i = 0; i <= text.size(); i++) { - if (i < text.size() && text[i] != '.') { - auto c = text[i]; - if (!StringUtil::CharacterIsAlpha(c) && !StringUtil::CharacterIsDigit(c) && c != '-') { +//! A host label: one or more words of letters and digits joined by single dashes, so no leading or trailing dash and +//! no two dashes touching - except the one place two dashes are legitimate, the 'xn--' that opens an internationalised +//! label in its punycode (A-label) form: 'xn--mnchen-3ya' for 'münchen' +static bool IsHostLabel(const string &label) { + idx_t start = 0; + if (label.size() > 4 && StringUtil::CIEquals(label.substr(0, 4), "xn--")) { + start = 4; + } + idx_t word_length = 0; + for (idx_t i = start; i <= label.size(); i++) { + auto c = i < label.size() ? label[i] : '-'; + if (c == '-') { + if (word_length == 0) { return false; } + word_length = 0; continue; } - // end of a label - if (i == label_start || text[label_start] == '-' || text[i - 1] == '-') { + if (!StringUtil::CharacterIsAlpha(c) && !StringUtil::CharacterIsDigit(c)) { return false; } - label_count++; - label_start = i + 1; + word_length++; + } + return true; +} + +bool ExtensionRepositoryManager::IsHostName(const string &text) { + // two or more labels separated by single dots, the last one letters only (an IPv4 literal is not a host), and not + // localhost + if (text.empty() || text.front() == '.' || text.back() == '.' || text.find("..") != string::npos) { + return false; } - if (label_count < 2) { + auto labels = StringUtil::Split(text, '.'); + if (labels.size() < 2) { return false; } - for (idx_t i = text.rfind('.') + 1; i < text.size(); i++) { - if (!StringUtil::CharacterIsAlpha(text[i])) { + for (auto &label : labels) { + if (!IsHostLabel(label)) { + return false; + } + } + for (auto c : labels.back()) { + if (!StringUtil::CharacterIsAlpha(c)) { return false; } } @@ -519,12 +560,14 @@ ExtensionRepositoryResolution ExtensionRepositoryManager::ResolveRepositoryFromH // only a name that is a host on the public internet is reached: a single word would resolve through search // domains to a host the user did not name, an IP literal or localhost is nobody's statement if (!IsHostName(name)) { - throw InvalidInputException( - "Cannot create extension repository '%s': '%s' is not a host name. A host has two or " - "more labels of letters, digits and '-' separated by dots, the last one letters " - "only, and is not localhost\nUse `WITH PREFIX ''` to name the repository's " - "location directly", - name_p, name); + throw InvalidInputException("Cannot create extension repository '%s': '%s' is not a host name. A host has two " + "or more labels separated by " + "dots, each label words of letters and digits joined by single dashes (or a " + "punycode label, 'xn--...'), the " + "last label letters only, and is not localhost\nUse `WITH PREFIX ''` to name " + "the repository's location " + "directly", + name_p, name); } ExtensionRepositoryResolution resolution; resolution.host = name; @@ -541,10 +584,14 @@ ExtensionRepositoryResolution ExtensionRepositoryManager::ResolveRepositoryFromH // a policy refusal (verification switched off for the url): not something the host did throw; } catch (std::exception &ex) { + // the inner message already names the file and the reason ("Failed to read the host's metadata file '': + // HTTP 404 Not Found"); say what it means for the statement, and what else can be done ErrorData error(ex); - throw IOException("Cannot create extension repository '%s': the host does not serve a metadata file (failed to " - "read '%s': %s)\nUse `WITH PREFIX ''` to name the repository's location directly", - name, metadata_path, error.RawMessage()); + throw IOException( + "Cannot create extension repository '%s': %s\nA repository is resolved from its host through " + "https:///.well-known/duckdb-extension-repo.json; use `WITH PREFIX ''` to name the " + "repository's location directly", + name, error.RawMessage()); } RepositoryJSONDocument document(yyjson_read(contents.c_str(), contents.size(), 0)); auto root = ReadVersionedObject(document, metadata_path); @@ -763,7 +810,7 @@ ExtensionRepository ExtensionRepositoryManager::CreateRepository(DatabaseInstanc } } // from here on something is added: the opt-in applies - CheckCanCreate(db, from_host); + CheckCanCreate(db, name, from_host); ExtensionRepository repository(name, requested.path, requested.public_keys); vector public_keys; @@ -787,7 +834,7 @@ ExtensionRepository ExtensionRepositoryManager::CreateRepository(DatabaseInstanc name); } // the fetches took time: the access may have been tightened meanwhile, so check again before persisting - CheckCanCreate(db, from_host); + CheckCanCreate(db, name, from_host); if (!fs.DirectoryExists(directory)) { fs.CreateDirectoriesRecursive(directory); @@ -842,6 +889,10 @@ void ExtensionRepositoryManager::DropRepository(DatabaseInstance &db, FileSystem CheckNotLocked(db); auto name = NormalizeRepositoryName(name_p); + if (!ExtensionRepository::TryGetRepositoryUrl(name).empty()) { + // the built-in repositories are not stored files: there is nothing to remove, and no way to distrust them + throw NotImplementedException("Extension repository '%s' is built in and cannot be dropped", name); + } auto file_path = GetRepositoryPath(db, fs, name); if (!fs.FileExists(file_path)) { if (on_entry_not_found == OnEntryNotFound::RETURN_NULL) { diff --git a/src/duckdb/src/main/http/http_transport_manager.cpp b/src/duckdb/src/main/http/http_transport_manager.cpp index 42289099c..ccedb156c 100644 --- a/src/duckdb/src/main/http/http_transport_manager.cpp +++ b/src/duckdb/src/main/http/http_transport_manager.cpp @@ -5,6 +5,7 @@ #include "duckdb/common/limits.hpp" #include "duckdb/main/config.hpp" #include "duckdb/main/database.hpp" +#include "duckdb/main/settings.hpp" namespace duckdb { @@ -259,12 +260,13 @@ void HTTPTransportManager::Initialize(const DBConfig &config) { initialized = true; } -idx_t HTTPTransportManager::AutomaticCapacity(const DBConfig &config) { +idx_t HTTPTransportManager::AutomaticCapacity(const DBConfig &config, optional_idx async_threads) { auto &fs = *config.file_system; - auto io_concurrency = config.options.async_threads == DConstants::INVALID_INDEX - ? DBConfig::GetSystemMaxAsyncThreads(fs) - : config.options.async_threads; - return CalculateCapacity(DBConfig::GetSystemMaxThreads(fs), FileSystem::GetFileDescriptorLimit(), io_concurrency); + if (!async_threads.IsValid()) { + async_threads = NumericCast(Settings::Get(config)); + } + return CalculateCapacity(DBConfig::GetSystemMaxThreads(fs), FileSystem::GetFileDescriptorLimit(), + async_threads.GetIndex()); } idx_t HTTPTransportManager::GetCapacity() const { diff --git a/src/duckdb/src/main/http/http_util.cpp b/src/duckdb/src/main/http/http_util.cpp index 5dce7a8d7..901fcc114 100644 --- a/src/duckdb/src/main/http/http_util.cpp +++ b/src/duckdb/src/main/http/http_util.cpp @@ -412,6 +412,15 @@ void HTTPUtil::DecomposeURL(const string &input, string &path_out, string &proto } } +// A request error can be a serialized exception that callers parse back with ErrorData, so it has to stay valid JSON. +static string AppendToRequestError(const string &request_error, const string ¬e) { + if (request_error.empty() || request_error[0] != '{') { + return request_error + note; + } + ErrorData error(request_error); + return Exception::ToJSON(error.ExtraInfo(), error.Type(), error.RawMessage() + note); +} + // Handlers turn error statuses into exceptions; rebuild the response they saw so it can be judged like a received one. static unique_ptr ResponseFromError(const ErrorData &error) { auto &extra_info = error.ExtraInfo(); @@ -472,15 +481,16 @@ HTTPUtil::RunRequestWithRetry(const std::function(void) if (response) { response->url = request.url; } - } catch (IOException &e) { - exception_error = e.what(); - caught_e = std::current_exception(); + } catch (const std::exception &e) { caught_error = ErrorData(e); - } catch (HTTPException &e) { + if (caught_error.Type() != ExceptionType::IO && caught_error.Type() != ExceptionType::HTTP) { + throw; + } exception_error = e.what(); caught_e = std::current_exception(); - caught_error = ErrorData(e); - caught_response = ResponseFromError(caught_error); + if (caught_error.Type() == ExceptionType::HTTP) { + caught_response = ResponseFromError(caught_error); + } } if (response) { @@ -536,12 +546,12 @@ HTTPUtil::RunRequestWithRetry(const std::function(void) if (request.try_request) { if (!response) { response = make_uniq(HTTPStatusCode::INVALID); - response->request_error = - (exception_error.empty() ? "Unknown error" : std::move(exception_error)) + quota_note; - } else if (!quota_note.empty()) { + response->request_error = exception_error.empty() ? "Unknown error" : std::move(exception_error); + } + if (!quota_note.empty()) { // A received error keeps its status; the note goes to the field GetError() reports. if (response->HasRequestError()) { - response->request_error += quota_note; + response->request_error = AppendToRequestError(response->request_error, quota_note); } else { response->reason += quota_note; } @@ -571,7 +581,7 @@ HTTPUtil::RunRequestWithRetry(const std::function(void) void HTTPParams::Initialize(optional_ptr opener) { db = FileOpener::TryGetDatabase(opener); if (db) { - auto &http_proxy_setting = db->config.options.http_proxy; + auto http_proxy_setting = Settings::Get(db->config); if (!http_proxy_setting.empty()) { idx_t port; string host; diff --git a/src/duckdb/src/main/relation.cpp b/src/duckdb/src/main/relation.cpp deleted file mode 100644 index ba58e2ce5..000000000 --- a/src/duckdb/src/main/relation.cpp +++ /dev/null @@ -1,438 +0,0 @@ -#include "duckdb/main/relation.hpp" -#include "duckdb/common/printer.hpp" -#include "duckdb/parser/parser.hpp" -#include "duckdb/main/relation/aggregate_relation.hpp" -#include "duckdb/main/relation/cross_product_relation.hpp" -#include "duckdb/main/relation/distinct_relation.hpp" -#include "duckdb/main/relation/explain_relation.hpp" -#include "duckdb/main/relation/filter_relation.hpp" -#include "duckdb/main/relation/insert_relation.hpp" -#include "duckdb/main/relation/limit_relation.hpp" -#include "duckdb/main/relation/order_relation.hpp" -#include "duckdb/main/relation/projection_relation.hpp" -#include "duckdb/main/relation/setop_relation.hpp" -#include "duckdb/main/relation/subquery_relation.hpp" -#include "duckdb/main/relation/table_function_relation.hpp" -#include "duckdb/main/relation/create_table_relation.hpp" -#include "duckdb/main/relation/create_view_relation.hpp" -#include "duckdb/main/relation/write_csv_relation.hpp" -#include "duckdb/main/relation/write_parquet_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/parser/tableref/subqueryref.hpp" -#include "duckdb/parser/statement/select_statement.hpp" -#include "duckdb/parser/expression/conjunction_expression.hpp" -#include "duckdb/parser/expression/columnref_expression.hpp" -#include "duckdb/main/relation/join_relation.hpp" -#include "duckdb/main/relation/value_relation.hpp" -#include "duckdb/parser/statement/explain_statement.hpp" - -namespace duckdb { - -shared_ptr Relation::Project(const string &select_list) { - return Project(select_list, vector()); -} - -shared_ptr Relation::Project(const string &expression, const string &alias) { - return Project(expression, vector({alias})); -} - -shared_ptr Relation::Project(const string &select_list, const vector &aliases) { - auto expressions = Parser(*context->GetContext()).ParseExpressionList(select_list); - return make_shared_ptr(shared_from_this(), std::move(expressions), - StringsToIdentifiers(aliases)); -} - -shared_ptr Relation::Project(const vector &expressions) { - vector aliases; - return Project(expressions, aliases); -} - -shared_ptr Relation::Project(vector> expressions, - const vector &aliases) { - return make_shared_ptr(shared_from_this(), std::move(expressions), - StringsToIdentifiers(aliases)); -} - -static vector> StringListToExpressionList(ClientContext &context, - const vector &expressions) { - if (expressions.empty()) { - throw ParserException("Zero expressions provided"); - } - vector> result_list; - for (auto &expr : expressions) { - auto expression_list = Parser(context).ParseExpressionList(expr); - if (expression_list.size() != 1) { - throw ParserException("Expected a single expression in the expression list"); - } - result_list.push_back(std::move(expression_list[0])); - } - return result_list; -} - -shared_ptr Relation::Project(const vector &expressions, const vector &aliases) { - auto result_list = StringListToExpressionList(*context->GetContext(), expressions); - return make_shared_ptr(shared_from_this(), std::move(result_list), - StringsToIdentifiers(aliases)); -} - -shared_ptr Relation::Filter(const string &expression) { - auto expression_list = Parser(*context->GetContext()).ParseExpressionList(expression); - if (expression_list.size() != 1) { - throw ParserException("Expected a single expression as filter condition"); - } - return Filter(std::move(expression_list[0])); -} - -shared_ptr Relation::Filter(unique_ptr expression) { - return make_shared_ptr(shared_from_this(), std::move(expression)); -} - -shared_ptr Relation::Filter(const vector &expressions) { - // if there are multiple expressions, we AND them together - auto expression_list = StringListToExpressionList(*context->GetContext(), expressions); - D_ASSERT(!expression_list.empty()); - - auto expr = std::move(expression_list[0]); - for (idx_t i = 1; i < expression_list.size(); i++) { - expr = make_uniq(ExpressionType::CONJUNCTION_AND, std::move(expr), - std::move(expression_list[i])); - } - return make_shared_ptr(shared_from_this(), std::move(expr)); -} - -shared_ptr Relation::Limit(int64_t limit, int64_t offset) { - return make_shared_ptr(shared_from_this(), limit, offset); -} - -shared_ptr Relation::Order(const string &expression) { - auto order_list = Parser(*context->GetContext()).ParseOrderList(expression); - return Order(std::move(order_list)); -} - -shared_ptr Relation::Order(vector order_list) { - return make_shared_ptr(shared_from_this(), std::move(order_list)); -} - -shared_ptr Relation::Order(const vector &expressions) { - if (expressions.empty()) { - throw ParserException("Zero ORDER BY expressions provided"); - } - vector order_list; - for (auto &expression : expressions) { - auto inner_list = Parser(*context->GetContext()).ParseOrderList(expression); - if (inner_list.size() != 1) { - throw ParserException("Expected a single ORDER BY expression in the expression list"); - } - order_list.push_back(std::move(inner_list[0])); - } - return Order(std::move(order_list)); -} - -shared_ptr Relation::Join(const shared_ptr &other, const string &condition, JoinType type, - JoinRefType ref_type) { - auto expression_list = Parser(*context->GetContext()).ParseExpressionList(condition); - D_ASSERT(!expression_list.empty()); - return Join(other, std::move(expression_list), type, ref_type); -} - -shared_ptr Relation::Join(const shared_ptr &other, - vector> expression_list, JoinType type, - JoinRefType ref_type) { - if (expression_list.size() > 1 || expression_list[0]->GetExpressionType() == ExpressionType::COLUMN_REF) { - // multiple columns or single column ref: the condition is a USING list - vector using_columns; - for (auto &expr : expression_list) { - if (expr->GetExpressionType() != ExpressionType::COLUMN_REF) { - throw ParserException("Expected a single expression as join condition"); - } - auto &colref = expr->Cast(); - if (colref.IsQualified()) { - throw ParserException("Expected unqualified column for column in USING clause"); - } - using_columns.push_back(colref.ColumnNames()[0]); - } - return make_shared_ptr(shared_from_this(), other, std::move(using_columns), type, ref_type); - } else { - // single expression that is not a column reference: use the expression as a join condition - return make_shared_ptr(shared_from_this(), other, std::move(expression_list[0]), type, ref_type); - } -} - -shared_ptr Relation::CrossProduct(const shared_ptr &other, JoinRefType join_ref_type) { - return make_shared_ptr(shared_from_this(), other, join_ref_type); -} - -shared_ptr Relation::Union(const shared_ptr &other) { - return make_shared_ptr(shared_from_this(), other, SetOperationType::UNION, true); -} - -shared_ptr Relation::Except(const shared_ptr &other) { - return make_shared_ptr(shared_from_this(), other, SetOperationType::EXCEPT, true); -} - -shared_ptr Relation::Intersect(const shared_ptr &other) { - return make_shared_ptr(shared_from_this(), other, SetOperationType::INTERSECT, true); -} - -shared_ptr Relation::Distinct() { - return make_shared_ptr(shared_from_this()); -} - -shared_ptr Relation::Alias(const string &alias) { - return make_shared_ptr(shared_from_this(), alias); -} - -shared_ptr Relation::Aggregate(const string &aggregate_list) { - auto expression_list = Parser(*context->GetContext()).ParseExpressionList(aggregate_list); - return make_shared_ptr(shared_from_this(), std::move(expression_list)); -} - -shared_ptr Relation::Aggregate(vector> expressions) { - return make_shared_ptr(shared_from_this(), std::move(expressions)); -} - -shared_ptr Relation::Aggregate(const string &aggregate_list, const string &group_list) { - auto expression_list = Parser(*context->GetContext()).ParseExpressionList(aggregate_list); - auto groups = Parser(*context->GetContext()).ParseGroupByList(group_list); - return make_shared_ptr(shared_from_this(), std::move(expression_list), std::move(groups)); -} - -shared_ptr Relation::Aggregate(const vector &aggregates) { - auto aggregate_list = StringListToExpressionList(*context->GetContext(), aggregates); - return make_shared_ptr(shared_from_this(), std::move(aggregate_list)); -} - -shared_ptr Relation::Aggregate(const vector &aggregates, const vector &groups) { - auto aggregate_list = StringUtil::Join(aggregates, ", "); - auto group_list = StringUtil::Join(groups, ", "); - return this->Aggregate(aggregate_list, group_list); -} - -shared_ptr Relation::Aggregate(vector> expressions, const string &group_list) { - auto groups = Parser(*context->GetContext()).ParseGroupByList(group_list); - return make_shared_ptr(shared_from_this(), std::move(expressions), std::move(groups)); -} - -Identifier Relation::GetAlias() { - return Identifier(alias); -} - -unique_ptr Relation::GetTableRef() { - auto select = make_uniq(); - select->node = GetQueryNode(); - return make_uniq(std::move(select), GetAlias()); -} - -unique_ptr Relation::Execute() { - return context->GetContext()->Execute(shared_from_this()); -} - -unique_ptr Relation::ExecuteOrThrow() { - auto res = Execute(); - D_ASSERT(res); - res->ThrowIfError(); - return res; -} - -BoundStatement Relation::Bind(Binder &binder) { - SelectStatement stmt; - stmt.node = GetQueryNode(); - return binder.Bind(stmt.Cast()); -} - -shared_ptr Relation::InsertRel(const Identifier &schema_name, const Identifier &table_name) { - return InsertRel(Identifier::InvalidCatalog(), schema_name, table_name); -} - -shared_ptr Relation::InsertRel(const Identifier &catalog_name, const Identifier &schema_name, - const Identifier &table_name) { - return make_shared_ptr(shared_from_this(), catalog_name, schema_name, table_name); -} - -void Relation::Insert(const Identifier &table_name) { - Insert(Identifier::InvalidSchema(), table_name); -} - -void Relation::Insert(const Identifier &schema_name, const Identifier &table_name) { - Insert(Identifier::InvalidCatalog(), schema_name, table_name); -} - -void Relation::Insert(const Identifier &catalog_name, const Identifier &schema_name, const Identifier &table_name) { - auto insert = InsertRel(catalog_name, schema_name, table_name); - auto res = insert->Execute(); - res->ThrowIfError("Failed to insert into table '" + table_name + "': "); -} - -void Relation::Insert(const vector> &values) { - throw InvalidInputException("INSERT with values can only be used on base tables!"); -} - -void Relation::Insert(vector>> &&expressions) { - (void)std::move(expressions); - throw InvalidInputException("INSERT with expressions can only be used on base tables!"); -} - -shared_ptr Relation::CreateRel(const Identifier &schema_name, const Identifier &table_name, bool temporary, - OnCreateConflict on_conflict) { - return CreateRel(Identifier::InvalidCatalog(), schema_name, table_name, temporary, on_conflict); -} - -shared_ptr Relation::CreateRel(const Identifier &catalog_name, const Identifier &schema_name, - const Identifier &table_name, bool temporary, OnCreateConflict on_conflict) { - return make_shared_ptr(shared_from_this(), catalog_name, schema_name, table_name, temporary, - on_conflict); -} - -void Relation::Create(const Identifier &table_name, bool temporary, OnCreateConflict on_conflict) { - Create(Identifier::InvalidCatalog(), Identifier::InvalidSchema(), table_name, temporary, on_conflict); -} - -void Relation::Create(const Identifier &schema_name, const Identifier &table_name, bool temporary, - OnCreateConflict on_conflict) { - Create(Identifier::InvalidCatalog(), schema_name, table_name, temporary, on_conflict); -} - -void Relation::Create(const Identifier &catalog_name, const Identifier &schema_name, const Identifier &table_name, - bool temporary, OnCreateConflict on_conflict) { - if (table_name.empty()) { - throw ParserException("Empty table name not supported"); - } - auto create = CreateRel(catalog_name, schema_name, table_name, temporary, on_conflict); - auto res = create->Execute(); - res->ThrowIfError("Failed to create table '" + table_name + "': "); -} - -shared_ptr Relation::WriteCSVRel(const string &csv_file, identifier_map_t> options) { - return make_shared_ptr(shared_from_this(), csv_file, std::move(options)); -} - -void Relation::WriteCSV(const string &csv_file, identifier_map_t> options) { - auto write_csv = WriteCSVRel(csv_file, std::move(options)); - auto res = write_csv->Execute(); - res->ThrowIfError("Failed to write '" + csv_file + "': "); -} - -shared_ptr Relation::WriteParquetRel(const string &parquet_file, identifier_map_t> options) { - auto write_parquet = - make_shared_ptr(shared_from_this(), parquet_file, std::move(options)); - return std::move(write_parquet); -} - -void Relation::WriteParquet(const string &parquet_file, identifier_map_t> options) { - auto write_parquet = WriteParquetRel(parquet_file, std::move(options)); - auto res = write_parquet->Execute(); - res->ThrowIfError("Failed to write '" + parquet_file + "': "); -} - -shared_ptr Relation::CreateView(const Identifier &name, bool replace, bool temporary) { - return CreateView(Identifier::InvalidSchema(), name, replace, temporary); -} - -shared_ptr Relation::CreateView(const Identifier &schema_name, const Identifier &name, bool replace, - bool temporary) { - auto view = make_shared_ptr(shared_from_this(), schema_name, name, replace, temporary); - auto res = view->Execute(); - res->ThrowIfError("Failed to create view '" + name + "': "); - return shared_from_this(); -} - -unique_ptr Relation::Query(const string &sql) const { - return context->GetContext()->Query(sql, QueryParameters()); -} - -unique_ptr Relation::Query(const Identifier &name, const string &sql) { - bool replace = true; - bool temp = IsReadOnly(); - CreateView(name, replace, temp); - return Query(sql); -} - -unique_ptr Relation::Explain(ExplainType type, const ProfilerPrintFormat &format) { - auto explain = make_shared_ptr(shared_from_this(), type, format); - return explain->Execute(); -} - -void Relation::TryBindRelation(vector &columns) { - context->TryBindRelation(*this, columns); -} - -void Relation::Update(const string &update, const string &condition) { - throw InvalidInputException("UPDATE can only be used on base tables!"); -} - -void Relation::Update(vector, // NOLINT: unused variable / copied on every invocation ... - vector> &&update, // NOLINT: unused variable - unique_ptr condition) { // NOLINT: unused variable - (void)std::move(update); - (void)std::move(condition); - throw InvalidInputException("UPDATE can only be used on base tables!"); -} - -void Relation::Delete(const string &condition) { - throw InvalidInputException("DELETE can only be used on base tables!"); -} - -shared_ptr Relation::TableFunction(const std::string &fname, const vector &values, - const named_parameter_map_t &named_parameters) { - return make_shared_ptr(context->GetContext(), fname, values, named_parameters, - shared_from_this()); -} - -shared_ptr Relation::TableFunction(const std::string &fname, const vector &values) { - return make_shared_ptr(context->GetContext(), fname, values, shared_from_this()); -} - -string Relation::ToString() { - string str; - str += "---------------------\n"; - str += "--- Relation Tree ---\n"; - str += "---------------------\n"; - str += ToString(0); - str += "\n\n"; - str += "---------------------\n"; - str += "-- Result Columns --\n"; - str += "---------------------\n"; - auto &cols = Columns(); - for (idx_t i = 0; i < cols.size(); i++) { - str += "- " + cols[i].Name() + " (" + cols[i].Type().ToString() + ")\n"; - } - return str; -} - -// LCOV_EXCL_START -string Relation::GetQuery() { - return GetQueryNode()->ToString(); -} - -void Relation::Head(idx_t limit) { - auto limit_node = Limit(NumericCast(limit)); - limit_node->Execute()->Print(); -} -// LCOV_EXCL_STOP - -void Relation::Print() { - Printer::Print(ToString()); -} - -string Relation::RenderWhitespace(idx_t depth) { - return string(depth * 2, ' '); -} - -void Relation::AddExternalDependency(shared_ptr dependency) { - external_dependencies.push_back(std::move(dependency)); -} - -vector> Relation::GetAllDependencies() { - vector> all_dependencies; - Relation *cur = this; - while (cur) { - for (auto &dep : cur->external_dependencies) { - all_dependencies.push_back(dep); - } - cur = cur->ChildRelation(); - } - return all_dependencies; -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/aggregate_relation.cpp b/src/duckdb/src/main/relation/aggregate_relation.cpp deleted file mode 100644 index 340fb33f1..000000000 --- a/src/duckdb/src/main/relation/aggregate_relation.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include "duckdb/main/relation/aggregate_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/tableref/subqueryref.hpp" - -namespace duckdb { - -AggregateRelation::AggregateRelation(shared_ptr child_p, - vector> parsed_expressions) - : Relation(child_p->context, RelationType::AGGREGATE_RELATION), expressions(std::move(parsed_expressions)), - child(std::move(child_p)) { - // bind the expressions - TryBindRelation(columns); -} - -AggregateRelation::AggregateRelation(shared_ptr child_p, - vector> parsed_expressions, GroupByNode groups_p) - : Relation(child_p->context, RelationType::AGGREGATE_RELATION), expressions(std::move(parsed_expressions)), - groups(std::move(groups_p)), child(std::move(child_p)) { - // bind the expressions - Relation::TryBindRelation(columns); -} - -AggregateRelation::AggregateRelation(shared_ptr child_p, - vector> parsed_expressions, - vector> groups_p) - : Relation(child_p->context, RelationType::AGGREGATE_RELATION), expressions(std::move(parsed_expressions)), - child(std::move(child_p)) { - if (!groups_p.empty()) { - // explicit groups provided: use standard handling - GroupingSet grouping_set; - for (idx_t i = 0; i < groups_p.size(); i++) { - groups.group_expressions.push_back(std::move(groups_p[i])); - grouping_set.emplace(i); - } - groups.grouping_sets.push_back(std::move(grouping_set)); - } - // bind the expressions - TryBindRelation(columns); -} - -unique_ptr AggregateRelation::GetQueryNode() { - auto child_ptr = child.get(); - while (child_ptr->InheritsColumnBindings()) { - child_ptr = child_ptr->ChildRelation(); - } - unique_ptr result; - if (child_ptr->type == RelationType::JOIN_RELATION) { - // child node is a join: push projection into the child query node - result = child->GetQueryNode(); - } else { - // child node is not a join: create a new select node and push the child as a table reference - auto select = make_uniq(); - select->from_table = child->GetTableRef(); - result = std::move(select); - } - D_ASSERT(result->type == QueryNodeType::SELECT_NODE); - auto &select_node = result->Cast(); - if (!groups.group_expressions.empty()) { - select_node.aggregate_handling = AggregateHandling::STANDARD_HANDLING; - select_node.groups = groups.Copy(); - } else { - // no groups provided: automatically figure out groups (if any) - select_node.aggregate_handling = AggregateHandling::FORCE_AGGREGATES; - } - select_node.select_list.clear(); - for (auto &expr : expressions) { - select_node.select_list.push_back(expr->Copy()); - } - return result; -} - -Identifier AggregateRelation::GetAlias() { - return child->GetAlias(); -} - -const vector &AggregateRelation::Columns() { - return columns; -} - -string AggregateRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Aggregate ["; - for (idx_t i = 0; i < expressions.size(); i++) { - if (i != 0) { - str += ", "; - } - str += expressions[i]->ToString(); - } - str += "]\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/create_table_relation.cpp b/src/duckdb/src/main/relation/create_table_relation.cpp deleted file mode 100644 index e2f11bde8..000000000 --- a/src/duckdb/src/main/relation/create_table_relation.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "duckdb/main/relation/create_table_relation.hpp" -#include "duckdb/parser/statement/create_statement.hpp" -#include "duckdb/parser/statement/select_statement.hpp" -#include "duckdb/parser/parsed_data/create_table_info.hpp" -#include "duckdb/planner/binder.hpp" - -namespace duckdb { - -CreateTableRelation::CreateTableRelation(shared_ptr child_p, Identifier schema_name, Identifier table_name, - bool temporary_p, OnCreateConflict on_conflict) - : Relation(child_p->context, RelationType::CREATE_TABLE_RELATION), child(std::move(child_p)), - schema_name(std::move(schema_name)), table_name(std::move(table_name)), temporary(temporary_p), - on_conflict(on_conflict) { - TryBindRelation(columns); -} - -CreateTableRelation::CreateTableRelation(shared_ptr child_p, Identifier catalog_name, Identifier schema_name, - Identifier table_name, bool temporary_p, OnCreateConflict on_conflict) - : Relation(child_p->context, RelationType::CREATE_TABLE_RELATION), child(std::move(child_p)), - catalog_name(std::move(catalog_name)), schema_name(std::move(schema_name)), table_name(std::move(table_name)), - temporary(temporary_p), on_conflict(on_conflict) { - TryBindRelation(columns); -} - -BoundStatement CreateTableRelation::Bind(Binder &binder) { - auto select = make_uniq(); - select->node = child->GetQueryNode(); - - CreateStatement stmt; - auto info = make_uniq(); - info->SetQualifiedName(QualifiedName(catalog_name, schema_name, table_name)); - info->query = std::move(select); - info->on_conflict = on_conflict; - info->temporary = temporary; - stmt.info = std::move(info); - return binder.Bind(stmt.Cast()); -} - -unique_ptr CreateTableRelation::GetQueryNode() { - throw InternalException("Cannot create a query node from a create table relation"); -} - -string CreateTableRelation::GetQuery() { - return string(); -} - -const vector &CreateTableRelation::Columns() { - return columns; -} - -string CreateTableRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Create Table\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/create_view_relation.cpp b/src/duckdb/src/main/relation/create_view_relation.cpp deleted file mode 100644 index b40ab159d..000000000 --- a/src/duckdb/src/main/relation/create_view_relation.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "duckdb/main/relation/create_view_relation.hpp" -#include "duckdb/parser/statement/create_statement.hpp" -#include "duckdb/parser/parsed_data/create_view_info.hpp" -#include "duckdb/planner/binder.hpp" - -namespace duckdb { - -CreateViewRelation::CreateViewRelation(shared_ptr child_p, Identifier view_name_p, bool replace_p, - bool temporary_p) - : Relation(child_p->context, RelationType::CREATE_VIEW_RELATION), child(std::move(child_p)), - view_name(std::move(view_name_p)), replace(replace_p), temporary(temporary_p) { - TryBindRelation(columns); -} - -CreateViewRelation::CreateViewRelation(shared_ptr child_p, Identifier schema_name_p, Identifier view_name_p, - bool replace_p, bool temporary_p) - : Relation(child_p->context, RelationType::CREATE_VIEW_RELATION), child(std::move(child_p)), - schema_name(std::move(schema_name_p)), view_name(std::move(view_name_p)), replace(replace_p), - temporary(temporary_p) { - TryBindRelation(columns); -} - -BoundStatement CreateViewRelation::Bind(Binder &binder) { - auto select = make_uniq(); - select->node = child->GetQueryNode(); - - CreateStatement stmt; - auto info = make_uniq(); - info->query = std::move(select); - info->temporary = temporary; - info->SetQualifiedName(QualifiedName(Identifier(), schema_name, view_name)); - info->on_conflict = replace ? OnCreateConflict::REPLACE_ON_CONFLICT : OnCreateConflict::ERROR_ON_CONFLICT; - stmt.info = std::move(info); - return binder.Bind(stmt.Cast()); -} - -unique_ptr CreateViewRelation::GetQueryNode() { - throw InternalException("Cannot create a query node from an update relation"); -} - -string CreateViewRelation::GetQuery() { - return string(); -} - -const vector &CreateViewRelation::Columns() { - return columns; -} - -string CreateViewRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Create View\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/cross_product_relation.cpp b/src/duckdb/src/main/relation/cross_product_relation.cpp deleted file mode 100644 index e0645fae1..000000000 --- a/src/duckdb/src/main/relation/cross_product_relation.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include "duckdb/main/relation/cross_product_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/parser/tableref/joinref.hpp" - -namespace duckdb { - -CrossProductRelation::CrossProductRelation(shared_ptr left_p, shared_ptr right_p, - JoinRefType ref_type) - : Relation(left_p->context, RelationType::CROSS_PRODUCT_RELATION), left(std::move(left_p)), - right(std::move(right_p)), ref_type(ref_type) { - if (left->context->GetContext() != right->context->GetContext()) { - throw InvalidInputException("Cannot combine LEFT and RIGHT relations of different connections!"); - } - TryBindRelation(columns); -} - -unique_ptr CrossProductRelation::GetQueryNode() { - auto result = make_uniq(); - result->select_list.push_back(make_uniq()); - result->from_table = GetTableRef(); - return std::move(result); -} - -unique_ptr CrossProductRelation::GetTableRef() { - auto cross_product_ref = make_uniq(ref_type); - cross_product_ref->left = left->GetTableRef(); - cross_product_ref->right = right->GetTableRef(); - return std::move(cross_product_ref); -} - -const vector &CrossProductRelation::Columns() { - return this->columns; -} - -string CrossProductRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth); - str = "Cross Product"; - return str + "\n" + left->ToString(depth + 1) + right->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/delete_relation.cpp b/src/duckdb/src/main/relation/delete_relation.cpp deleted file mode 100644 index 362a0bd17..000000000 --- a/src/duckdb/src/main/relation/delete_relation.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include "duckdb/main/relation/delete_relation.hpp" -#include "duckdb/parser/statement/delete_statement.hpp" -#include "duckdb/parser/query_node/delete_query_node.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/tableref/basetableref.hpp" - -namespace duckdb { - -DeleteRelation::DeleteRelation(shared_ptr &context, unique_ptr condition_p, - Identifier catalog_name_p, Identifier schema_name_p, Identifier table_name_p) - : Relation(context, RelationType::DELETE_RELATION), condition(std::move(condition_p)), - catalog_name(std::move(catalog_name_p)), schema_name(std::move(schema_name_p)), - table_name(std::move(table_name_p)) { - TryBindRelation(columns); -} - -BoundStatement DeleteRelation::Bind(Binder &binder) { - auto basetable = make_uniq(); - basetable->SetQualifiedName(QualifiedName(catalog_name, schema_name, table_name)); - - DeleteStatement stmt; - auto &node = *stmt.node; - node.condition = condition ? condition->Copy() : nullptr; - node.table = std::move(basetable); - return binder.Bind(stmt.Cast()); -} - -unique_ptr DeleteRelation::GetQueryNode() { - throw InternalException("Cannot create a query node from a delete relation"); -} - -string DeleteRelation::GetQuery() { - return string(); -} - -const vector &DeleteRelation::Columns() { - return columns; -} - -string DeleteRelation::ToString(idx_t depth) { - string str = - RenderWhitespace(depth) + "DELETE FROM " + - QualifiedName(catalog_name, schema_name, table_name).ToString(QualifiedNameToStringMode::HIDE_DEFAULT_SCHEMA); - if (condition) { - str += " WHERE " + condition->ToString(); - } - return str; -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/delim_get_relation.cpp b/src/duckdb/src/main/relation/delim_get_relation.cpp deleted file mode 100644 index 3f1b9cbc8..000000000 --- a/src/duckdb/src/main/relation/delim_get_relation.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "duckdb/main/relation/delim_get_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/parser/tableref/delimgetref.hpp" - -namespace duckdb { - -DelimGetRelation::DelimGetRelation(const shared_ptr &context, vector chunk_types_p) - : Relation(context, RelationType::DELIM_GET_RELATION), chunk_types(std::move(chunk_types_p)) { - TryBindRelation(columns); -} - -unique_ptr DelimGetRelation::GetQueryNode() { - auto result = make_uniq(); - result->select_list.push_back(make_uniq()); - result->from_table = GetTableRef(); - return std::move(result); -} - -unique_ptr DelimGetRelation::GetTableRef() { - auto delim_get_ref = make_uniq(chunk_types); - return std::move(delim_get_ref); -} - -const vector &DelimGetRelation::Columns() { - return this->columns; -} - -string DelimGetRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth); - str += "Delimiter Get ["; - for (idx_t i = 0; i < chunk_types.size(); i++) { - str += chunk_types[i].ToString(); - if (i + 1 < chunk_types.size()) { - str += ", "; - } - } - str += "]"; - - return str; -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/distinct_relation.cpp b/src/duckdb/src/main/relation/distinct_relation.cpp deleted file mode 100644 index 5f904b124..000000000 --- a/src/duckdb/src/main/relation/distinct_relation.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "duckdb/main/relation/distinct_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/query_node.hpp" - -namespace duckdb { - -DistinctRelation::DistinctRelation(shared_ptr child_p) - : Relation(child_p->context, RelationType::DISTINCT_RELATION), child(std::move(child_p)) { - D_ASSERT(child.get() != this); - vector dummy_columns; - TryBindRelation(dummy_columns); -} - -unique_ptr DistinctRelation::GetQueryNode() { - auto child_node = child->GetQueryNode(); - child_node->AddDistinct(); - return child_node; -} - -Identifier DistinctRelation::GetAlias() { - return child->GetAlias(); -} - -const vector &DistinctRelation::Columns() { - return child->Columns(); -} - -string DistinctRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Distinct\n"; - return str + child->ToString(depth + 1); - ; -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/explain_relation.cpp b/src/duckdb/src/main/relation/explain_relation.cpp deleted file mode 100644 index 5bc461e69..000000000 --- a/src/duckdb/src/main/relation/explain_relation.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "duckdb/main/relation/explain_relation.hpp" -#include "duckdb/parser/statement/explain_statement.hpp" -#include "duckdb/parser/statement/select_statement.hpp" -#include "duckdb/parser/parsed_data/create_view_info.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/main/client_context.hpp" - -namespace duckdb { - -ExplainRelation::ExplainRelation(shared_ptr child_p, ExplainType type, const ProfilerPrintFormat &format) - : Relation(child_p->context, RelationType::EXPLAIN_RELATION), child(std::move(child_p)), type(type), - format(format) { - TryBindRelation(columns); -} - -BoundStatement ExplainRelation::Bind(Binder &binder) { - auto select = make_uniq(); - select->node = child->GetQueryNode(); - ExplainStatement explain(std::move(select), type, format); - return binder.Bind(explain.Cast()); -} - -unique_ptr ExplainRelation::GetQueryNode() { - throw InternalException("Cannot create a query node from an explain relation"); -} - -string ExplainRelation::GetQuery() { - return string(); -} - -const vector &ExplainRelation::Columns() { - return columns; -} - -string ExplainRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Explain\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/filter_relation.cpp b/src/duckdb/src/main/relation/filter_relation.cpp deleted file mode 100644 index 82fae0ce4..000000000 --- a/src/duckdb/src/main/relation/filter_relation.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "duckdb/main/relation/filter_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/query_node/set_operation_node.hpp" -#include "duckdb/parser/expression/conjunction_expression.hpp" -#include "duckdb/parser/expression/star_expression.hpp" - -namespace duckdb { - -FilterRelation::FilterRelation(shared_ptr child_p, unique_ptr condition_p) - : Relation(child_p->context, RelationType::FILTER_RELATION), condition(std::move(condition_p)), - child(std::move(child_p)) { - D_ASSERT(child.get() != this); - vector dummy_columns; - TryBindRelation(dummy_columns); -} - -unique_ptr FilterRelation::GetQueryNode() { - auto child_ptr = child.get(); - while (child_ptr->InheritsColumnBindings()) { - child_ptr = child_ptr->ChildRelation(); - } - if (child_ptr->type == RelationType::JOIN_RELATION) { - // child node is a join: push filter into WHERE clause of select node - auto child_node = child->GetQueryNode(); - D_ASSERT(child_node->type == QueryNodeType::SELECT_NODE); - auto &select_node = child_node->Cast(); - if (!select_node.where_clause) { - select_node.where_clause = condition->Copy(); - } else { - select_node.where_clause = make_uniq( - ExpressionType::CONJUNCTION_AND, std::move(select_node.where_clause), condition->Copy()); - } - return child_node; - } else { - auto result = make_uniq(); - result->select_list.push_back(make_uniq()); - result->from_table = child->GetTableRef(); - result->where_clause = condition->Copy(); - return std::move(result); - } -} - -Identifier FilterRelation::GetAlias() { - return child->GetAlias(); -} - -const vector &FilterRelation::Columns() { - return child->Columns(); -} - -string FilterRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Filter [" + condition->ToString() + "]\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/insert_relation.cpp b/src/duckdb/src/main/relation/insert_relation.cpp deleted file mode 100644 index e0dbf4280..000000000 --- a/src/duckdb/src/main/relation/insert_relation.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include "duckdb/main/relation/insert_relation.hpp" -#include "duckdb/parser/statement/insert_statement.hpp" -#include "duckdb/parser/query_node/insert_query_node.hpp" -#include "duckdb/parser/statement/select_statement.hpp" -#include "duckdb/parser/parsed_data/create_table_info.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/main/client_context.hpp" - -namespace duckdb { - -InsertRelation::InsertRelation(shared_ptr child_p, Identifier schema_name, Identifier table_name) - : Relation(child_p->context, RelationType::INSERT_RELATION), child(std::move(child_p)), - schema_name(std::move(schema_name)), table_name(std::move(table_name)) { - TryBindRelation(columns); -} - -InsertRelation::InsertRelation(shared_ptr child_p, Identifier catalog_name, Identifier schema_name, - Identifier table_name) - : Relation(child_p->context, RelationType::INSERT_RELATION), child(std::move(child_p)), - catalog_name(std::move(catalog_name)), schema_name(std::move(schema_name)), table_name(std::move(table_name)) { - TryBindRelation(columns); -} - -BoundStatement InsertRelation::Bind(Binder &binder) { - InsertStatement stmt; - auto &node = *stmt.node; - auto select = make_uniq(); - select->node = child->GetQueryNode(); - - node.qualified_name = QualifiedName(catalog_name, schema_name, table_name); - node.select_statement = std::move(select); - return binder.Bind(stmt.Cast()); -} - -unique_ptr InsertRelation::GetQueryNode() { - throw InternalException("Cannot create a query node from an insert relation"); -} - -string InsertRelation::GetQuery() { - return string(); -} - -const vector &InsertRelation::Columns() { - return columns; -} - -string InsertRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Insert\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/join_relation.cpp b/src/duckdb/src/main/relation/join_relation.cpp deleted file mode 100644 index eb1f672fa..000000000 --- a/src/duckdb/src/main/relation/join_relation.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include "duckdb/main/relation/join_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/parser/tableref/joinref.hpp" -#include "duckdb/common/enum_util.hpp" -#include "duckdb/main/client_context_wrapper.hpp" - -namespace duckdb { - -JoinRelation::JoinRelation(shared_ptr left_p, shared_ptr right_p, - unique_ptr condition_p, JoinType type, JoinRefType join_ref_type) - : Relation(left_p->context, RelationType::JOIN_RELATION), left(std::move(left_p)), right(std::move(right_p)), - condition(std::move(condition_p)), join_type(type), join_ref_type(join_ref_type) { - if (left->context->GetContext() != right->context->GetContext()) { - throw InvalidInputException("Cannot combine LEFT and RIGHT relations of different connections!"); - } - TryBindRelation(columns); -} - -JoinRelation::JoinRelation(shared_ptr left_p, shared_ptr right_p, - vector using_columns_p, JoinType type, JoinRefType join_ref_type) - : Relation(left_p->context, RelationType::JOIN_RELATION), left(std::move(left_p)), right(std::move(right_p)), - using_columns(std::move(using_columns_p)), join_type(type), join_ref_type(join_ref_type) { - if (left->context->GetContext() != right->context->GetContext()) { - throw InvalidInputException("Cannot combine LEFT and RIGHT relations of different connections!"); - } - TryBindRelation(columns); -} - -unique_ptr JoinRelation::GetQueryNode() { - auto result = make_uniq(); - result->select_list.push_back(make_uniq()); - result->from_table = GetTableRef(); - return std::move(result); -} - -unique_ptr JoinRelation::GetTableRef() { - auto join_ref = make_uniq(join_ref_type); - join_ref->left = left->GetTableRef(); - join_ref->right = right->GetTableRef(); - if (condition) { - join_ref->condition = condition->Copy(); - } - join_ref->using_columns = using_columns; - join_ref->type = join_type; - join_ref->delim_flipped = delim_flipped; - for (auto &col : duplicate_eliminated_columns) { - join_ref->duplicate_eliminated_columns.emplace_back(col->Copy()); - } - return std::move(join_ref); -} - -const vector &JoinRelation::Columns() { - return this->columns; -} - -string JoinRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth); - str += "Join " + EnumUtil::ToString(join_ref_type) + " " + EnumUtil::ToString(join_type); - if (condition) { - str += " " + condition->GetName(); - } - - return str + "\n" + left->ToString(depth + 1) + "\n" + right->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/limit_relation.cpp b/src/duckdb/src/main/relation/limit_relation.cpp deleted file mode 100644 index f26677600..000000000 --- a/src/duckdb/src/main/relation/limit_relation.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "duckdb/main/relation/limit_relation.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/query_node.hpp" -#include "duckdb/parser/expression/constant_expression.hpp" -#include "duckdb/common/to_string.hpp" - -namespace duckdb { - -LimitRelation::LimitRelation(shared_ptr child_p, int64_t limit, int64_t offset) - : Relation(child_p->context, RelationType::LIMIT_RELATION), limit(limit), offset(offset), - child(std::move(child_p)) { - D_ASSERT(child.get() != this); -} - -unique_ptr LimitRelation::GetQueryNode() { - auto child_node = child->GetQueryNode(); - auto limit_node = make_uniq(); - if (limit >= 0) { - limit_node->limit = ConstantExpression::Integer(limit); - } - if (offset > 0) { - limit_node->offset = ConstantExpression::Integer(offset); - } - - child_node->modifiers.push_back(std::move(limit_node)); - return child_node; -} - -Identifier LimitRelation::GetAlias() { - return child->GetAlias(); -} - -const vector &LimitRelation::Columns() { - return child->Columns(); -} - -string LimitRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Limit " + to_string(limit); - if (offset > 0) { - str += " Offset " + to_string(offset); - } - str += "\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/materialized_relation.cpp b/src/duckdb/src/main/relation/materialized_relation.cpp deleted file mode 100644 index 47d551736..000000000 --- a/src/duckdb/src/main/relation/materialized_relation.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "duckdb/main/relation/materialized_relation.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/planner/bound_statement.hpp" -#include "duckdb/planner/operator/logical_column_data_get.hpp" -#include "duckdb/parser/tableref/column_data_ref.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/common/exception.hpp" - -namespace duckdb { - -MaterializedRelation::MaterializedRelation(const shared_ptr &context, - unique_ptr &&collection_p, vector names, - const Identifier &alias_p) - : Relation(context, RelationType::MATERIALIZED_RELATION), alias(alias_p.GetIdentifierName()), - collection(std::move(collection_p)) { - // create constant expressions for the values - auto types = collection->Types(); - D_ASSERT(types.size() == names.size()); - - QueryResult::DeduplicateColumns(names); - for (idx_t i = 0; i < types.size(); i++) { - auto &type = types[i]; - auto &name = names[i]; - auto column_definition = ColumnDefinition(name, type); - columns.push_back(std::move(column_definition)); - } -} - -unique_ptr MaterializedRelation::GetQueryNode() { - auto result = make_uniq(); - result->select_list.push_back(make_uniq()); - result->from_table = GetTableRef(); - return std::move(result); -} - -unique_ptr MaterializedRelation::GetTableRef() { - auto table_ref = make_uniq(collection); - for (auto &col : columns) { - table_ref->expected_names.emplace_back(col.Name()); - } - table_ref->alias = Identifier(GetAlias()); - return std::move(table_ref); -} - -Identifier MaterializedRelation::GetAlias() { - return Identifier(alias); -} - -const vector &MaterializedRelation::Columns() { - return columns; -} - -string MaterializedRelation::ToString(idx_t depth) { - return collection->ToString(); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/order_relation.cpp b/src/duckdb/src/main/relation/order_relation.cpp deleted file mode 100644 index 7a2237da9..000000000 --- a/src/duckdb/src/main/relation/order_relation.cpp +++ /dev/null @@ -1,48 +0,0 @@ -#include "duckdb/main/relation/order_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/query_node.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/expression/star_expression.hpp" - -namespace duckdb { - -OrderRelation::OrderRelation(shared_ptr child_p, vector orders) - : Relation(child_p->context, RelationType::ORDER_RELATION), orders(std::move(orders)), child(std::move(child_p)) { - D_ASSERT(child.get() != this); - // bind the expressions - TryBindRelation(columns); -} - -unique_ptr OrderRelation::GetQueryNode() { - auto select = make_uniq(); - select->from_table = child->GetTableRef(); - select->select_list.push_back(make_uniq()); - auto order_node = make_uniq(); - for (idx_t i = 0; i < orders.size(); i++) { - order_node->orders.emplace_back(orders[i].type, orders[i].null_order, orders[i].expression->Copy()); - } - select->modifiers.push_back(std::move(order_node)); - return std::move(select); -} - -Identifier OrderRelation::GetAlias() { - return child->GetAlias(); -} - -const vector &OrderRelation::Columns() { - return columns; -} - -string OrderRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Order ["; - for (idx_t i = 0; i < orders.size(); i++) { - if (i != 0) { - str += ", "; - } - str += orders[i].expression->ToString() + (orders[i].type == OrderType::ASCENDING ? " ASC" : " DESC"); - } - str += "]\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/projection_relation.cpp b/src/duckdb/src/main/relation/projection_relation.cpp deleted file mode 100644 index c80518d4e..000000000 --- a/src/duckdb/src/main/relation/projection_relation.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "duckdb/main/relation/projection_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/tableref/subqueryref.hpp" -#include "duckdb/common/exception/parser_exception.hpp" - -namespace duckdb { - -ProjectionRelation::ProjectionRelation(shared_ptr child_p, - vector> parsed_expressions, - vector aliases) - : Relation(child_p->context, RelationType::PROJECTION_RELATION), expressions(std::move(parsed_expressions)), - child(std::move(child_p)) { - if (!aliases.empty()) { - if (aliases.size() != expressions.size()) { - throw ParserException("Aliases list length must match expression list length!"); - } - for (idx_t i = 0; i < aliases.size(); i++) { - expressions[i]->SetAlias(aliases[i]); - } - } - // bind the expressions - TryBindRelation(columns); -} - -unique_ptr ProjectionRelation::GetQueryNode() { - auto child_ptr = child.get(); - while (child_ptr->InheritsColumnBindings()) { - child_ptr = child_ptr->ChildRelation(); - } - unique_ptr result; - if (child_ptr->type == RelationType::JOIN_RELATION) { - // child node is a join: push projection into the child query node - result = child->GetQueryNode(); - } else { - // child node is not a join: create a new select node and push the child as a table reference - auto select = make_uniq(); - select->from_table = child->GetTableRef(); - result = std::move(select); - } - D_ASSERT(result->type == QueryNodeType::SELECT_NODE); - auto &select_node = result->Cast(); - select_node.aggregate_handling = AggregateHandling::NO_AGGREGATES_ALLOWED; - select_node.select_list.clear(); - for (auto &expr : expressions) { - select_node.select_list.push_back(expr->Copy()); - } - return result; -} - -Identifier ProjectionRelation::GetAlias() { - return child->GetAlias(); -} - -const vector &ProjectionRelation::Columns() { - return columns; -} - -string ProjectionRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Projection ["; - for (idx_t i = 0; i < expressions.size(); i++) { - if (i != 0) { - str += ", "; - } - str += expressions[i]->ToString() + " as " + expressions[i]->GetAlias(); - } - str += "]\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/query_relation.cpp b/src/duckdb/src/main/relation/query_relation.cpp deleted file mode 100644 index ca415cd70..000000000 --- a/src/duckdb/src/main/relation/query_relation.cpp +++ /dev/null @@ -1,115 +0,0 @@ -#include "duckdb/main/relation/query_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/statement/select_statement.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/parser/tableref/subqueryref.hpp" -#include "duckdb/parser/tableref/joinref.hpp" -#include "duckdb/parser/parser.hpp" -#include "duckdb/planner/bound_statement.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/planner/query_node/bound_select_node.hpp" -#include "duckdb/parser/common_table_expression_info.hpp" -#include "duckdb/parser/query_node/cte_node.hpp" - -namespace duckdb { - -QueryRelation::QueryRelation(const shared_ptr &context, unique_ptr select_stmt_p, - string alias_p, const string &query_p) - : Relation(context, RelationType::QUERY_RELATION), select_stmt(std::move(select_stmt_p)), query(query_p), - alias(std::move(alias_p)) { - if (query.empty()) { - query = select_stmt->ToString(); - } - TryBindRelation(columns); -} - -QueryRelation::~QueryRelation() { -} - -unique_ptr QueryRelation::ParseStatement(ClientContext &context, const string &query, - const string &error) { - Parser parser(context); - parser.ParseQuery(query); - if (parser.statements.size() != 1) { - throw ParserException(error); - } - if (parser.statements[0]->type != StatementType::SELECT_STATEMENT) { - throw ParserException(error); - } - return unique_ptr_cast(std::move(parser.statements[0])); -} - -unique_ptr QueryRelation::GetSelectStatement() { - return unique_ptr_cast(select_stmt->Copy()); -} - -unique_ptr QueryRelation::GetQueryNode() { - auto select = GetSelectStatement(); - return std::move(select->node); -} - -string QueryRelation::GetQuery() { - return query; -} - -unique_ptr QueryRelation::GetTableRef() { - auto subquery_ref = make_uniq(GetSelectStatement(), GetAlias()); - return std::move(subquery_ref); -} - -BoundStatement QueryRelation::Bind(Binder &binder) { - auto saved_binding_mode = binder.GetBindingMode(); - binder.SetBindingMode(BindingMode::EXTRACT_REPLACEMENT_SCANS); - bool first_bind = columns.empty(); - auto result = Relation::Bind(binder); - auto &replacements = binder.GetReplacementScans(); - if (first_bind) { - for (auto &kv : replacements) { - auto &name = kv.first; - auto &tableref = kv.second; - - if (!tableref->external_dependency) { - // Only push a CTE for objects that are out of our control (i.e Python) - // This makes sure replacement scans for files (parquet/csv/json etc) are not transformed into a CTE - continue; - } - - auto select = make_uniq(); - auto select_node = make_uniq(); - select_node->select_list.push_back(make_uniq()); - select_node->from_table = std::move(tableref); - select->node = std::move(select_node); - - auto cte_info = make_uniq(); - cte_info->query_node = std::move(select->node); - - auto subquery = make_uniq(std::move(select_stmt), "query_relation"); - auto top_level_select = make_uniq(); - auto top_level_select_node = make_uniq(); - top_level_select_node->select_list.push_back(make_uniq()); - top_level_select_node->from_table = std::move(subquery); - auto &cte_map = top_level_select_node->cte_map; - top_level_select->node = std::move(top_level_select_node); - cte_map.map[name] = std::move(cte_info); - select_stmt = std::move(top_level_select); - } - } - replacements.clear(); - binder.SetBindingMode(saved_binding_mode); - return result; -} - -Identifier QueryRelation::GetAlias() { - return Identifier(alias); -} - -const vector &QueryRelation::Columns() { - return columns; -} - -string QueryRelation::ToString(idx_t depth) { - return RenderWhitespace(depth) + "Subquery"; -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/read_csv_relation.cpp b/src/duckdb/src/main/relation/read_csv_relation.cpp deleted file mode 100644 index 11d6c649d..000000000 --- a/src/duckdb/src/main/relation/read_csv_relation.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include "duckdb/main/relation/read_csv_relation.hpp" - -#include "duckdb/execution/operator/csv_scanner/csv_buffer_manager.hpp" -#include "duckdb/execution/operator/csv_scanner/sniffer/csv_sniffer.hpp" -#include "duckdb/parser/expression/columnref_expression.hpp" -#include "duckdb/parser/expression/comparison_expression.hpp" -#include "duckdb/parser/expression/constant_expression.hpp" -#include "duckdb/parser/expression/function_expression.hpp" -#include "duckdb/common/string_util.hpp" -#include "duckdb/execution/operator/csv_scanner/csv_reader_options.hpp" -#include "duckdb/common/multi_file/multi_file_reader.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/tableref/basetableref.hpp" -#include "duckdb/parser/tableref/table_function_ref.hpp" -#include "duckdb/function/table/read_csv.hpp" -#include "duckdb/common/multi_file/multi_file_function.hpp" -#include "duckdb/execution/operator/csv_scanner/csv_file_scanner.hpp" -#include "duckdb/execution/operator/csv_scanner/csv_schema_discovery.hpp" -#include "duckdb/common/multi_file/union_by_name.hpp" - -namespace duckdb { - -void ReadCSVRelation::InitializeAlias(const vector &input) { - D_ASSERT(!input.empty()); - const auto &csv_file = input[0]; - alias = StringUtil::Split(csv_file, ".")[0]; -} - -CSVReaderOptions ReadCSVRelationBind(const shared_ptr &context, const vector &input, - named_parameter_map_t &options, vector &columns, - MultiFileOptions &file_options) { - auto file_list = MultiFileReader::CreateValueFromFileList(input); - - auto multi_file_reader = MultiFileReader::CreateDefault("ReadCSVRelation"); - vector files; - files = multi_file_reader->CreateFileList(*context, file_list)->GetAllFiles(); - - D_ASSERT(!files.empty()); - - auto &file_name = files[0]; - CSVReaderOptions csv_options; - csv_options.file_path = file_name.path; - vector empty; - named_argument_map_t named_arguments; - for (auto &option : options) { - named_arguments.insert(option.first, option.second); - } - csv_options.FromNamedParameters(named_arguments, *context, file_options); - - // Run the auto-detect, populating the options with the detected settings - SimpleMultiFileList multi_file_list(files); - - if (file_options.union_by_name) { - vector types; - vector names; - // sniff every file and unify the columns of the files by name - identifier_map_t union_names_map; - for (auto &file : files) { - auto file_csv_options = csv_options; - file_csv_options.file_path = file.path; - CSVFileScan file_scan(*context, file, file_csv_options, file_options); - UnionByName::CombineUnionTypes(file_scan.GetNames(), file_scan.GetTypes(), types, names, union_names_map); - } - if (!csv_options.sql_types_per_column.empty()) { - const auto exception = CSVError::ColumnTypesError(csv_options.sql_types_per_column, names); - if (!exception.error_message.empty()) { - throw BinderException(exception.error_message); - } - for (idx_t i = 0; i < names.size(); i++) { - auto it = csv_options.sql_types_per_column.find(names[i]); - if (it != csv_options.sql_types_per_column.end()) { - types[i] = csv_options.sql_type_list[it->second]; - } - } - } - D_ASSERT(names.size() == types.size()); - for (idx_t i = 0; i < names.size(); i++) { - columns.emplace_back(names[i], types[i]); - } - } else { - if (csv_options.auto_detect) { - vector return_types; - vector names; - shared_ptr buffer_manager; - CSVSchemaDiscovery::SchemaDiscovery(*context, buffer_manager, csv_options, file_options, return_types, - names, multi_file_list); - for (idx_t i = 0; i < return_types.size(); i++) { - columns.emplace_back(names[i], return_types[i]); - } - } else { - for (idx_t i = 0; i < csv_options.sql_type_list.size(); i++) { - D_ASSERT(csv_options.name_list.size() == csv_options.sql_type_list.size()); - columns.emplace_back(csv_options.name_list[i], csv_options.sql_type_list[i]); - } - } - // After sniffing we can consider these set, so they are exported as named parameters - // FIXME: This is horribly hacky, should be refactored at some point - csv_options.dialect_options.state_machine_options.escape.ChangeSetByUserTrue(); - csv_options.dialect_options.state_machine_options.delimiter.ChangeSetByUserTrue(); - csv_options.dialect_options.state_machine_options.quote.ChangeSetByUserTrue(); - csv_options.dialect_options.state_machine_options.comment.ChangeSetByUserTrue(); - csv_options.dialect_options.header.ChangeSetByUserTrue(); - csv_options.dialect_options.skip_rows.ChangeSetByUserTrue(); - } - return csv_options; -} - -ReadCSVRelation::ReadCSVRelation(const shared_ptr &context, const vector &input, - named_parameter_map_t &&options, string alias_p) - : TableFunctionRelation(context, "read_csv_auto", {MultiFileReader::CreateValueFromFileList(input)}, nullptr, - false), - alias(std::move(alias_p)) { - MultiFileOptions file_options; - - InitializeAlias(input); - CSVReaderOptions csv_options; - context->RunFunctionInTransaction( - [&]() { csv_options = ReadCSVRelationBind(context, input, options, columns, file_options); }); - - // Capture the options potentially set/altered by the auto-detection phase - csv_options.ToNamedParameters(options); - - // No need to auto-detect again - options["auto_detect"] = Value::BOOLEAN(false); - SetNamedParameters(std::move(options)); - - child_list_t column_names; - for (idx_t i = 0; i < columns.size(); i++) { - column_names.emplace_back(make_pair(columns[i].Name(), Value(columns[i].Type().ToString()))); - } - - if (!file_options.union_by_name) { - AddNamedParameter("columns", Value::STRUCT(std::move(column_names))); - } - RemoveNamedParameterIfExists("names"); - RemoveNamedParameterIfExists("types"); - RemoveNamedParameterIfExists("dtypes"); -} - -Identifier ReadCSVRelation::GetAlias() { - return Identifier(alias); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/read_json_relation.cpp b/src/duckdb/src/main/relation/read_json_relation.cpp deleted file mode 100644 index f05053af8..000000000 --- a/src/duckdb/src/main/relation/read_json_relation.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "duckdb/main/relation/read_json_relation.hpp" -#include "duckdb/parser/column_definition.hpp" -#include "duckdb/common/multi_file/multi_file_reader.hpp" - -namespace duckdb { - -void ReadJSONRelation::InitializeAlias(const vector &input) { - D_ASSERT(!input.empty()); - const auto &first_file = input[0]; - alias = StringUtil::Split(first_file, ".")[0]; -} - -ReadJSONRelation::ReadJSONRelation(const shared_ptr &context, vector &input, - named_parameter_map_t options, bool auto_detect, string alias_p) - : TableFunctionRelation(context, auto_detect ? "read_json_auto" : "read_json", - {MultiFileReader::CreateValueFromFileList(input)}, std::move(options)), - alias(std::move(alias_p)) { - InitializeAlias(input); -} - -ReadJSONRelation::ReadJSONRelation(const shared_ptr &context, string json_file_p, - named_parameter_map_t options, bool auto_detect, string alias_p) - : TableFunctionRelation(context, auto_detect ? "read_json_auto" : "read_json", {Value(json_file_p)}, - std::move(options)), - json_file(std::move(json_file_p)), alias(std::move(alias_p)) { - if (alias.empty()) { - alias = StringUtil::Split(json_file, ".")[0]; - } -} - -ReadJSONRelation::~ReadJSONRelation() { -} - -Identifier ReadJSONRelation::GetAlias() { - return Identifier(alias); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/setop_relation.cpp b/src/duckdb/src/main/relation/setop_relation.cpp deleted file mode 100644 index 609828cfe..000000000 --- a/src/duckdb/src/main/relation/setop_relation.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "duckdb/main/relation/setop_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/query_node/set_operation_node.hpp" -#include "duckdb/parser/result_modifier.hpp" - -namespace duckdb { - -SetOpRelation::SetOpRelation(shared_ptr left_p, shared_ptr right_p, SetOperationType setop_type_p, - bool setop_all) - : Relation(left_p->context, RelationType::SET_OPERATION_RELATION), left(std::move(left_p)), - right(std::move(right_p)), setop_type(setop_type_p), setop_all(setop_all) { - if (left->context->GetContext() != right->context->GetContext()) { - throw InvalidInputException("Cannot combine LEFT and RIGHT relations of different connections!"); - } - TryBindRelation(columns); -} - -unique_ptr SetOpRelation::GetQueryNode() { - auto result = make_uniq(); - if (!setop_all) { - result->modifiers.push_back(make_uniq()); - } - result->children.push_back(left->GetQueryNode()); - result->children.push_back(right->GetQueryNode()); - result->setop_type = setop_type; - result->setop_all = setop_all; - return std::move(result); -} - -Identifier SetOpRelation::GetAlias() { - return left->GetAlias(); -} - -const vector &SetOpRelation::Columns() { - return this->columns; -} - -string SetOpRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth); - switch (setop_type) { - case SetOperationType::UNION: - str += "Union"; - break; - case SetOperationType::EXCEPT: - str += "Except"; - break; - case SetOperationType::INTERSECT: - str += "Intersect"; - break; - default: - throw InternalException("Unknown setop type"); - } - return str + "\n" + left->ToString(depth + 1) + right->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/subquery_relation.cpp b/src/duckdb/src/main/relation/subquery_relation.cpp deleted file mode 100644 index 2e83ed124..000000000 --- a/src/duckdb/src/main/relation/subquery_relation.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "duckdb/main/relation/subquery_relation.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/query_node.hpp" - -namespace duckdb { - -SubqueryRelation::SubqueryRelation(shared_ptr child_p, const string &alias_p) - : Relation(child_p->context, RelationType::SUBQUERY_RELATION, alias_p), child(std::move(child_p)) { - D_ASSERT(child.get() != this); - vector dummy_columns; - Relation::TryBindRelation(dummy_columns); -} - -unique_ptr SubqueryRelation::GetQueryNode() { - return child->GetQueryNode(); -} - -const vector &SubqueryRelation::Columns() { - return child->Columns(); -} - -string SubqueryRelation::ToString(idx_t depth) { - return child->ToString(depth); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/table_function_relation.cpp b/src/duckdb/src/main/relation/table_function_relation.cpp deleted file mode 100644 index 51ef3ef7b..000000000 --- a/src/duckdb/src/main/relation/table_function_relation.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include "duckdb/main/relation/table_function_relation.hpp" -#include "duckdb/parser/tableref/basetableref.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/parser/tableref/table_function_ref.hpp" -#include "duckdb/parser/expression/constant_expression.hpp" -#include "duckdb/parser/expression/function_expression.hpp" -#include "duckdb/parser/expression/subquery_expression.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/expression/comparison_expression.hpp" -#include "duckdb/parser/expression/columnref_expression.hpp" -#include "duckdb/common/shared_ptr.hpp" - -namespace duckdb { - -void TableFunctionRelation::AddNamedParameter(const string &name, Value argument) { - named_parameters[Identifier(name)] = std::move(argument); -} - -void TableFunctionRelation::RemoveNamedParameterIfExists(const string &name) { - if (named_parameters.find(Identifier(name)) != named_parameters.end()) { - named_parameters.erase(Identifier(name)); - } -} - -void TableFunctionRelation::SetNamedParameters(named_parameter_map_t &&options) { - D_ASSERT(named_parameters.empty()); - named_parameters = std::move(options); -} - -TableFunctionRelation::TableFunctionRelation(const shared_ptr &context, string name_p, - vector parameters_p, named_parameter_map_t named_parameters, - shared_ptr input_relation_p, bool auto_init, - shared_ptr bind_info_p) - : Relation(context, RelationType::TABLE_FUNCTION_RELATION), name(std::move(name_p)), - parameters(std::move(parameters_p)), named_parameters(std::move(named_parameters)), - input_relation(std::move(input_relation_p)), bind_info(std::move(bind_info_p)), auto_initialize(auto_init) { - InitializeColumns(); -} - -TableFunctionRelation::TableFunctionRelation(const shared_ptr &context, string name_p, - vector parameters_p, named_parameter_map_t named_parameters, - shared_ptr input_relation_p, bool auto_init, - shared_ptr bind_info_p) - : Relation(context, RelationType::TABLE_FUNCTION_RELATION), name(std::move(name_p)), - parameters(std::move(parameters_p)), named_parameters(std::move(named_parameters)), - input_relation(std::move(input_relation_p)), bind_info(std::move(bind_info_p)), auto_initialize(auto_init) { - InitializeColumns(); -} - -TableFunctionRelation::TableFunctionRelation(const shared_ptr &context, string name_p, - vector parameters_p, shared_ptr input_relation_p, - bool auto_init, shared_ptr bind_info_p) - : Relation(context, RelationType::TABLE_FUNCTION_RELATION), name(std::move(name_p)), - parameters(std::move(parameters_p)), input_relation(std::move(input_relation_p)), - bind_info(std::move(bind_info_p)), auto_initialize(auto_init) { - InitializeColumns(); -} - -void TableFunctionRelation::InitializeColumns() { - if (!auto_initialize) { - return; - } - TryBindRelation(columns); -} - -unique_ptr TableFunctionRelation::GetQueryNode() { - auto result = make_uniq(); - result->select_list.push_back(make_uniq()); - result->from_table = GetTableRef(); - return std::move(result); -} - -unique_ptr TableFunctionRelation::GetTableRef() { - vector> children; - if (input_relation) { // input relation becomes first parameter if present, always - auto subquery = make_uniq(); - subquery->SubqueryMutable() = make_uniq(); - subquery->SubqueryMutable()->node = input_relation->GetQueryNode(); - subquery->GetSubqueryTypeMutable() = SubqueryType::SCALAR; - children.push_back(std::move(subquery)); - } - for (auto ¶meter : parameters) { - children.push_back(ConstantExpression::FromValue(parameter)); - } - - for (auto ¶meter : named_parameters) { - // Hackity-hack some comparisons with column refs - // This is all but pretty, basically the named parameter is the column, the table is empty because that's what - // the function binder likes - auto column_ref = make_uniq(parameter.first); - auto constant_value = ConstantExpression::FromValue(parameter.second); - auto comparison = make_uniq(ExpressionType::COMPARE_EQUAL, std::move(column_ref), - std::move(constant_value)); - children.push_back(std::move(comparison)); - } - - auto table_function = make_uniq(); - auto function = make_uniq(name, std::move(children)); - table_function->function = std::move(function); - table_function->bind_info = bind_info; - return std::move(table_function); -} - -Identifier TableFunctionRelation::GetAlias() { - return name; -} - -const vector &TableFunctionRelation::Columns() { - return columns; -} - -string TableFunctionRelation::ToString(idx_t depth) { - string function_call = name + "("; - for (idx_t i = 0; i < parameters.size(); i++) { - if (i > 0) { - function_call += ", "; - } - function_call += parameters[i].ToString(); - } - function_call += ")"; - return RenderWhitespace(depth) + function_call; -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/table_relation.cpp b/src/duckdb/src/main/relation/table_relation.cpp deleted file mode 100644 index c9d30981c..000000000 --- a/src/duckdb/src/main/relation/table_relation.cpp +++ /dev/null @@ -1,105 +0,0 @@ -#include "duckdb/main/relation/table_relation.hpp" -#include "duckdb/parser/tableref/basetableref.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/main/relation/delete_relation.hpp" -#include "duckdb/main/relation/value_relation.hpp" -#include "duckdb/main/relation/update_relation.hpp" -#include "duckdb/parser/parser.hpp" -#include "duckdb/main/client_context.hpp" - -namespace duckdb { - -TableRelation::TableRelation(const shared_ptr &context, unique_ptr description) - : Relation(context, RelationType::TABLE_RELATION), description(std::move(description)) { -} - -TableRelation::TableRelation(const shared_ptr &context, - unique_ptr description) - : Relation(context, RelationType::TABLE_RELATION), description(std::move(description)) { -} - -unique_ptr TableRelation::GetQueryNode() { - auto result = make_uniq(); - result->select_list.push_back(make_uniq()); - result->from_table = GetTableRef(); - return std::move(result); -} - -unique_ptr TableRelation::GetTableRef() { - auto table_ref = make_uniq(); - table_ref->SetQualifiedName(description->qualified_name); - return std::move(table_ref); -} - -Identifier TableRelation::GetAlias() { - return description->qualified_name.Name(); -} - -const vector &TableRelation::Columns() { - return description->columns; -} - -string TableRelation::ToString(idx_t depth) { - return RenderWhitespace(depth) + "Scan Table [" + - description->qualified_name.ToString(QualifiedNameToStringMode::HIDE_DEFAULT_SCHEMA) + "]"; -} - -static unique_ptr ParseCondition(ClientContext &context, const string &condition) { - if (!condition.empty()) { - auto expression_list = Parser(context).ParseExpressionList(condition); - if (expression_list.size() != 1) { - throw ParserException("Expected a single expression as filter condition"); - } - return std::move(expression_list[0]); - } else { - return nullptr; - } -} - -void TableRelation::Update(vector names, vector> &&update, - unique_ptr condition) { - vector update_columns = StringsToIdentifiers(names); - vector> expressions = std::move(update); - - auto update_relation = make_shared_ptr( - context, std::move(condition), description->qualified_name.Catalog(), description->qualified_name.Schema(), - description->qualified_name.Name(), std::move(update_columns), std::move(expressions)); - update_relation->Execute(); -} - -void TableRelation::Update(const string &update_list, const string &condition) { - vector update_columns; - vector> expressions; - auto cond = ParseCondition(*context->GetContext(), condition); - Parser(*context->GetContext()).ParseUpdateList(update_list, update_columns, expressions); - auto update = make_shared_ptr( - context, std::move(cond), description->qualified_name.Catalog(), description->qualified_name.Schema(), - description->qualified_name.Name(), std::move(update_columns), std::move(expressions)); - update->Execute(); -} - -void TableRelation::Delete(const string &condition) { - auto cond = ParseCondition(*context->GetContext(), condition); - auto del = - make_shared_ptr(context, std::move(cond), description->qualified_name.Catalog(), - description->qualified_name.Schema(), description->qualified_name.Name()); - del->Execute(); -} - -void TableRelation::Insert(const vector> &values) { - vector column_names; - auto rel = make_shared_ptr(context->GetContext(), values, std::move(column_names), "values"); - rel->Insert(description->qualified_name.Catalog(), description->qualified_name.Schema(), - description->qualified_name.Name()); -} - -void TableRelation::Insert(vector>> &&expressions) { - vector column_names; - auto rel = make_shared_ptr(context->GetContext(), std::move(expressions), std::move(column_names), - "values"); - rel->Insert(description->qualified_name.Catalog(), description->qualified_name.Schema(), - description->qualified_name.Name()); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/update_relation.cpp b/src/duckdb/src/main/relation/update_relation.cpp deleted file mode 100644 index a3c9f0de5..000000000 --- a/src/duckdb/src/main/relation/update_relation.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "duckdb/main/relation/update_relation.hpp" -#include "duckdb/parser/statement/update_statement.hpp" -#include "duckdb/parser/query_node/update_query_node.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/tableref/basetableref.hpp" - -namespace duckdb { - -UpdateRelation::UpdateRelation(shared_ptr &context, unique_ptr condition_p, - Identifier catalog_name_p, Identifier schema_name_p, Identifier table_name_p, - vector update_columns_p, vector> expressions_p) - : Relation(context, RelationType::UPDATE_RELATION), condition(std::move(condition_p)), - catalog_name(std::move(catalog_name_p)), schema_name(std::move(schema_name_p)), - table_name(std::move(table_name_p)), update_columns(std::move(update_columns_p)), - expressions(std::move(expressions_p)) { - D_ASSERT(update_columns.size() == expressions.size()); - TryBindRelation(columns); -} - -BoundStatement UpdateRelation::Bind(Binder &binder) { - auto basetable = make_uniq(); - basetable->SetQualifiedName(QualifiedName(catalog_name, schema_name, table_name)); - - UpdateStatement stmt; - auto &node = *stmt.node; - - node.set_info = make_uniq(); - node.set_info->condition = condition ? condition->Copy() : nullptr; - node.table = std::move(basetable); - node.set_info->columns = update_columns; - for (auto &expr : expressions) { - node.set_info->expressions.push_back(expr->Copy()); - } - return binder.Bind(stmt.Cast()); -} - -unique_ptr UpdateRelation::GetQueryNode() { - throw InternalException("Cannot create a query node from an update relation"); -} - -string UpdateRelation::GetQuery() { - return string(); -} - -const vector &UpdateRelation::Columns() { - return columns; -} - -string UpdateRelation::ToString(idx_t depth) { - string str = - RenderWhitespace(depth) + "UPDATE " + - QualifiedName(catalog_name, schema_name, table_name).ToString(QualifiedNameToStringMode::HIDE_DEFAULT_SCHEMA) + - " SET\n"; - for (idx_t i = 0; i < expressions.size(); i++) { - str += update_columns[i] + " = " + expressions[i]->ToString() + "\n"; - } - if (condition) { - str += "WHERE " + condition->ToString() + "\n"; - } - return str; -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/value_relation.cpp b/src/duckdb/src/main/relation/value_relation.cpp deleted file mode 100644 index 1340132ca..000000000 --- a/src/duckdb/src/main/relation/value_relation.cpp +++ /dev/null @@ -1,133 +0,0 @@ -#include "duckdb/main/relation/value_relation.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/parser/tableref/expressionlistref.hpp" -#include "duckdb/parser/expression/constant_expression.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/parser.hpp" - -namespace duckdb { - -ValueRelation::ValueRelation(const shared_ptr &context, const vector> &values, - vector names_p, string alias_p) - : Relation(context, RelationType::VALUE_LIST_RELATION), names(std::move(names_p)), alias(std::move(alias_p)) { - // create constant expressions for the values - for (idx_t row_idx = 0; row_idx < values.size(); row_idx++) { - auto &list = values[row_idx]; - vector> expressions; - for (idx_t col_idx = 0; col_idx < list.size(); col_idx++) { - expressions.push_back(ConstantExpression::FromValue(list[col_idx])); - } - this->expressions.push_back(std::move(expressions)); - } - QueryResult::DeduplicateColumns(names); - TryBindRelation(columns); -} - -ValueRelation::ValueRelation(const shared_ptr &context, - vector>> &&expressions_p, vector names_p, - string alias_p) - : ValueRelation(make_shared_ptr(context), std::move(expressions_p), std::move(names_p), - std::move(alias_p)) { -} - -ValueRelation::ValueRelation(const shared_ptr &context, const string &values_list, - vector names_p, string alias_p) - : Relation(context, RelationType::VALUE_LIST_RELATION), names(std::move(names_p)), alias(std::move(alias_p)) { - this->expressions = Parser(*context).ParseValuesList(values_list); - QueryResult::DeduplicateColumns(names); - TryBindRelation(columns); -} - -ValueRelation::ValueRelation(const shared_ptr &context, const vector> &values, - vector names_p, string alias_p) - : Relation(context, RelationType::VALUE_LIST_RELATION), names(std::move(names_p)), alias(std::move(alias_p)) { - // create constant expressions for the values - for (idx_t row_idx = 0; row_idx < values.size(); row_idx++) { - auto &list = values[row_idx]; - vector> expressions; - for (idx_t col_idx = 0; col_idx < list.size(); col_idx++) { - expressions.push_back(ConstantExpression::FromValue(list[col_idx])); - } - this->expressions.push_back(std::move(expressions)); - } - QueryResult::DeduplicateColumns(names); - TryBindRelation(columns); -} - -ValueRelation::ValueRelation(const shared_ptr &context, - vector>> &&expressions_p, vector names_p, - string alias_p) - : Relation(context, RelationType::VALUE_LIST_RELATION), alias(std::move(alias_p)) { - D_ASSERT(!expressions_p.empty()); - if (names_p.empty()) { - auto &first_list = expressions_p[0]; - for (auto &expr : first_list) { - names_p.emplace_back(expr->GetName()); - } - } - names = std::move(names_p); - expressions = std::move(expressions_p); - QueryResult::DeduplicateColumns(names); - TryBindRelation(columns); -} - -unique_ptr ValueRelation::GetQueryNode() { - auto result = make_uniq(); - result->select_list.push_back(make_uniq()); - result->from_table = GetTableRef(); - return std::move(result); -} - -unique_ptr ValueRelation::GetTableRef() { - auto table_ref = make_uniq(); - // set the expected types/names - if (columns.empty()) { - // no columns yet: only set up names - for (idx_t i = 0; i < names.size(); i++) { - table_ref->expected_names.push_back(Identifier(names[i])); - } - } else { - for (idx_t i = 0; i < columns.size(); i++) { - table_ref->expected_names.emplace_back(columns[i].Name()); - table_ref->expected_types.push_back(columns[i].Type()); - D_ASSERT(names.size() == 0 || columns[i].Name() == names[i]); - } - } - // copy the expressions - for (auto &expr_list : expressions) { - vector> copied_list; - copied_list.reserve(expr_list.size()); - for (auto &expr : expr_list) { - copied_list.push_back(expr->Copy()); - } - table_ref->values.push_back(std::move(copied_list)); - } - table_ref->alias = Identifier(GetAlias()); - return std::move(table_ref); -} - -Identifier ValueRelation::GetAlias() { - return Identifier(alias); -} - -const vector &ValueRelation::Columns() { - return columns; -} - -string ValueRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Values "; - for (idx_t row_idx = 0; row_idx < expressions.size(); row_idx++) { - auto &list = expressions[row_idx]; - str += row_idx > 0 ? ", (" : "("; - for (idx_t col_idx = 0; col_idx < list.size(); col_idx++) { - str += col_idx > 0 ? ", " : ""; - str += list[col_idx]->ToString(); - } - str += ")"; - } - str += "\n"; - return str; -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/view_relation.cpp b/src/duckdb/src/main/relation/view_relation.cpp deleted file mode 100644 index d8fd38e94..000000000 --- a/src/duckdb/src/main/relation/view_relation.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "duckdb/main/relation/view_relation.hpp" -#include "duckdb/parser/tableref/basetableref.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/parser/parser.hpp" - -namespace duckdb { - -ViewRelation::ViewRelation(const shared_ptr &context, Identifier schema_name_p, Identifier view_name_p) - : Relation(context, RelationType::VIEW_RELATION), schema_name(std::move(schema_name_p)), - view_name(std::move(view_name_p)) { - TryBindRelation(columns); -} - -ViewRelation::ViewRelation(const shared_ptr &context, Identifier schema_name_p, - Identifier view_name_p) - : Relation(context, RelationType::VIEW_RELATION), schema_name(std::move(schema_name_p)), - view_name(std::move(view_name_p)) { - TryBindRelation(columns); -} - -ViewRelation::ViewRelation(const shared_ptr &context, unique_ptr ref, const string &view_name) - : Relation(context, RelationType::VIEW_RELATION), view_name(view_name), premade_tableref(std::move(ref)) { - TryBindRelation(columns); - premade_tableref->alias = Identifier(view_name); -} - -unique_ptr ViewRelation::GetQueryNode() { - auto result = make_uniq(); - result->select_list.push_back(make_uniq()); - result->from_table = GetTableRef(); - return std::move(result); -} - -unique_ptr ViewRelation::GetTableRef() { - if (premade_tableref) { - return premade_tableref->Copy(); - } - auto table_ref = make_uniq(); - table_ref->SetQualifiedName(QualifiedName(table_ref->GetQualifiedName().Catalog(), schema_name, view_name)); - return std::move(table_ref); -} - -Identifier ViewRelation::GetAlias() { - D_ASSERT(!view_name.empty()); - return view_name; -} - -const vector &ViewRelation::Columns() { - return columns; -} - -string ViewRelation::ToString(idx_t depth) { - return RenderWhitespace(depth) + "View [" + view_name + "]"; -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/write_csv_relation.cpp b/src/duckdb/src/main/relation/write_csv_relation.cpp deleted file mode 100644 index eac30e859..000000000 --- a/src/duckdb/src/main/relation/write_csv_relation.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "duckdb/main/relation/write_csv_relation.hpp" -#include "duckdb/parser/statement/copy_statement.hpp" -#include "duckdb/parser/parsed_data/create_table_info.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/main/client_context.hpp" - -namespace duckdb { - -WriteCSVRelation::WriteCSVRelation(shared_ptr child_p, string csv_file_p, - identifier_map_t> options_p) - : Relation(child_p->context, RelationType::WRITE_CSV_RELATION), child(std::move(child_p)), - csv_file(std::move(csv_file_p)), options(std::move(options_p)) { - TryBindRelation(columns); -} - -BoundStatement WriteCSVRelation::Bind(Binder &binder) { - CopyStatement copy; - auto info = make_uniq(); - info->select_statement = child->GetQueryNode(); - info->is_from = false; - info->file_path = csv_file; - info->format = "csv"; - info->options = options; - copy.info = std::move(info); - return binder.Bind(copy.Cast()); -} - -unique_ptr WriteCSVRelation::GetQueryNode() { - throw InternalException("Cannot create a query node from a write CSV relation"); -} - -string WriteCSVRelation::GetQuery() { - return string(); -} - -const vector &WriteCSVRelation::Columns() { - return columns; -} - -string WriteCSVRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Write To CSV [" + csv_file + "]\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/relation/write_parquet_relation.cpp b/src/duckdb/src/main/relation/write_parquet_relation.cpp deleted file mode 100644 index e3b8e9cbf..000000000 --- a/src/duckdb/src/main/relation/write_parquet_relation.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "duckdb/main/relation/write_parquet_relation.hpp" -#include "duckdb/parser/statement/copy_statement.hpp" -#include "duckdb/parser/parsed_data/create_table_info.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/main/client_context.hpp" - -namespace duckdb { - -WriteParquetRelation::WriteParquetRelation(shared_ptr child_p, string parquet_file_p, - identifier_map_t> options_p) - : Relation(child_p->context, RelationType::WRITE_PARQUET_RELATION), child(std::move(child_p)), - parquet_file(std::move(parquet_file_p)), options(std::move(options_p)) { - TryBindRelation(columns); -} - -BoundStatement WriteParquetRelation::Bind(Binder &binder) { - CopyStatement copy; - auto info = make_uniq(); - info->select_statement = child->GetQueryNode(); - info->is_from = false; - info->file_path = parquet_file; - info->format = "parquet"; - info->options = options; - copy.info = std::move(info); - return binder.Bind(copy.Cast()); -} - -unique_ptr WriteParquetRelation::GetQueryNode() { - throw InternalException("Cannot create a query node from a write parquet relation"); -} - -string WriteParquetRelation::GetQuery() { - return string(); -} - -const vector &WriteParquetRelation::Columns() { - return columns; -} - -string WriteParquetRelation::ToString(idx_t depth) { - string str = RenderWhitespace(depth) + "Write To Parquet [" + parquet_file + "]\n"; - return str + child->ToString(depth + 1); -} - -} // namespace duckdb diff --git a/src/duckdb/src/main/settings/autogenerated_settings.cpp b/src/duckdb/src/main/settings/autogenerated_settings.cpp index 8457da4a7..2f1f06608 100644 --- a/src/duckdb/src/main/settings/autogenerated_settings.cpp +++ b/src/duckdb/src/main/settings/autogenerated_settings.cpp @@ -204,14 +204,6 @@ void FsyncModeSetting::OnSet(SettingCallbackInfo &info, Value ¶meter) { EnumUtil::FromString(StringValue::Get(parameter)); } -//===----------------------------------------------------------------------===// -// H T T P Proxy -//===----------------------------------------------------------------------===// -Value HTTPProxySetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value(config.options.http_proxy); -} - //===----------------------------------------------------------------------===// // Lambda Syntax //===----------------------------------------------------------------------===// diff --git a/src/duckdb/src/main/settings/custom_settings.cpp b/src/duckdb/src/main/settings/custom_settings.cpp index 60101b6f1..de702a828 100644 --- a/src/duckdb/src/main/settings/custom_settings.cpp +++ b/src/duckdb/src/main/settings/custom_settings.cpp @@ -93,16 +93,6 @@ static idx_t ParseMemoryLimitOrPercentage(const string &input, BASE &&get_base) return LossyNumericCast(result); } -//! The available system memory. The config's filesystem is not set until the database starts, but -//! options can be configured before that, so fall back to a temporary local filesystem. -static idx_t GetAvailableSystemMemory(DBConfig &config) { - if (config.file_system) { - return DBConfig::GetSystemAvailableMemory(*config.file_system); - } - auto local_fs = FileSystem::CreateLocal(); - return DBConfig::GetSystemAvailableMemory(*local_fs); -} - } // namespace //===----------------------------------------------------------------------===// @@ -310,7 +300,7 @@ void AllowedDirectoriesSetting::SetGlobal(DatabaseInstance *db, DBConfig &config if (!Settings::Get(config)) { throw InvalidInputException("Cannot change allowed_directories when enable_external_access is disabled"); } - if (!config.file_system) { + if (!db) { throw InvalidInputException("Cannot change/set allowed_directories before the database is started"); } vector directories; @@ -346,7 +336,7 @@ void AllowedPathsSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, cons if (!Settings::Get(config)) { throw InvalidInputException("Cannot change allowed_paths when enable_external_access is disabled"); } - if (!config.file_system) { + if (!db) { throw InvalidInputException("Cannot change/set allowed_paths before the database is started"); } @@ -884,6 +874,7 @@ static LogicalType ParseForceVariantShredding(const string &input, bool allow_un case LogicalTypeId::INTERVAL: case LogicalTypeId::BIT: case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: break; default: throw InvalidInputException("Variants can not be shredded on type: %s", type.ToString()); @@ -1128,7 +1119,8 @@ void ExternalThreadsSetting::OnSet(SettingCallbackInfo &info, Value &input) { } auto new_external_threads = input.GetValue(); if (info.db) { - TaskScheduler::GetScheduler(*info.db).SetThreads(info.config.options.maximum_threads, new_external_threads); + TaskScheduler::GetScheduler(*info.db).SetThreads(NumericCast(Settings::Get(info.config)), + new_external_threads); } } @@ -1211,12 +1203,14 @@ void ForceMbedtlsUnsafeSetting::OnSet(SettingCallbackInfo &info, Value &input) { //===----------------------------------------------------------------------===// // HTTP Proxy //===----------------------------------------------------------------------===// -void HTTPProxySetting::SetGlobal(DatabaseInstance *, DBConfig &config, const Value &input) { - config.options.http_proxy = input.GetValue(); +Value HTTPProxySetting::GetDefaultValue(const DBConfig &) { + return Value(FileSystem::GetEnvVariable("HTTP_PROXY")); } -void HTTPProxySetting::ResetGlobal(DatabaseInstance *, DBConfig &config) { - config.options.http_proxy = FileSystem::GetEnvVariable("HTTP_PROXY"); +void HTTPProxySetting::OnSet(SettingCallbackInfo &, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", HTTPProxySetting::Name); + } } //===----------------------------------------------------------------------===// @@ -1270,30 +1264,27 @@ void LogQueryPathSetting::OnSet(SettingCallbackInfo &info, Value &input) { //===----------------------------------------------------------------------===// // Max Memory //===----------------------------------------------------------------------===// -void MaxMemorySetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { - // a percentage is relative to the system memory, since resolving it against maximum_memory would be circular - auto maximum_memory = - ParseMemoryLimitOrPercentage(input.ToString(), [&]() { return GetAvailableSystemMemory(config); }); - if (db) { - BufferManager::GetBufferManager(*db).SetMemoryLimit(maximum_memory); - } - config.options.maximum_memory = maximum_memory; +Value MaxMemorySetting::GetDefaultValue(const DBConfig &config) { + return Value(StringUtil::BytesToHumanReadableString(config.GetDefaultMaxMemory())); } -void MaxMemorySetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - auto old_memory = config.options.maximum_memory; - config.SetDefaultMaxMemory(); - auto new_memory = config.options.maximum_memory; - config.options.maximum_memory = old_memory; - if (db) { - BufferManager::GetBufferManager(*db).SetMemoryLimit(new_memory); +void MaxMemorySetting::OnSet(SettingCallbackInfo &info, Value &input) { + idx_t maximum_memory; + if (info.is_reset) { + maximum_memory = info.config.GetDefaultMaxMemory(); + } else { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", MaxMemorySetting::Name); + } + // a percentage is relative to the system memory, since resolving it against maximum_memory would be circular + maximum_memory = ParseMemoryLimitOrPercentage( + input.ToString(), [&]() { return DBConfig::GetSystemAvailableMemory(*info.config.file_system); }); } - config.options.maximum_memory = new_memory; -} - -Value MaxMemorySetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value(StringUtil::BytesToHumanReadableString(config.options.maximum_memory)); + if (info.db) { + BufferManager::GetBufferManager(*info.db).SetMemoryLimit(maximum_memory); + } + info.config.options.maximum_memory = maximum_memory; + input = Value(StringUtil::BytesToHumanReadableString(maximum_memory)); } //===----------------------------------------------------------------------===// @@ -1478,14 +1469,17 @@ void ProfilingRendererSettingsSetting::OnSet(SettingCallbackInfo &info, Value &i } new_settings[StringUtil::Lower(key_value[0].ToString())] = key_value[1].DefaultCastAs(LogicalType::VARCHAR); } - // eagerly configure the renderer of the current profiler format to validate the setting values - if (info.context) { - auto renderer = QueryProfiler::Get(*info.context).GetRenderer(); - if (renderer) { - renderer->Configure(new_settings); - } - } input = TreeRenderer::RendererSettingsToValue(new_settings); + if (info.is_reset) { + return; + } + if (!info.context) { + throw InvalidInputException("Could not set option \"%s\" as a global option", + ProfilingRendererSettingsSetting::Name); + } + // validate the new values against the renderer of the current profiler format, ignoring the stored ones + auto format = ClientConfig::GetConfig(*info.context).profiler_print_format; + TreeRenderer::CreateRenderer(*info.context, format == "no_output" ? "query_tree" : format, new_settings); } //===----------------------------------------------------------------------===// @@ -1610,21 +1604,15 @@ Value SecretDirectorySetting::GetSetting(const ClientContext &context) { //===----------------------------------------------------------------------===// // Storage Compatibility Version //===----------------------------------------------------------------------===// -void StorageCompatibilityVersionSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { - auto version_string = input.GetValue(); - auto storage_compatibility = StorageCompatibility::FromString(version_string); - config.options.storage_compatibility = storage_compatibility; -} - -void StorageCompatibilityVersionSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - config.options.storage_compatibility = DBConfigOptions().storage_compatibility; -} - -Value StorageCompatibilityVersionSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - - auto &version_name = config.options.storage_compatibility.duckdb_version; - return Value(version_name); +void StorageCompatibilityVersionSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (info.is_reset) { + info.config.options.storage_compatibility = StorageCompatibility::Default(); + return; + } + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", StorageCompatibilityVersionSetting::Name); + } + info.config.options.storage_compatibility = StorageCompatibility::FromString(input.GetValue()); } //===----------------------------------------------------------------------===// @@ -1645,19 +1633,12 @@ Value StandardVectorSizeSetting::GetSetting(const ClientContext &) { //===----------------------------------------------------------------------===// // Streaming Buffer Size //===----------------------------------------------------------------------===// -void MaxStreamingBufferSizeSetting::SetLocal(ClientContext &context, const Value &input) { - auto &config = ClientConfig::GetConfig(context); - config.max_streaming_buffer_size = DBConfig::ParseMemoryLimitOrMaximum(input.ToString()); -} - -void MaxStreamingBufferSizeSetting::ResetLocal(ClientContext &context) { - auto &config = ClientConfig::GetConfig(context); - config.SetDefaultStreamingBufferSize(); -} - -Value MaxStreamingBufferSizeSetting::GetSetting(const ClientContext &context) { - auto &config = ClientConfig::GetConfig(context); - return Value(StringUtil::BytesToHumanReadableString(config.max_streaming_buffer_size)); +void MaxStreamingBufferSizeSetting::OnSet(SettingCallbackInfo &info, Value &input) { + if (input.IsNull()) { + throw InvalidInputException("%s setting cannot be NULL", MaxStreamingBufferSizeSetting::Name); + } + auto size = DBConfig::ParseMemoryLimitOrMaximum(input.ToString()); + input = Value(StringUtil::BytesToHumanReadableString(size)); } //===----------------------------------------------------------------------===// @@ -1723,7 +1704,11 @@ void TrackedMetricsSetting::OnSet(SettingCallbackInfo &info, Value &input) { //===----------------------------------------------------------------------===// // Threads //===----------------------------------------------------------------------===// -void ThreadsSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { +Value ThreadsSetting::GetDefaultValue(const DBConfig &config) { + return Value::BIGINT(NumericCast(config.GetDefaultThreads())); +} + +void ThreadsSetting::OnSet(SettingCallbackInfo &info, Value &input) { if (input.IsNull()) { throw InvalidInputException("threads must be a positive integer"); } @@ -1731,37 +1716,28 @@ void ThreadsSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Val if (new_val < 1) { throw SyntaxException("Must have at least 1 thread!"); } - auto new_maximum_threads = NumericCast(new_val); - if (db) { - TaskScheduler::GetScheduler(*db).SetThreads(new_maximum_threads, Settings::Get(config)); - } - config.options.maximum_threads = new_maximum_threads; -} - -void ThreadsSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - idx_t new_maximum_threads = config.GetSystemMaxThreads(*config.file_system); - if (db) { - TaskScheduler::GetScheduler(*db).SetThreads(new_maximum_threads, Settings::Get(config)); + if (info.db) { + TaskScheduler::GetScheduler(*info.db).SetThreads(NumericCast(new_val), + Settings::Get(info.config)); } - config.options.maximum_threads = new_maximum_threads; } -Value ThreadsSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value::BIGINT(NumericCast(config.options.maximum_threads)); -} - -static void ResizeAutomaticHTTPClientPool(optional_ptr db, DBConfig &config) { +static void ResizeAutomaticHTTPClientPool(optional_ptr db, DBConfig &config, + optional_idx async_threads = optional_idx()) { if (!db || config.options.http_client_pool_capacity != DConstants::INVALID_INDEX) { return; } - config.GetHTTPTransportManager().SetCapacity(HTTPTransportManager::AutomaticCapacity(config)); + config.GetHTTPTransportManager().SetCapacity(HTTPTransportManager::AutomaticCapacity(config, async_threads)); } //===----------------------------------------------------------------------===// // Async Threads //===----------------------------------------------------------------------===// -void AsyncThreadsSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { +Value AsyncThreadsSetting::GetDefaultValue(const DBConfig &config) { + return Value::BIGINT(NumericCast(config.GetDefaultAsyncThreads())); +} + +void AsyncThreadsSetting::OnSet(SettingCallbackInfo &info, Value &input) { if (input.IsNull()) { throw InvalidInputException("async_threads must be a positive integer"); } @@ -1769,26 +1745,10 @@ void AsyncThreadsSetting::SetGlobal(DatabaseInstance *db, DBConfig &config, cons if (new_val < 0) { throw SyntaxException("Cannot have negative async_threads!"); } - auto new_async_threads = NumericCast(new_val); - if (db) { - TaskScheduler::GetScheduler(*db).SetAsyncThreads(new_async_threads); - } - config.options.async_threads = new_async_threads; - ResizeAutomaticHTTPClientPool(db, config); -} - -void AsyncThreadsSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { - idx_t new_async_threads = config.GetSystemMaxAsyncThreads(*config.file_system); - if (db) { - TaskScheduler::GetScheduler(*db).SetAsyncThreads(new_async_threads); + if (info.db) { + TaskScheduler::GetScheduler(*info.db).SetAsyncThreads(NumericCast(new_val)); } - config.options.async_threads = new_async_threads; - ResizeAutomaticHTTPClientPool(db, config); -} - -Value AsyncThreadsSetting::GetSetting(const ClientContext &context) { - auto &config = DBConfig::GetConfig(context); - return Value::BIGINT(NumericCast(config.options.async_threads)); + ResizeAutomaticHTTPClientPool(info.db, info.config, NumericCast(new_val)); } void HTTPClientPoolCapacitySetting::SetGlobal(DatabaseInstance *db, DBConfig &config, const Value &input) { @@ -1860,13 +1820,7 @@ void WriteBufferRowGroupMemoryLimitSetting::ResetGlobal(DatabaseInstance *db, DB Value WriteBufferRowGroupMemoryLimitSetting::GetSetting(const ClientContext &context) { auto &config = DBConfig::GetConfig(context); - idx_t bytes = 0; - if (config.options.write_buffer_row_group_memory_limit.IsValid()) { - bytes = config.options.write_buffer_row_group_memory_limit.GetIndex(); - } else { - bytes = config.options.maximum_memory / 5 / (config.options.maximum_threads + 1); - } - return Value(StringUtil::BytesToHumanReadableString(bytes)); + return Value(StringUtil::BytesToHumanReadableString(config.GetWriteBufferMemoryLimit())); } void CurrentTransactionInvalidationPolicySetting::OnSet(SettingCallbackInfo &info, Value &input) { @@ -1878,6 +1832,19 @@ void CurrentTransactionInvalidationPolicySetting::OnSet(SettingCallbackInfo &inf EnumUtil::FromString(input.GetValue())); } +//! Undo the dialect_compatibility_mode that selecting the current dialect has set +static void ClearDialectCompatibilityMode(ClientContext &context) { + auto &client_config = ClientConfig::GetConfig(context); + if (!client_config.current_dialect) { + return; + } + auto &config = DatabaseInstance::GetDatabase(context).config; + auto dialect_extension = config.GetCallbackManager().GetDialectExtension(*client_config.current_dialect); + if (dialect_extension && dialect_extension->GetCompatibilityMode()) { + client_config.user_settings.ClearSetting(DialectCompatibilityModeSetting::SettingIndex); + } +} + void CurrentDialectSetting::SetLocal(ClientContext &context, const Value &input) { if (!OnLocalSet(context, input)) { return; @@ -1886,6 +1853,7 @@ void CurrentDialectSetting::SetLocal(ClientContext &context, const Value &input) auto &config = DatabaseInstance::GetDatabase(context).config; if (input.IsNull()) { + ClearDialectCompatibilityMode(context); client_config.current_dialect = std::nullopt; return; } @@ -1898,6 +1866,7 @@ void CurrentDialectSetting::SetLocal(ClientContext &context, const Value &input) auto &dialect_extension = *dialect_extension_p; //! The grammar gets lazily compiled, load it if it wasn't compiled yet (void)dialect_extension.GetCompiledGrammar(context); + ClearDialectCompatibilityMode(context); client_config.current_dialect = dialect_name; auto &compatibility_mode = dialect_extension.GetCompatibilityMode(); if (compatibility_mode) { @@ -1910,6 +1879,7 @@ void CurrentDialectSetting::ResetLocal(ClientContext &context) { if (!OnLocalReset(context)) { return; } + ClearDialectCompatibilityMode(context); ClientConfig::GetConfig(context).current_dialect = std::nullopt; } diff --git a/src/duckdb/src/main/settings/settings.cpp b/src/duckdb/src/main/settings/settings.cpp index cfb558018..7cd8c2eca 100644 --- a/src/duckdb/src/main/settings/settings.cpp +++ b/src/duckdb/src/main/settings/settings.cpp @@ -65,6 +65,22 @@ bool Settings::TryGetSettingInternal(const DatabaseInstance &db, idx_t setting_i return TryGetSettingInternal(DBConfig::GetConfig(db), setting_index, result); } +const DBConfig &Settings::GetConfigInternal(const DatabaseInstance &db) { + return DBConfig::GetConfig(db); +} + +const DBConfig &Settings::GetConfigInternal(const DBConfig &config) { + return config; // NOLINT(bugprone-return-const-ref-from-parameter) +} + +const DBConfig &Settings::GetConfigInternal(const ClientContext &context) { + return DBConfig::GetConfig(context); +} + +const DBConfig &Settings::GetConfigInternal(const Context &context) { + return DBConfig::GetConfig(context.GetDatabase()); +} + void Settings::SetSettingInternal(DatabaseInstance &db, idx_t setting_index, SetScope scope, Value target_value) { SetSettingInternal(DBConfig::GetConfig(db), setting_index, scope, std::move(target_value)); } diff --git a/src/duckdb/src/main/user_settings.cpp b/src/duckdb/src/main/user_settings.cpp index f8c2d42d1..bff02eca9 100644 --- a/src/duckdb/src/main/user_settings.cpp +++ b/src/duckdb/src/main/user_settings.cpp @@ -154,16 +154,52 @@ optional_idx GlobalUserSettings::TryGetExtensionSettingIndex(const Identifier &n #endif } +#if !defined(__MINGW32__) && !defined(__MVS__) +//! The cache of the worker thread running on this thread, if any. A pointer needs no thread_local destructor +static thread_local CachedGlobalSettings *worker_settings_cache = nullptr; // NOLINT +#endif + +WorkerSettingsCache::WorkerSettingsCache() { +} + +WorkerSettingsCache::~WorkerSettingsCache() { +#if !defined(__MINGW32__) && !defined(__MVS__) + if (cache) { + worker_settings_cache = previous.get(); + } +#endif +} + +bool WorkerSettingsCache::IsInitialized() const { + return cache != nullptr; +} + +void WorkerSettingsCache::Initialize() { + cache = make_uniq(); +#if !defined(__MINGW32__) && !defined(__MVS__) + previous = worker_settings_cache; + worker_settings_cache = cache.get(); +#endif +} + #ifndef __MINGW32__ -CachedGlobalSettings &GlobalUserSettings::GetSettings() const { // Cache of global settings - used to allow lock-free access to global settings in a thread-safe manner +static CachedGlobalSettings &GetThreadSettingsCache() { #ifdef __MVS__ static __tlssim current_cache_impl; -#define current_cache (*current_cache_impl.access()) + return *current_cache_impl.access(); #else + if (worker_settings_cache) { + return *worker_settings_cache; + } + // the first use on a thread registers the destructor, which allocates thread_local CachedGlobalSettings current_cache; + return current_cache; #endif +} +CachedGlobalSettings &GlobalUserSettings::GetSettings() const { + auto ¤t_cache = GetThreadSettingsCache(); const auto current_version = settings_version.load(std::memory_order_acquire); if (!current_cache.global_user_settings || this != current_cache.global_user_settings.get() || current_cache.uuid != uuid || current_cache.version != current_version) { @@ -172,10 +208,8 @@ CachedGlobalSettings &GlobalUserSettings::GetSettings() const { current_cache = CachedGlobalSettings(*this, settings_version, settings_map, extension_parameters); } return current_cache; -#ifdef __MVS__ -#undef current_cache -#endif } +#endif hugeint_t GlobalUserSettings::GetUUID() const { return uuid; @@ -194,7 +228,6 @@ CachedGlobalSettings::CachedGlobalSettings(const GlobalUserSettings &global_user extension_setting_indexes.emplace(entry.first, entry.second.setting_index.GetIndex()); } } -#endif //===--------------------------------------------------------------------===// // LocalUserSettings diff --git a/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp b/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp index 2585cea40..ca260a429 100644 --- a/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp +++ b/src/duckdb/src/optimizer/aggregate_function_rewriter.cpp @@ -11,10 +11,14 @@ #include "duckdb/planner/binder.hpp" #include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/planner/expression/bound_case_expression.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" #include "duckdb/planner/expression_nullability.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_projection.hpp" @@ -61,6 +65,34 @@ class AggregateRewriteRule { unique_ptr matcher; }; +//! The rewrite of one aggregate, as an AggregateRewriteAnalyzer has planned it +struct AnalyzedAggregateRewrite { + virtual ~AnalyzedAggregateRewrite() = default; + + //! The aggregate that replaces the original aggregate + unique_ptr aggregate; + //! The helper aggregates of the rewrite. A helper that equals an aggregate of the operator re-uses that aggregate + vector> helpers; + + //! Whether a projection computes the result of the original aggregate: without one, the rewritten aggregate is + //! the result + virtual bool HasProjection() const = 0; + //! The result of the original aggregate, computed from the rewritten aggregate and the helpers (in the order of + //! `helpers`) + virtual unique_ptr CreateProjectionExpression(Optimizer &optimizer, + unique_ptr aggregate_ref, + vector> helper_refs) const = 0; +}; + +//! Plans the rewrite of an aggregate in one step, instead of the matcher and the callbacks of an AggregateRewriteRule +class AggregateRewriteAnalyzer { +public: + virtual ~AggregateRewriteAnalyzer() = default; + + //! Returns the rewrite of the aggregate, or nullptr if the aggregate stays as it is + virtual unique_ptr Analyze(LogicalAggregate &aggr, const Expression &expr) = 0; +}; + static unique_ptr GetSmallIntegerTypesMatcher() { vector types {LogicalTypeId::TINYINT, LogicalTypeId::SMALLINT, LogicalTypeId::INTEGER, LogicalTypeId::BIGINT, LogicalTypeId::UTINYINT, LogicalTypeId::USMALLINT, @@ -177,16 +209,18 @@ class AvgRewriteRule : public AggregateRewriteRule { }; //! SUM(x + C) -> SUM(x) + C * COUNT(x) +//! SUM(x - C) -> SUM(x) - C * COUNT(x) +//! SUM(C - x) -> C * COUNT(x) - SUM(x) class SumRewriteRule : public AggregateRewriteRule { public: explicit SumRewriteRule(Optimizer &optimizer) : AggregateRewriteRule(optimizer) { - // Match SUM(x + C) or SUM(C + x) on integer types + // Match SUM(x + C), SUM(C + x), SUM(x - C) or SUM(C - x) on integer types auto op = make_uniq(); op->function = make_uniq("sum"); op->policy = SetMatcher::Policy::UNORDERED; auto arithmetic = make_uniq(); - arithmetic->function = make_uniq("+"); + arithmetic->function = make_uniq(identifier_set_t {"+", "-"}); arithmetic->type = make_uniq(); auto child_constant_matcher = make_uniq(); auto child_expression_matcher = make_uniq(); @@ -202,35 +236,99 @@ class SumRewriteRule : public AggregateRewriteRule { public: bool ShouldSkip(const LogicalAggregate &aggr) const override { - // This can probably be relaxed to be the same check as AvgRewriteRule, - // but behaviour (for now) is the same as the old SumRewriterOptimizer - return !aggr.groups.empty(); + return !aggr.grouping_functions.empty(); + } + + bool ShouldRewrite(const LogicalAggregate &aggr, Expression &expr) override { + auto &arithmetic = GetArithmetic(expr); + // unsigned subtraction commonly underflows and throws, and the rewrite would hide that error + if (arithmetic.Function().GetName() == "-" && !arithmetic.GetReturnType().IsSigned()) { + return false; + } + if (aggr.groups.empty()) { + return true; + } + if (optimizer.OptimizerDisabled(OptimizerType::COMMON_AGGREGATE)) { + return false; + } + // the added COUNT(x) is extra per-group state, so only rewrite if SUM(x) or COUNT(x) is shared + auto &argument = *arithmetic.GetChildren()[1 - GetConstantIndex(arithmetic)]; + for (auto &other : aggr.expressions) { + if (expr.Equals(*other)) { + continue; + } + if (ComputesSumOrCount(*other, argument)) { + return true; + } + } + return false; } unique_ptr Rewrite(unique_ptr &, vector> &bindings, vector> &additional_expressions) override { auto &sum = bindings[0].get().Cast(); - auto &addition = bindings[1].get().Cast(); - idx_t const_idx = addition.GetChildren()[0]->GetExpressionType() == ExpressionType::VALUE_CONSTANT ? 0 : 1; - auto const_expr = std::move(addition.GetChildrenMutable()[const_idx]); - auto main_expr = std::move(addition.GetChildrenMutable()[1 - const_idx]); - - // Turn SUM(x + C) into SUM(x) + auto &arithmetic = bindings[1].get().Cast(); + const auto const_idx = GetConstantIndex(arithmetic); + const bool is_subtract = arithmetic.Function().GetName() == "-"; + const bool sum_is_left = !is_subtract || const_idx == 1; + auto const_expr = std::move(arithmetic.GetChildrenMutable()[const_idx]); + auto main_expr = std::move(arithmetic.GetChildrenMutable()[1 - const_idx]); + + // Turn SUM(x +/- C) into SUM(x) - this destroys the arithmetic expression sum.GetChildrenMutable()[0] = main_expr->Copy(); additional_expressions.push_back(std::move(const_expr)); + additional_expressions.push_back(make_uniq(Value::BOOLEAN(is_subtract))); + additional_expressions.push_back(make_uniq(Value::BOOLEAN(sum_is_left))); return main_expr; } unique_ptr CreateProjectionExpression(const LogicalType &aggr_type, unique_ptr aggr_ref, vector> additional_expressions) override { - // SUM(x) + C * COUNT(x): additional_expressions[0] is the const, additional_expressions[1] is COUNT(x) ref + // additional_expressions: the const, whether it is a subtraction, whether SUM(x) is the left operand, + // the COUNT(x) ref auto cast_const = BoundCastExpression::AddCastToType(optimizer.context, std::move(additional_expressions[0]), aggr_type); + auto is_subtract = additional_expressions[1]->Cast().GetValue().GetValue(); + auto sum_is_left = additional_expressions[2]->Cast().GetValue().GetValue(); auto cast_count = - BoundCastExpression::AddCastToType(optimizer.context, std::move(additional_expressions[1]), aggr_type); + BoundCastExpression::AddCastToType(optimizer.context, std::move(additional_expressions[3]), aggr_type); auto multiply = optimizer.BindScalarFunction("*", std::move(cast_count), std::move(cast_const)); - return optimizer.BindScalarFunction("+", std::move(aggr_ref), std::move(multiply)); + const Identifier function_name = is_subtract ? "-" : "+"; + if (sum_is_left) { + return optimizer.BindScalarFunction(function_name, std::move(aggr_ref), std::move(multiply)); + } + return optimizer.BindScalarFunction(function_name, std::move(multiply), std::move(aggr_ref)); + } + +private: + static idx_t GetConstantIndex(const BoundFunctionExpression &arithmetic) { + return arithmetic.GetChildren()[0]->GetExpressionType() == ExpressionType::VALUE_CONSTANT ? 0 : 1; + } + + BoundFunctionExpression &GetArithmetic(Expression &expr) { + vector> bindings; + if (!matcher->Match(expr, bindings)) { + throw InternalException("SumRewriteRule: expression does not match SUM(x +/- C)"); + } + return bindings[1].get().Cast(); + } + + //! Whether expr is SUM(argument), COUNT(argument) or SUM(argument +/- C) + bool ComputesSumOrCount(Expression &expr, const Expression &argument) { + vector> bindings; + if (matcher->Match(expr, bindings)) { + auto &arithmetic = bindings[1].get().Cast(); + return arithmetic.GetChildren()[1 - GetConstantIndex(arithmetic)]->Equals(argument); + } + auto &aggregate = expr.Cast(); + if (aggregate.GetFilter() || aggregate.GetOrderBys() || + aggregate.GetAggregateType() != AggregateType::NON_DISTINCT) { + return false; + } + const auto &name = aggregate.Function().GetName(); + auto &children = aggregate.GetChildren(); + return (name == "sum" || name == "count") && children.size() == 1 && children[0]->Equals(argument); } }; @@ -339,17 +437,419 @@ unique_ptr ListRewriteRule::Rewrite(unique_ptr &expr, ve return nullptr; } +//! f(CASE WHEN c THEN x END) -> f(x) FILTER (WHERE c), so that the state is only updated for the matching rows and +//! aggregates that share a condition evaluate it once per chunk. The rewritten forms are the kinds below. +//! +//! Where the aggregate returns a row for an empty input (no groups, or a grouping set without columns), the ELSE 0 +//! forms are wrapped in CASE WHEN count(*) > 0 THEN ... END: the sum over no rows is NULL. +//! +//! The CASE only evaluates x for the matching rows, whereas the FILTER form evaluates it for every row. Hence x must +//! not be able to throw and must not be volatile. +enum class CaseToFilterKind : uint8_t { + //! f(CASE WHEN c THEN x END) -> f(x) FILTER (WHERE c) + //! for sum / count / avg / min / max / bool_and / bool_or: both are NULL (0 for count) without a matching row. + //! A DISTINCT stays on the aggregate: the distinct values of the CASE are the distinct x of the matching rows and + //! a NULL, which these aggregates ignore. An existing FILTER (WHERE p) becomes FILTER (WHERE p AND c) + FILTERED_AGGREGATE, + //! count(CASE WHEN c THEN k END) -> count(*) FILTER (WHERE c) + //! for a non-NULL constant k. Not under DISTINCT: count(DISTINCT CASE WHEN c THEN k END) is 0 or 1, and is + //! rewritten as a FILTERED_AGGREGATE to count(DISTINCT k) FILTER (WHERE c) + FILTERED_COUNT_STAR, + //! sum(CASE WHEN c THEN x ELSE 0 END) -> coalesce(sum(x) FILTER (WHERE c), 0) + //! if x is provably not NULL + COALESCED_SUM, + //! sum(CASE WHEN c THEN x ELSE 0 END) -> CASE WHEN count(*) > count(*) FILTER (WHERE c) + //! THEN coalesce(sum(x) FILTER (WHERE c), 0) + //! ELSE sum(x) FILTER (WHERE c) END + //! if x is nullable: a group in which every row matches and every x is NULL is NULL (a sum over NULLs), any other + //! group without a non-NULL matching x holds a row that contributed the ELSE 0 + NULLABLE_SUM, + //! sum(CASE WHEN c THEN k ELSE 0 END) -> count(*) FILTER (WHERE c) * k + //! for an integer constant k + SCALED_COUNT +}; + +//! The rewrite of one conditional aggregate: its kind, and what the projection above the aggregate needs +struct CaseToFilterRewrite : public AnalyzedAggregateRewrite { + CaseToFilterRewrite(CaseToFilterKind kind_p, LogicalType result_type_p) + : kind(kind_p), result_type(std::move(result_type_p)) { + } + + CaseToFilterKind kind; + //! The type of the original aggregate + LogicalType result_type; + //! The constant of the projection, typed as the sum: the 0 of coalesce(.., 0) or the factor k of the count + Value constant; + //! The helper count(*) FILTER (WHERE c) of NULLABLE_SUM: the number of matching rows + optional_idx matching_count; + //! The helper count(*): the number of rows, for NULLABLE_SUM and for the other ELSE 0 kinds if the aggregate + //! returns a row for an empty input + optional_idx row_count; + + bool HasProjection() const override { + return kind != CaseToFilterKind::FILTERED_AGGREGATE && kind != CaseToFilterKind::FILTERED_COUNT_STAR; + } + + unique_ptr CreateProjectionExpression(Optimizer &optimizer, unique_ptr aggregate_ref, + vector> helper_refs) const override { + unique_ptr result; + switch (kind) { + case CaseToFilterKind::COALESCED_SUM: + case CaseToFilterKind::NULLABLE_SUM: { + // coalesce(sum(x) FILTER (WHERE c), 0) + auto coalesce = make_uniq(ExpressionType::OPERATOR_COALESCE, result_type); + coalesce->GetChildrenMutable().push_back(aggregate_ref->Copy()); + coalesce->GetChildrenMutable().push_back(make_uniq(constant)); + if (kind == CaseToFilterKind::NULLABLE_SUM) { + // only a group with a row that did not match holds the ELSE 0: without one the sum is the result + auto has_else_rows = BoundComparisonExpression::Create( + ExpressionType::COMPARE_GREATERTHAN, std::move(helper_refs[row_count.GetIndex()]), + std::move(helper_refs[matching_count.GetIndex()])); + return make_uniq(std::move(has_else_rows), std::move(coalesce), + std::move(aggregate_ref)); + } + result = std::move(coalesce); + break; + } + case CaseToFilterKind::SCALED_COUNT: + // count(*) FILTER (WHERE c) * k + result = BoundCastExpression::AddCastToType(optimizer.context, std::move(aggregate_ref), result_type); + if (constant != Value::Numeric(result_type, 1)) { + result = + optimizer.BindScalarFunction("*", std::move(result), make_uniq(constant)); + result = BoundCastExpression::AddCastToType(optimizer.context, std::move(result), result_type); + } + break; + default: + throw InternalException("CaseToFilterRewrite: the filtered aggregate is the result"); + } + if (!row_count.IsValid()) { + return result; + } + // the sum over an empty input is NULL + auto has_rows = BoundComparisonExpression::Create(ExpressionType::COMPARE_GREATERTHAN, + std::move(helper_refs[row_count.GetIndex()]), + make_uniq(Value::BIGINT(0))); + return make_uniq(std::move(has_rows), std::move(result), + make_uniq(Value(result_type))); + } +}; + +class CaseToFilterRule : public AggregateRewriteAnalyzer { +public: + CaseToFilterRule(Optimizer &optimizer_p, LogicalOperator &root, bool use_statistics_p) + : optimizer(optimizer_p), nullability(optimizer_p.context, root), + use_statistics(use_statistics_p && !optimizer_p.OptimizerDisabled(OptimizerType::STATISTICS_PROPAGATION)) { + } + +private: + //! The parts of f(CASE WHEN c THEN x [ELSE 0] END), an aggregate that passed the preconditions of the rule + struct ConditionalAggregate { + optional_ptr aggregate; + //! c + optional_ptr condition; + //! x + optional_ptr value; + //! p of an existing FILTER (WHERE p) + optional_ptr filter; + //! Whether the CASE has an ELSE 0 (under sum) instead of an ELSE NULL + bool else_zero = false; + + const string &FunctionName() const { + return aggregate->Function().GetName().GetIdentifierName(); + } + }; + +private: + static bool IsRewritableFunction(const string &name) { + static constexpr const char *FUNCTIONS[] = {"sum", "count", "avg", "min", "max", "bool_and", "bool_or"}; + for (auto &function_name : FUNCTIONS) { + if (name == function_name) { + return true; + } + } + return false; + } + + static bool IsNonNullConstant(const Expression &expr) { + return expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT && + !expr.Cast().GetValue().IsNull(); + } + + static bool IsZero(const Value &value) { + if (value.IsNull() || !value.type().IsNumeric()) { + return false; + } + return value == Value::Numeric(value.type(), 0); + } + + //! Whether the expression is an aggregate over a single-branch CASE that passes the preconditions of the rule + static bool MatchConditionalAggregate(const Expression &expr, ConditionalAggregate &result) { + if (expr.GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) { + return false; + } + auto &aggr = expr.Cast(); + if (aggr.StateExportMode() == AggregateStateExportMode::STATE_EXPORT || aggr.GetOrderBys() || + aggr.GetChildren().size() != 1) { + return false; + } + if (aggr.GetFilter()) { + // the rewritten aggregate has the filter `p AND c`, which evaluates p or c for a part of the rows only + auto &filter = *aggr.GetFilter(); + if (filter.IsVolatile() || !filter.IsConsistent() || filter.CanThrow() || filter.HasSubquery()) { + return false; + } + } + auto &name = aggr.Function().GetName().GetIdentifierName(); + if (!IsRewritableFunction(name)) { + return false; + } + auto &child = *aggr.GetChildren()[0]; + if (child.GetExpressionClass() != ExpressionClass::BOUND_CASE) { + return false; + } + auto &case_expr = child.Cast(); + if (case_expr.CaseChecks().size() != 1) { + return false; + } + auto &when_expr = *case_expr.CaseChecks()[0].when_expr; + auto &then_expr = *case_expr.CaseChecks()[0].then_expr; + auto &else_expr = case_expr.Else(); + if (when_expr.IsVolatile() || !when_expr.IsConsistent() || when_expr.HasSubquery() || when_expr.IsAggregate() || + when_expr.IsWindow()) { + return false; + } + // the CASE evaluates the THEN branch for the matching rows only, the FILTER form for every row + if (then_expr.CanThrow() || then_expr.IsVolatile() || then_expr.HasSubquery()) { + return false; + } + // min / max over strings or nested types update their state faster from the vector of the CASE than from a + // slice of the argument + if ((name == "min" || name == "max") && !TypeIsConstantSize(then_expr.GetReturnType().InternalType())) { + return false; + } + const auto is_sum = name == "sum"; + // the sum of the distinct values adds them in the order of the hash table that holds them, which is another + // order once the values of the rows that do not match are no longer part of it + if ((is_sum || name == "avg") && aggr.IsDistinct() && then_expr.GetReturnType().IsFloating()) { + return false; + } + // sum and avg add value * count for a constant input vector instead of adding the value count times, which + // is another floating point number. A constant THEN branch is such a vector in every chunk: the filtered sum + // would never be the sum of the CASE form, so that it keeps its CASE. A column is not covered by this: it + // only is a constant vector where the scan or a join hands one out (a constant or RLE segment, the one-row + // side of a cross join), and there every sum over it adds the product - with a user-written FILTER, too + if ((is_sum || name == "avg") && then_expr.GetReturnType().IsFloating() && + then_expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { + return false; + } + // the binder casts the branches to the type of the CASE, so that f(x) binds like f(CASE ...) + if (then_expr.GetReturnType() != child.GetReturnType()) { + return false; + } + if (else_expr.GetExpressionClass() != ExpressionClass::BOUND_CONSTANT) { + return false; + } + auto &else_value = else_expr.Cast().GetValue(); + if (!else_value.IsNull()) { + // the ELSE 0 forms count the rows of the group: these counts are not those of the rows that pass an + // existing filter, and the 0 is one of the distinct values + if (!is_sum || !IsZero(else_value) || aggr.GetFilter() || aggr.IsDistinct()) { + return false; + } + } + result.aggregate = aggr; + result.condition = when_expr; + result.value = then_expr; + result.filter = aggr.GetFilter().get(); + result.else_zero = !else_value.IsNull(); + return true; + } + + //! Whether the function returns a value whenever its arguments are values. The default NULL handling only states + //! that a NULL argument gives NULL, not the converse (struct_extract of a NULL field, list_extract past the end) + static bool PreservesNotNull(const BoundFunctionExpression &function) { + if (function.Function().GetNullHandling() != FunctionNullHandling::DEFAULT_NULL_HANDLING) { + return false; + } + auto &name = function.Function().GetName().GetIdentifierName(); + return function.IsOperator() && (name == "+" || name == "-" || name == "*"); + } + + //! Whether the expression is provably not NULL at the output of the operator + bool IsNotNull(LogicalOperator &input, const Expression &expr) { + switch (expr.GetExpressionClass()) { + case ExpressionClass::BOUND_CONSTANT: + return IsNonNullConstant(expr); + case ExpressionClass::BOUND_COLUMN_REF: + return use_statistics && nullability.IsNotNull(input, expr); + case ExpressionClass::BOUND_FUNCTION: { + auto &function = expr.Cast(); + if (BoundCastExpression::IsCast(expr)) { + // a cast between numeric types returns a value or throws + auto &source = BoundCastExpression::Child(function); + return !BoundCastExpression::IsTryCast(function) && source.GetReturnType().IsNumeric() && + expr.GetReturnType().IsNumeric() && IsNotNull(input, source); + } + if (!PreservesNotNull(function) || function.GetChildren().empty()) { + return false; + } + for (auto &child : function.GetChildren()) { + if (!IsNotNull(input, *child)) { + return false; + } + } + return true; + } + default: + return false; + } + } + + //! The form that the aggregate is rewritten to + CaseToFilterKind GetKind(LogicalAggregate &aggr, const ConditionalAggregate &input) { + auto &value = *input.value; + if (!input.else_zero) { + if (input.FunctionName() == "count" && IsNonNullConstant(value) && !input.aggregate->IsDistinct()) { + return CaseToFilterKind::FILTERED_COUNT_STAR; + } + return CaseToFilterKind::FILTERED_AGGREGATE; + } + // k * count(*) is only the exact sum for an integer k + const auto sum_type = input.aggregate->GetReturnType().id(); + if (IsNonNullConstant(value) && value.GetReturnType().IsIntegral() && + (sum_type == LogicalTypeId::HUGEINT || sum_type == LogicalTypeId::UHUGEINT)) { + return CaseToFilterKind::SCALED_COUNT; + } + if (IsNotNull(*aggr.children[0], value)) { + return CaseToFilterKind::COALESCED_SUM; + } + return CaseToFilterKind::NULLABLE_SUM; + } + + //! Binds count(*), with an optional filter + unique_ptr BindCountStar(unique_ptr filter) const { + FunctionBinder function_binder(optimizer.context); + auto count_fun = GetBuiltinAggregateFunction(optimizer.context, CountFun::Name, {}); + return function_binder.BindAggregateFunction(count_fun, {}, std::move(filter), AggregateType::NON_DISTINCT); + } + + //! The filter of the rewritten aggregate: c, or `p AND c` for an aggregate with a FILTER (WHERE p). A row passes + //! it if p and c are both true, which are the rows that the CASE aggregate reads a value for + static unique_ptr GetFilter(const ConditionalAggregate &input) { + if (!input.filter) { + return input.condition->Copy(); + } + return make_uniq(ExpressionType::CONJUNCTION_AND, input.filter->Copy(), + input.condition->Copy()); + } + + //! Binds the filtered aggregate that replaces the conditional aggregate, or returns nullptr if it cannot replace it + unique_ptr BindFiltered(const ConditionalAggregate &input, CaseToFilterKind kind) const { + auto &aggr = *input.aggregate; + unique_ptr result; + if (kind == CaseToFilterKind::FILTERED_COUNT_STAR || kind == CaseToFilterKind::SCALED_COUNT) { + result = BindCountStar(GetFilter(input)); + if (result->GetReturnType() != LogicalType::BIGINT) { + return nullptr; + } + } else { + auto function = TryGetBuiltinAggregateFunction(optimizer.context, aggr.Function().GetName(), + {input.value->GetReturnType()}); + if (!function) { + return nullptr; + } + FunctionBinder function_binder(optimizer.context); + vector> children; + children.push_back(input.value->Copy()); + result = function_binder.BindAggregateFunction(function, std::move(children), GetFilter(input), + aggr.GetAggregateType()); + if (result->GetReturnType() != aggr.GetReturnType()) { + return nullptr; + } + } + result->SetAlias(aggr.GetAlias()); + return result; + } + + //! Whether the aggregate returns a row for an empty input + static bool HasEmptyGroupingSet(const LogicalAggregate &aggr) { + if (aggr.groups.empty()) { + return true; + } + for (auto &grouping_set : aggr.grouping_sets) { + if (grouping_set.empty()) { + return true; + } + } + return false; + } + +public: + unique_ptr Analyze(LogicalAggregate &aggr, const Expression &expr) override { + ConditionalAggregate input; + if (!MatchConditionalAggregate(expr, input)) { + return nullptr; + } + const auto kind = GetKind(aggr, input); + auto result = make_uniq(kind, expr.GetReturnType()); + if (result->HasProjection()) { + const auto constant = kind == CaseToFilterKind::SCALED_COUNT + ? input.value->Cast().GetValue() + : Value::INTEGER(0); + auto typed_constant = constant.DefaultTryCastAs(result->result_type); + if (!typed_constant) { + return nullptr; + } + result->constant = std::move(*typed_constant); + } + result->aggregate = BindFiltered(input, kind); + if (!result->aggregate) { + return nullptr; + } + if (kind == CaseToFilterKind::NULLABLE_SUM) { + // count(*) > count(*) FILTER (WHERE c): a row of the group took the ELSE 0 + result->matching_count = optional_idx(result->helpers.size()); + result->helpers.push_back(BindCountStar(input.condition->Copy())); + } + if (kind == CaseToFilterKind::NULLABLE_SUM || (result->HasProjection() && HasEmptyGroupingSet(aggr))) { + // count(*) > 0: the aggregate has seen a row + result->row_count = optional_idx(result->helpers.size()); + result->helpers.push_back(BindCountStar(nullptr)); + } + return std::move(result); + } + +private: + Optimizer &optimizer; + NotNullExpressionAnalyzer nullability; + //! Whether a column may be proven NOT NULL: the proof reads the statistics of the scanned tables, which the + //! optimizer does not use for a plan with a data-modifying CTE (the rows change while the query runs) + const bool use_statistics; +}; + //! Internal LogicalOperatorVisitor that does the actual rewriting class AggregateFunctionRewriterInternal : public LogicalOperatorVisitor { public: AggregateFunctionRewriterInternal(Optimizer &optimizer, AggregateRewriteRule &rule) : optimizer(optimizer), rule(rule) { } + AggregateFunctionRewriterInternal(Optimizer &optimizer, AggregateRewriteAnalyzer &analyzer) + : optimizer(optimizer), analyzer(analyzer) { + } private: + AggregateFunctionRewriterInternal(Optimizer &optimizer, optional_ptr rule, + optional_ptr analyzer) + : optimizer(optimizer), rule(rule), analyzer(analyzer) { + } + struct RewriteInfo { idx_t count_idx; vector> additional_expressions; + //! The rewrite that an analyzer has planned, and the indexes of its helper aggregates + unique_ptr analyzed; + vector helper_indexes; }; public: @@ -367,7 +867,7 @@ class AggregateFunctionRewriterInternal : public LogicalOperatorVisitor { case LogicalOperatorType::LOGICAL_INTERSECT: case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: case LogicalOperatorType::LOGICAL_PROJECTION: { - AggregateFunctionRewriterInternal rewriter(optimizer, rule); + AggregateFunctionRewriterInternal rewriter(optimizer, rule, analyzer); rewriter.StandardVisitOperator(op); return; } @@ -395,26 +895,57 @@ class AggregateFunctionRewriterInternal : public LogicalOperatorVisitor { return nullptr; } + //! Replaces the aggregate by the rewrite that the analyzer returns for it (if any) and adds the helper aggregates + bool RewriteAnalyzed(LogicalAggregate &aggr, idx_t aggr_idx, RewriteInfo &rewrite_info) { + rewrite_info.analyzed = analyzer->Analyze(aggr, *aggr.expressions[aggr_idx]); + if (!rewrite_info.analyzed) { + return false; + } + auto &analyzed = *rewrite_info.analyzed; + aggr.expressions[aggr_idx] = std::move(analyzed.aggregate); + for (auto &helper : analyzed.helpers) { + idx_t helper_idx; + for (helper_idx = 0; helper_idx < aggr.expressions.size(); helper_idx++) { + if (aggr.expressions[helper_idx]->Equals(*helper)) { + break; + } + } + if (helper_idx == aggr.expressions.size()) { + aggr.expressions.push_back(std::move(helper)); + } + rewrite_info.helper_indexes.push_back(helper_idx); + } + return true; + } + void RewriteAggregates(unique_ptr &op) { auto &aggr = op->Cast(); - if (rule.ShouldSkip(aggr)) { + if (rule && rule->ShouldSkip(aggr)) { return; } const idx_t aggr_count = aggr.expressions.size(); unordered_map rewrites; + bool needs_projection = false; for (idx_t i = 0; i < aggr_count; ++i) { + RewriteInfo rewrite_info; + if (analyzer) { + if (RewriteAnalyzed(aggr, i, rewrite_info)) { + needs_projection = needs_projection || rewrite_info.analyzed->HasProjection(); + rewrites.emplace(i, std::move(rewrite_info)); + } + continue; + } auto &expr = aggr.expressions[i]; vector> bindings; - if (!rule.matcher->Match(*expr, bindings)) { + if (!rule->matcher->Match(*expr, bindings)) { continue; } - if (!rule.ShouldRewrite(aggr, *expr)) { + if (!rule->ShouldRewrite(aggr, *expr)) { continue; } - RewriteInfo rewrite_info; - auto count_arg = rule.Rewrite(expr, bindings, rewrite_info.additional_expressions); + auto count_arg = rule->Rewrite(expr, bindings, rewrite_info.additional_expressions); // Add COUNT([x]) to the aggregate list - the count set holds both the unary count and count_star FunctionBinder function_binder(optimizer.context); @@ -431,9 +962,11 @@ class AggregateFunctionRewriterInternal : public LogicalOperatorVisitor { rewrite_info.count_idx = aggr.expressions.size(); rewrites.emplace(i, std::move(rewrite_info)); aggr.expressions.push_back(std::move(count_aggr)); + needs_projection = true; } - if (rewrites.empty()) { + if (!needs_projection) { + // nothing was rewritten, or every rewritten aggregate is the result as it is return; } @@ -465,13 +998,29 @@ class AggregateFunctionRewriterInternal : public LogicalOperatorVisitor { } auto &rewrite_info = rewrite_entry->second; + if (rewrite_info.analyzed) { + if (!rewrite_info.analyzed->HasProjection()) { + // The rewritten aggregate is the result + projection_expressions.push_back(std::move(aggr_ref)); + continue; + } + vector> helper_refs; + for (auto &helper_idx : rewrite_info.helper_indexes) { + ColumnBinding helper_binding(aggr.aggregate_index, ProjectionIndex(helper_idx)); + helper_refs.push_back(make_uniq( + aggr.expressions[helper_idx]->GetReturnType(), helper_binding)); + } + projection_expressions.push_back(rewrite_info.analyzed->CreateProjectionExpression( + optimizer, std::move(aggr_ref), std::move(helper_refs))); + continue; + } ColumnBinding count_binding(aggr.aggregate_index, ProjectionIndex(rewrite_info.count_idx)); auto count_ref = make_uniq( aggr.expressions[rewrite_info.count_idx]->GetReturnType(), count_binding); rewrite_info.additional_expressions.push_back(std::move(count_ref)); - auto final_result = rule.CreateProjectionExpression(aggr_type, std::move(aggr_ref), - std::move(rewrite_info.additional_expressions)); + auto final_result = rule->CreateProjectionExpression(aggr_type, std::move(aggr_ref), + std::move(rewrite_info.additional_expressions)); projection_expressions.push_back(std::move(final_result)); } @@ -495,7 +1044,9 @@ class AggregateFunctionRewriterInternal : public LogicalOperatorVisitor { private: Optimizer &optimizer; - AggregateRewriteRule &rule; + //! The rewrites are either those of a rule or those that an analyzer plans + optional_ptr rule; + optional_ptr analyzer; column_binding_map_t aggregate_map; }; @@ -518,4 +1069,10 @@ void AggregateFunctionRewriter::Optimize(unique_ptr &op) { } } +void AggregateFunctionRewriter::RewriteCaseToFilter(unique_ptr &op, bool use_statistics) { + CaseToFilterRule rule(optimizer, *op, use_statistics); + AggregateFunctionRewriterInternal rewriter(optimizer, rule); + rewriter.Optimize(op); +} + } // namespace duckdb diff --git a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp index 4759d8616..03ccbb216 100644 --- a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp +++ b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp @@ -1,142 +1,20 @@ #include "duckdb/optimizer/apply_functional_dependencies.hpp" -#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" -#include "duckdb/parser/constraints/not_null_constraint.hpp" -#include "duckdb/parser/constraints/unique_constraint.hpp" #include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/planner/expression_binder/base_select_binder.hpp" -#include "duckdb/planner/operator/logical_aggregate.hpp" -#include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_order.hpp" -#include "duckdb/planner/operator/logical_projection.hpp" namespace duckdb { -void ApplyFunctionalDependencies::VisitLogicalGet(LogicalGet &get) { - VisitOperatorChildren(get); - // Table-in/out functions need not preserve the multiplicity of their input keys. - result.clear(); - - auto table = get.GetTable(); - if (!table || !table->IsDuckTable() || !get.children.empty() || get.GetColumnIds().empty()) { - return; - } - unordered_map column_bindings; - for (auto &binding : get.GetColumnBindings()) { - auto &column_index = get.GetColumnIndex(binding); - if (!column_index.HasPrimaryIndex() || column_index.HasChildren() || column_index.IsVirtualColumn()) { - continue; - } - column_bindings.emplace(column_index.GetPrimaryIndex(), binding); - } - auto &columns = table->GetColumns(); - auto &constraints = table->GetConstraints(); - unordered_set not_null_columns; - for (auto &constraint : constraints) { - if (constraint->type == ConstraintType::NOT_NULL) { - not_null_columns.insert(constraint->Cast().index.index); - } - } - for (auto &constraint : constraints) { - if (constraint->type != ConstraintType::UNIQUE) { - continue; - } - auto &unique = constraint->Cast(); - if (unique.IsDeferred()) { - continue; - } - auto &names = unique.GetColumnNames(); - if (!unique.HasIndex() && !std::all_of(names.begin(), names.end(), - [&](const Identifier &name) { return columns.ColumnExists(name); })) { - continue; - } - column_binding_set_t key; - bool usable = true; - for (auto &column : unique.GetLogicalIndexes(columns)) { - auto entry = column_bindings.find(column.index); - if (entry == column_bindings.end() || - (!unique.IsPrimaryKey() && not_null_columns.find(column.index) == not_null_columns.end())) { - usable = false; - break; - } - key.insert(entry->second); - } - if (usable && !key.empty()) { - result.push_back(std::move(key)); - } - } -} - -void ApplyFunctionalDependencies::VisitLogicalAggregate(LogicalAggregate &aggr) { - VisitOperatorChildren(aggr); - - // TODO: use child FDs to simplify groupings. - result.clear(); - - if (aggr.groups.empty() || aggr.grouping_sets.size() > 1 || !aggr.grouping_functions.empty()) { - return; - } - column_binding_set_t key; - if (aggr.grouping_sets.empty()) { - for (auto group_idx : ProjectionIndex::GetIndexes(aggr.groups.size())) { - key.insert(ColumnBinding(aggr.group_index, group_idx)); - } - } else { - for (auto group_idx : aggr.grouping_sets[0]) { - if (group_idx.GetIndex() >= aggr.groups.size()) { - return; - } - key.insert(ColumnBinding(aggr.group_index, group_idx)); - } - } - if (!key.empty()) { - result.push_back(std::move(key)); - } -} - -void ApplyFunctionalDependencies::VisitLogicalProjection(LogicalProjection &projection) { - VisitOperatorChildren(projection); - - vector child_sets; - child_sets.swap(result); - if (child_sets.empty()) { - return; - } - column_binding_map_t forwarded; - for (auto expr_idx : ProjectionIndex::GetIndexes(projection.expressions.size())) { - auto &expr = *projection.expressions[expr_idx]; - if (expr.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { - forwarded.emplace(expr.Cast().Binding(), - ColumnBinding(projection.table_index, expr_idx)); - } - } - for (auto &child_set : child_sets) { - column_binding_set_t key; - bool complete = true; - for (auto &binding : child_set) { - auto entry = forwarded.find(binding); - if (entry == forwarded.end()) { - complete = false; - break; - } - key.insert(entry->second); - } - if (complete) { - result.push_back(std::move(key)); - } - } -} - void ApplyFunctionalDependencies::VisitLogicalOrder(LogicalOrder &order) { - VisitOperatorChildren(order); - + result = distinctness.GetUniqueSets(*order.children[0]); VisitOrderBys(order.orders); } void ApplyFunctionalDependencies::VisitOrderBys(vector &orders) const { - if (orders.size() < 2 || read_only) { + if (orders.size() < 2) { return; } @@ -183,10 +61,6 @@ void ApplyFunctionalDependencies::VisitOrderBys(vector &orders } void ApplyFunctionalDependencies::VisitPartitioning(vector> &partitions) const { - if (read_only) { - return; - } - // Remove partitioning keys that are FD on the others for (idx_t i = 0; i < partitions.size();) { vector> refs; @@ -259,7 +133,7 @@ void ApplyFunctionalDependencies::VisitWindowExpression(BoundWindowExpression &w // so there is only one peer group, which is the same as having no ORDER BY clause. auto &partition_bys = wexpr.Partitions(); auto &order_bys = wexpr.OrderByMutable(); - if (!read_only && !partition_bys.empty() && order_bys.size() == 1) { + if (!partition_bys.empty() && order_bys.size() == 1) { vector> refs; for (auto &arg : partition_bys) { refs.emplace_back(*arg); @@ -281,32 +155,16 @@ void ApplyFunctionalDependencies::VisitExpression(unique_ptr *expres } void ApplyFunctionalDependencies::VisitOperator(LogicalOperator &op) { + VisitOperatorChildren(op); switch (op.type) { case LogicalOperatorType::LOGICAL_ORDER_BY: VisitLogicalOrder(op.Cast()); break; - case LogicalOperatorType::LOGICAL_FILTER: - case LogicalOperatorType::LOGICAL_LIMIT: - VisitOperatorChildren(op); - break; case LogicalOperatorType::LOGICAL_WINDOW: - VisitOperatorChildren(op); + result = distinctness.GetUniqueSets(*op.children[0]); VisitOperatorExpressions(op); - // Windowing only adds bindings - break; - case LogicalOperatorType::LOGICAL_PROJECTION: - VisitLogicalProjection(op.Cast()); - break; - case LogicalOperatorType::LOGICAL_GET: - VisitLogicalGet(op.Cast()); - break; - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: - VisitLogicalAggregate(op.Cast()); break; default: - VisitOperatorChildren(op); - // Clear the keys because we don't know if the operator preserves them. - result.clear(); break; } } diff --git a/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp b/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp index 852f461ad..7aa17ae3e 100644 --- a/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp +++ b/src/duckdb/src/optimizer/build_probe_side_optimizer.cpp @@ -429,12 +429,13 @@ void BuildProbeSideOptimizer::VisitOperator(LogicalOperator &op) { switch (join.join_type) { case JoinType::SEMI: case JoinType::ANTI: { - // if the conditions have no equality, do not flip the children. - // There is no physical join operator (yet) that can do an inequality right_semi/anti join. + // flip only where a physical operator implements the flipped join: the hash join on an equality, and the + // piecewise merge join for a RIGHT SEMI join on a single range condition idx_t has_range = 0; bool prefer_range_joins = Settings::Get(context); - if (op.type == LogicalOperatorType::LOGICAL_ANY_JOIN || - (op.Cast().HasEquality(has_range) && !prefer_range_joins)) { + const bool has_equality = join.HasEquality(has_range); + const bool single_range = join.join_type == JoinType::SEMI && join.conditions.size() == 1 && has_range == 1; + if ((has_equality && !prefer_range_joins) || single_range) { TryFlipJoinChildren(join); } break; diff --git a/src/duckdb/src/optimizer/column_binding_replacer.cpp b/src/duckdb/src/optimizer/column_binding_replacer.cpp index e3e66bae1..64fe81d1e 100644 --- a/src/duckdb/src/optimizer/column_binding_replacer.cpp +++ b/src/duckdb/src/optimizer/column_binding_replacer.cpp @@ -19,11 +19,10 @@ ReplacementBinding::ReplacementBinding(ColumnBinding old_binding, ColumnBinding ReplacementBinding BindingReplacementGraph::ResolveReplacement(ColumnBinding binding) const { ReplacementBinding result(binding, binding); - column_binding_set_t visited; - while (visited.insert(result.new_binding).second) { - auto replacement = Find(result.new_binding); - if (!replacement) { - return result; + idx_t traversed_edges = 0; + while (auto replacement = Find(result.new_binding)) { + if (++traversed_edges > replacement_bindings.size()) { + throw InternalException("Cyclic column binding replacements"); } result.new_binding = replacement->new_binding; if (replacement->replace_type) { @@ -31,7 +30,7 @@ ReplacementBinding BindingReplacementGraph::ResolveReplacement(ColumnBinding bin result.new_type = replacement->new_type; } } - throw InternalException("Cyclic column binding replacements"); + return result; } optional_ptr BindingReplacementGraph::Find(ColumnBinding old_binding) const { @@ -108,8 +107,13 @@ void BindingReplacementGraph::AddTo(ColumnBindingReplacer &replacer) const { ColumnBindingReplacer::ColumnBindingReplacer() { } +ColumnBindingReplacer::ColumnBindingReplacer(const BindingReplacementGraph &replacements) + : replacement_graph(replacements) { +} + void ColumnBindingReplacer::AddReplacements(const vector &old_bindings, const vector &new_bindings) { + D_ASSERT(!replacement_graph); if (old_bindings.size() != new_bindings.size()) { throw InternalException("Column binding replacement lists must have the same size"); } @@ -122,6 +126,7 @@ void ColumnBindingReplacer::AddReplacements(const vector &old_bin } void ColumnBindingReplacer::BuildIndex() { + D_ASSERT(!replacement_graph); replacement_index.clear(); use_index = false; column_binding_map_t index; @@ -150,6 +155,11 @@ optional_ptr ColumnBindingReplacer::FindReplacement(Co } void ColumnBindingReplacer::Replace(ColumnBinding &binding) const { + if (replacement_graph) { + D_ASSERT(replacement_bindings.empty()); + binding = replacement_graph->Resolve(binding); + return; + } if (use_index) { auto replacement = FindReplacement(binding); if (replacement) { @@ -165,6 +175,15 @@ void ColumnBindingReplacer::Replace(ColumnBinding &binding) const { } void ColumnBindingReplacer::Replace(ColumnBinding &binding, LogicalType &type) const { + if (replacement_graph) { + D_ASSERT(replacement_bindings.empty()); + auto replacement = replacement_graph->ResolveReplacement(binding); + binding = replacement.new_binding; + if (replacement.replace_type) { + type = replacement.new_type; + } + return; + } if (use_index) { auto replacement = FindReplacement(binding); if (replacement) { @@ -215,6 +234,17 @@ void ColumnBindingReplacer::VisitOperatorBindings(LogicalOperator &op) { unique_ptr ColumnBindingReplacer::VisitReplace(BoundColumnRefExpression &expr, unique_ptr *expr_ptr) { + if (replacement_graph) { + D_ASSERT(replacement_bindings.empty()); + auto replacement = replacement_graph->ResolveReplacement(expr.Binding()); + if (replacement.replace_type) { + return expr.WithBinding(replacement.new_binding, replacement.new_type); + } + if (replacement.new_binding == expr.Binding()) { + return nullptr; + } + return expr.WithBinding(replacement.new_binding); + } if (use_index) { auto replacement = FindReplacement(expr.Binding()); if (!replacement) { @@ -312,9 +342,7 @@ void ColumnBindingRewrite::ApplyToOperatorBindings(LogicalOperator &op, const Bi if (replacements.Empty()) { return; } - CorrelatedColumnBindingReplacer replacer; - replacements.AddTo(replacer); - replacer.BuildIndex(); + CorrelatedColumnBindingReplacer replacer(replacements); replacer.VisitOperatorBindings(op); } diff --git a/src/duckdb/src/optimizer/constant_or_null_simplification.cpp b/src/duckdb/src/optimizer/constant_or_null_simplification.cpp index 5581f9b72..b0c35c503 100644 --- a/src/duckdb/src/optimizer/constant_or_null_simplification.cpp +++ b/src/duckdb/src/optimizer/constant_or_null_simplification.cpp @@ -52,13 +52,6 @@ static bool ConstantOrNullInputsAreNotNull(LogicalOperator &input, BoundFunction // Folding is only valid when the NULL-preserving inputs cannot be NULL. for (idx_t child_idx = 1; child_idx < children.size(); ++child_idx) { - if (children[child_idx]->GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { - auto &constant = children[child_idx]->Cast().GetValue(); - if (!constant.IsNull()) { - continue; - } - } - if (!analyzer.IsNotNull(input, *children[child_idx])) { return false; } @@ -105,18 +98,17 @@ unique_ptr ConstantOrNullSimplification::SimplifyExpression(LogicalO return expr; } -unique_ptr ConstantOrNullSimplification::OptimizeFilter(unique_ptr op, - bool plan_has_side_effects) { +void ConstantOrNullSimplification::OptimizeFilter(unique_ptr &op, bool plan_has_side_effects, + NotNullExpressionAnalyzer &analyzer) { auto &filter = op->Cast(); if (filter.children.size() != 1) { - return op; + return; } // Folding removes the NULL check, so disable it for plans with side effects. // Same-statement DML can add NULLs after statistics-based nullability analysis. const bool allow_folding = !plan_has_side_effects; - NotNullExpressionAnalyzer analyzer(context); vector> remaining_expressions; remaining_expressions.reserve(filter.expressions.size()); for (auto &expr : filter.expressions) { @@ -125,40 +117,42 @@ unique_ptr ConstantOrNullSimplification::OptimizeFilter(unique_ if (!value.has_value()) { remaining_expressions.push_back(std::move(expr)); } else if (!value.value()) { - return make_uniq(std::move(op)); + op = make_uniq(std::move(op)); + return; } } if (!remaining_expressions.empty()) { filter.expressions = std::move(remaining_expressions); - return op; + return; } if (filter.projection_map.empty()) { - return std::move(filter.children[0]); + auto child = std::move(filter.children[0]); + op = std::move(child); + return; } remaining_expressions.push_back(make_uniq(Value::BOOLEAN(true))); filter.expressions = std::move(remaining_expressions); - return op; } unique_ptr ConstantOrNullSimplification::Optimize(unique_ptr op) { const bool has_side_effects = op->HasSideEffects(); - return OptimizeInternal(std::move(op), has_side_effects); + NotNullExpressionAnalyzer analyzer(context, *op); + OptimizeInternal(op, has_side_effects, analyzer); + return op; } -unique_ptr ConstantOrNullSimplification::OptimizeInternal(unique_ptr op, - bool plan_has_side_effects) { +void ConstantOrNullSimplification::OptimizeInternal(unique_ptr &op, bool plan_has_side_effects, + NotNullExpressionAnalyzer &analyzer) { for (auto &child : op->children) { - child = OptimizeInternal(std::move(child), plan_has_side_effects); + OptimizeInternal(child, plan_has_side_effects, analyzer); } if (op->type == LogicalOperatorType::LOGICAL_FILTER) { - return OptimizeFilter(std::move(op), plan_has_side_effects); + OptimizeFilter(op, plan_has_side_effects, analyzer); } - - return op; } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/cte_filter_pusher.cpp b/src/duckdb/src/optimizer/cte_filter_pusher.cpp index 73b820273..8c446ee36 100644 --- a/src/duckdb/src/optimizer/cte_filter_pusher.cpp +++ b/src/duckdb/src/optimizer/cte_filter_pusher.cpp @@ -22,13 +22,11 @@ CTEFilterPusher::CTEFilterPusher(Optimizer &optimizer_p) : optimizer(optimizer_p unique_ptr CTEFilterPusher::Optimize(unique_ptr op) { FindCandidates(*op); + // A join that keeps only the matching rows of a CTE reference filters that reference like a consumer filter. + GenerateSemiJoinFilters(*op); if (cte_info_map.empty()) { return op; } - // Scalar producer pushdown must preserve markers referenced by CTE consumers. - FilterPushdown pushdown(optimizer); - unordered_set referenced_bindings; - pushdown.CheckMarkToSemi(*op, referenced_bindings); auto ctes = std::move(cte_info_map); // Iterate once over all materialized CTEs @@ -178,7 +176,7 @@ void CTEFilterPusher::PushFilterIntoCTE(MaterializedCTEInfo &info) { new_cte->children.push_back(std::move(info.materialized_cte.children[0])); // Push down the filter - FilterPushdown pushdown(optimizer, true, FilterPushdown::ProjectionMode::PRESERVE_COMPUTED_EXPRESSIONS); + FilterPushdown pushdown(optimizer, FilterPushdown::ProjectionMode::PRESERVE_COMPUTED_EXPRESSIONS); new_cte = pushdown.Rewrite(std::move(new_cte)); info.materialized_cte.children[0] = std::move(new_cte); diff --git a/src/duckdb/src/optimizer/cte_semi_join_filter_transfer.cpp b/src/duckdb/src/optimizer/cte_semi_join_filter_transfer.cpp new file mode 100644 index 000000000..277aad053 --- /dev/null +++ b/src/duckdb/src/optimizer/cte_semi_join_filter_transfer.cpp @@ -0,0 +1,333 @@ +#include "duckdb/optimizer/cte_filter_pusher.hpp" + +#include "duckdb/optimizer/filter_combiner.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" + +namespace duckdb { + +//! The search follows one column, but the equalities of an INNER join fork it: the bound keeps it linear +static constexpr idx_t MAX_SEARCH_STEPS = 256; + +static optional_ptr PlainColumn(const Expression &expr) { + if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return nullptr; + } + auto &column_ref = expr.Cast(); + if (column_ref.Depth() != 0) { + return nullptr; + } + return &column_ref; +} + +static bool IsEquality(const JoinCondition &condition) { + return condition.IsComparison() && (condition.GetComparisonType() == ExpressionType::COMPARE_EQUAL || + condition.GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM); +} + +static bool HasBinding(LogicalOperator &op, const ColumnBinding &binding) { + for (auto &op_binding : op.GetColumnBindings()) { + if (op_binding == binding) { + return true; + } + } + return false; +} + +//! Adds the conjuncts of the filter that compare `column` with constants and cannot throw +static void AddColumnFilters(const Expression &filter, const BoundColumnRefExpression &column, + vector> &result) { + if (filter.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + for (auto &child : filter.Cast().GetChildren()) { + AddColumnFilters(*child, column, result); + } + return; + } + auto compared = FilterCombiner::GetComparedExpression(filter); + if (compared && compared->Equals(column) && !filter.CanThrow()) { + result.push_back(filter.Copy()); + } +} + +//! Adds the filters that compare `column`, a column of `op`, with constants and that every row of `op` passes +static void GuaranteedColumnFilters(LogicalOperator &op, const BoundColumnRefExpression &column, idx_t &steps, + vector> &result) { + if (++steps > MAX_SEARCH_STEPS) { + return; + } + // the filters on a column of the child that is passed on as `column` + auto follow = [&](LogicalOperator &child, const BoundColumnRefExpression &source) { + if (source.Binding() == column.Binding()) { + GuaranteedColumnFilters(child, column, steps, result); + return; + } + if (source.GetReturnType() != column.GetReturnType()) { + return; + } + vector> source_filters; + GuaranteedColumnFilters(child, source, steps, source_filters); + for (auto &filter : source_filters) { + result.push_back(ExpressionIterator::ReplaceExpression(*filter, source, column)); + } + }; + auto &binding = column.Binding(); + switch (op.type) { + case LogicalOperatorType::LOGICAL_FILTER: + for (auto &expr : op.expressions) { + AddColumnFilters(*expr, column, result); + } + follow(*op.children[0], column); + break; + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &projection = op.Cast(); + if (binding.table_index != projection.table_index || binding.column_index.GetIndex() >= op.expressions.size()) { + break; + } + auto source = PlainColumn(*op.expressions[binding.column_index.GetIndex()]); + if (source) { + follow(*op.children[0], *source); + } + break; + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + // grouping sets add NULL groups that the filters below do not describe + auto &aggregate = op.Cast(); + if (binding.table_index != aggregate.group_index || aggregate.grouping_sets.size() > 1 || + binding.column_index.GetIndex() >= aggregate.groups.size()) { + break; + } + auto source = PlainColumn(*aggregate.groups[binding.column_index.GetIndex()]); + if (source) { + follow(*op.children[0], *source); + } + break; + } + case LogicalOperatorType::LOGICAL_GET: { + auto &get = op.Cast(); + if (binding.table_index != get.table_index || !op.children.empty()) { + break; + } + auto filter = get.table_filters.TryGetFilterByColumnIndex(binding.column_index); + // an optional filter is a hint the scan may ignore + if (!filter || ExpressionFilter::IsOptionalFilter(*filter)) { + break; + } + AddColumnFilters(*filter->ToExpression(column), column, result); + break; + } + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { + auto &join = op.Cast(); + if (op.children.size() != 2) { + break; + } + optional_idx side; + for (idx_t child_idx = 0; child_idx < 2; child_idx++) { + if (HasBinding(*op.children[child_idx], binding)) { + side = child_idx; + break; + } + } + if (!side.IsValid()) { + break; + } + // the side that an outer join extends with NULLs has rows its filters do not describe + const auto side_idx = side.GetIndex(); + bool preserved; + switch (join.join_type) { + case JoinType::INNER: + preserved = true; + break; + case JoinType::LEFT: + case JoinType::SEMI: + case JoinType::ANTI: + case JoinType::MARK: + preserved = side_idx == 0; + break; + case JoinType::RIGHT: + preserved = side_idx == 1; + break; + default: + preserved = false; + break; + } + if (!preserved) { + break; + } + follow(*op.children[side_idx], column); + if (join.join_type != JoinType::INNER) { + break; + } + // the rows of an INNER join also pass what the filters on the other side imply through its equalities + auto &other_child = *op.children[1 - side_idx]; + vector> other_filters; + for (auto &condition : join.conditions) { + if (!IsEquality(condition)) { + continue; + } + auto own = PlainColumn(side_idx == 0 ? condition.GetLHS() : condition.GetRHS()); + auto other = PlainColumn(side_idx == 0 ? condition.GetRHS() : condition.GetLHS()); + if (own && other && own->Binding() == binding && HasBinding(other_child, other->Binding())) { + GuaranteedColumnFilters(other_child, *other, steps, other_filters); + } + } + vector> filters; + for (auto &filter : other_filters) { + filters.push_back(*filter); + } + FilterCombiner::GenerateJoinFilters(join.conditions, filters, side_idx == 0 ? JoinSide::LEFT : JoinSide::RIGHT, + [&](unique_ptr filter) { + // an equality of the other column with another column of this side + AddColumnFilters(*filter, column, result); + }); + break; + } + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + for (auto &child : op.children) { + if (HasBinding(*child, binding)) { + follow(*child, column); + break; + } + } + break; + case LogicalOperatorType::LOGICAL_ORDER_BY: + case LogicalOperatorType::LOGICAL_LIMIT: + case LogicalOperatorType::LOGICAL_TOP_N: + case LogicalOperatorType::LOGICAL_DISTINCT: + case LogicalOperatorType::LOGICAL_WINDOW: + // rows are removed, reordered or kept, the columns of the child pass through under their own bindings + if (op.children.size() == 1 && HasBinding(*op.children[0], binding)) { + follow(*op.children[0], column); + } + break; + default: + // set operations and CTE references end the search + break; + } +} + +//! The join that keeps only the left rows with a match: a SEMI join, or a MARK join below a filter on its bare mark +static optional_ptr FilteringJoin(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &join = op.Cast(); + return join.join_type == JoinType::SEMI && op.children.size() == 2 ? &join : nullptr; + } + if (op.type != LogicalOperatorType::LOGICAL_FILTER || + op.children[0]->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return nullptr; + } + auto &join = op.children[0]->Cast(); + if (join.join_type != JoinType::MARK || join.children.size() != 2) { + return nullptr; + } + for (auto &expr : op.expressions) { + auto column_ref = PlainColumn(*expr); + if (column_ref && column_ref->Binding().table_index == join.mark_index) { + return &join; + } + } + return nullptr; +} + +void CTEFilterPusher::GenerateSemiJoinFilters(LogicalOperator &op) { + if (cte_info_map.empty()) { + return; + } + // children first, so that a nested join has filtered its left side before the join above searches that side + for (auto &child : op.children) { + GenerateSemiJoinFilters(*child); + } + auto join = FilteringJoin(op); + if (!join) { + return; + } + // the left side is a reference of a materialized CTE whose other references are all filtered + optional_ptr ref_op = join->children[0].get(); + optional_ptr ref_filter; + if (ref_op->type == LogicalOperatorType::LOGICAL_FILTER && !ref_op->Cast().HasProjectionMap()) { + ref_filter = ref_op; + ref_op = ref_op->children[0].get(); + } + if (ref_op->type != LogicalOperatorType::LOGICAL_CTE_REF) { + return; + } + auto &cte_ref = ref_op->Cast(); + auto entry = cte_info_map.find(to_string(cte_ref.cte_index.index)); + if (entry == cte_info_map.end() || cte_ref.is_recurring || cte_ref.correlated_columns != 0) { + return; + } + auto &info = *entry->second; + if (info.references.size() != info.filters.size() + (ref_filter ? 0 : 1)) { + return; + } + + // the filters on the join keys that every right row passes + vector> right_filters; + for (auto &condition : join->conditions) { + if (!IsEquality(condition)) { + continue; + } + auto right_key = PlainColumn(condition.GetRHS()); + if (right_key && HasBinding(*join->children[1], right_key->Binding())) { + idx_t steps = 0; + GuaranteedColumnFilters(*join->children[1], *right_key, steps, right_filters); + } + } + if (right_filters.empty()) { + return; + } + + // a left row with a match passes what they imply for the left side + vector> filters; + for (auto &filter : right_filters) { + filters.push_back(*filter); + } + vector> left_filters; + FilterCombiner::GenerateJoinFilters(join->conditions, filters, JoinSide::LEFT, + [&](unique_ptr left_filter) { + bool exists = false; + if (ref_filter) { + for (auto &existing : ref_filter->expressions) { + exists = exists || existing->Equals(*left_filter); + } + } + for (auto &existing : left_filters) { + exists = exists || existing->Equals(*left_filter); + } + if (!exists) { + left_filters.push_back(std::move(left_filter)); + } + }); + if (left_filters.empty()) { + return; + } + if (ref_filter) { + for (auto &left_filter : left_filters) { + ref_filter->expressions.push_back(std::move(left_filter)); + } + return; + } + // The CTE is restricted by the disjunction of the filters of its references, which this filter usually repeats in + // part. As one flat conjunction it is a branch that the expression rewriter reduces: (A AND B AND C) OR A is A. + auto filter = make_uniq(); + if (left_filters.size() == 1) { + filter->expressions = std::move(left_filters); + } else { + auto conjunction = make_uniq(ExpressionType::CONJUNCTION_AND); + conjunction->GetChildrenMutable() = std::move(left_filters); + filter->expressions.push_back(std::move(conjunction)); + } + filter->children.push_back(std::move(join->children[0])); + info.filters.push_back(*filter); + info.all_cte_refs_are_filtered = true; + join->children[0] = std::move(filter); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/deliminator.cpp b/src/duckdb/src/optimizer/deliminator.cpp index a6375ce17..f506f22c3 100644 --- a/src/duckdb/src/optimizer/deliminator.cpp +++ b/src/duckdb/src/optimizer/deliminator.cpp @@ -293,7 +293,7 @@ bool Deliminator::RemoveInequalityJoinWithDelimGet(LogicalComparisonJoin &delim_ delim_conditions.size() != join_conditions.size()) { return false; } - NotNullExpressionAnalyzer nullability(context, root); + NotNullExpressionAnalyzer nullability(context, *root); // TODO: we cannot perform the optimization here because our pure inequality joins don't implement // JoinType::SINGLE yet, and JoinType::MARK is a special case @@ -438,42 +438,10 @@ void Deliminator::TrySwitchSingleToLeft(LogicalComparisonJoin &delim_join) { join_bindings.emplace_back(colref.Binding()); } - // Now try to find an aggr in the RHS such that the join_column_bindings is a superset of the groups - reference current_op = *delim_join.children[1]; - while (current_op.get().type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { - if (current_op.get().children.size() != 1) { - return; - } - - switch (current_op.get().type) { - case LogicalOperatorType::LOGICAL_PROJECTION: - FindAndReplaceBindings(join_bindings, current_op.get().expressions, current_op.get().GetColumnBindings()); - break; - case LogicalOperatorType::LOGICAL_FILTER: - break; // Doesn't change bindings - default: - return; - } - current_op = *current_op.get().children[0]; - } - - D_ASSERT(current_op.get().type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY); - const auto &aggr = current_op.get().Cast(); - if (!aggr.grouping_functions.empty()) { - return; - } - if (aggr.grouping_sets.size() > 1) { - // multiple grouping sets emit one row per set, so the groups do not determine a unique row + // Each LHS row finds at most one RHS row: the join cannot fail, and LEFT is equivalent + if (!LogicalAggregate::KeysAreUnique(*delim_join.children[1], std::move(join_bindings))) { return; } - - for (idx_t group_idx = 0; group_idx < aggr.groups.size(); group_idx++) { - if (std::find(join_bindings.begin(), join_bindings.end(), - ColumnBinding(aggr.group_index, ProjectionIndex(group_idx))) == join_bindings.end()) { - return; - } - } - delim_join.join_type = JoinType::LEFT; } diff --git a/src/duckdb/src/optimizer/distinctness.cpp b/src/duckdb/src/optimizer/distinctness.cpp new file mode 100644 index 000000000..cfaa50c69 --- /dev/null +++ b/src/duckdb/src/optimizer/distinctness.cpp @@ -0,0 +1,321 @@ +#include "duckdb/optimizer/distinctness.hpp" + +#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" +#include "duckdb/parser/constraints/not_null_constraint.hpp" +#include "duckdb/parser/constraints/unique_constraint.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_cast_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" + +namespace duckdb { + +static bool ForwardsChildUniqueSets(LogicalOperatorType type, DistinctnessPropagation propagation) { + switch (type) { + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_LIMIT: + case LogicalOperatorType::LOGICAL_ORDER_BY: + case LogicalOperatorType::LOGICAL_TOP_N: + case LogicalOperatorType::LOGICAL_WINDOW: + return true; + case LogicalOperatorType::LOGICAL_SAMPLE: + return propagation == DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS; + default: + return false; + } +} + +static optional GetInjectiveColumnBinding(const Expression &expression, + optional_ptr context) { + if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + return expression.Cast().Binding(); + } + if (!context || !BoundCastExpression::IsCast(expression)) { + return {}; + } + auto &cast = expression.Cast(); + auto source_type = BoundCastExpression::SourceType(cast); + auto &target_type = BoundCastExpression::TargetType(cast); + if (BoundCastExpression::IsTryCast(cast) || + CastFunctionSet::Get(*context).CanOverrideDefaultCast(source_type, target_type)) { + return {}; + } + // Successful strict integral casts do not merge distinct input values. + if (source_type != target_type && !(source_type.IsIntegral() && target_type.IsIntegral()) && + !BoundCastExpression::CastIsInvertibleForEquality(source_type, target_type)) { + return {}; + } + return GetInjectiveColumnBinding(BoundCastExpression::Child(cast), context); +} + +bool Distinctness::IsDistinctOn(LogicalOperator &op, const vector> &keys) { + column_binding_set_t bindings; + for (auto &key : keys) { + auto binding = GetInjectiveColumnBinding(*key, context); + if (binding) { + bindings.insert(*binding); + } + } + return IsDistinctOnProjectedKeys(op, bindings); +} + +bool Distinctness::IsDistinctOnProjectedKeys(LogicalOperator &op, const column_binding_set_t &keys) { + if (keys.empty()) { + return false; + } + if (IsDistinctOn(op, keys)) { + return true; + } + if (ForwardsChildUniqueSets(op.type, propagation)) { + return IsDistinctOnProjectedKeys(*op.children[0], keys); + } + if (op.type != LogicalOperatorType::LOGICAL_PROJECTION) { + return false; + } + auto &projection = op.Cast(); + column_binding_set_t child_keys; + for (auto expr_idx : ProjectionIndex::GetIndexes(projection.expressions.size())) { + if (!keys.count(ColumnBinding(projection.table_index, expr_idx))) { + continue; + } + auto binding = GetInjectiveColumnBinding(*projection.expressions[expr_idx], context); + if (binding) { + child_keys.insert(*binding); + } + } + return IsDistinctOnProjectedKeys(*projection.children[0], child_keys); +} + +bool Distinctness::IsDistinctOn(LogicalOperator &op, const column_binding_set_t &keys) { + if (keys.empty()) { + return false; + } + // a superset of a unique set is unique as well + for (auto &unique_set : GetUniqueSets(op)) { + bool covered = true; + for (auto &binding : unique_set) { + if (keys.find(binding) == keys.end()) { + covered = false; + break; + } + } + if (covered) { + return true; + } + } + return false; +} + +bool Distinctness::GetJoinEqualityKeys(const LogicalComparisonJoin &join, idx_t child_idx, column_binding_set_t &keys) { + keys.clear(); + for (auto &cond : join.conditions) { + // other conditions only filter the matches + if (!cond.IsComparison()) { + continue; + } + if (cond.GetComparisonType() != ExpressionType::COMPARE_EQUAL && + cond.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + continue; + } + auto &key = child_idx == 0 ? cond.GetLHS() : cond.GetRHS(); + if (key.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + // e.g. a cast: several values of the column can be equal to the same value of the other side + return false; + } + keys.insert(key.Cast().Binding()); + } + return !keys.empty(); +} + +bool Distinctness::IsDistinctOnJoinKeys(LogicalComparisonJoin &join, idx_t child_idx) { + column_binding_set_t keys; + if (!GetJoinEqualityKeys(join, child_idx, keys)) { + return false; + } + return IsDistinctOn(*join.children[child_idx], keys); +} + +vector Distinctness::ComputeJoinUniqueSets(LogicalComparisonJoin &join) { + vector result; + switch (join.join_type) { + case JoinType::SEMI: + case JoinType::ANTI: + case JoinType::MARK: + case JoinType::SINGLE: + // these emit every row of the left side at most once + return GetUniqueSets(*join.children[0]); + case JoinType::INNER: + // a row that is joined to a side that is distinct on its join keys finds at most one match + if (IsDistinctOnJoinKeys(join, 1)) { + result = GetUniqueSets(*join.children[0]); + } + if (IsDistinctOnJoinKeys(join, 0)) { + auto &right_sets = GetUniqueSets(*join.children[1]); + result.insert(result.end(), right_sets.begin(), right_sets.end()); + } + if (result.size() > MAX_UNIQUE_SETS) { + // this is the only place where the number of unique sets grows: bound it, so that a chain of key joins + // does not accumulate them. Dropping a unique set only loses a proof + result.resize(MAX_UNIQUE_SETS); + } + return result; + case JoinType::LEFT: + if (IsDistinctOnJoinKeys(join, 1)) { + result = GetUniqueSets(*join.children[0]); + } + return result; + default: + return result; + } +} + +const vector &Distinctness::GetUniqueSets(LogicalOperator &op) { + auto entry = unique_sets.find(op); + if (entry != unique_sets.end()) { + return entry->second; + } + // every operator is computed once: its children are looked up in the cache + return unique_sets.emplace(op, ComputeUniqueSets(op)).first->second; +} + +vector Distinctness::ComputeScanUniqueSets(LogicalGet &get) { + // the PRIMARY KEY / UNIQUE NOT NULL constraints of a scanned table, if all of their columns are scanned + vector result; + // Table-in/out functions need not preserve the multiplicity of their input keys. + auto table = get.GetTable(); + if (!table || !table->IsDuckTable() || !get.children.empty() || get.GetColumnIds().empty()) { + return result; + } + unordered_map column_bindings; + for (auto &binding : get.GetColumnBindings()) { + auto &column_index = get.GetColumnIndex(binding); + if (!column_index.HasPrimaryIndex() || column_index.HasChildren() || column_index.IsVirtualColumn()) { + continue; + } + column_bindings.emplace(column_index.GetPrimaryIndex(), binding); + } + auto &columns = table->GetColumns(); + auto &constraints = table->GetConstraints(); + unordered_set not_null_columns; + for (auto &constraint : constraints) { + if (constraint->type == ConstraintType::NOT_NULL) { + not_null_columns.insert(constraint->Cast().index.index); + } + } + for (auto &constraint : constraints) { + if (constraint->type != ConstraintType::UNIQUE) { + continue; + } + auto &unique = constraint->Cast(); + if (unique.IsDeferred()) { + continue; + } + auto &names = unique.GetColumnNames(); + if (!unique.HasIndex() && !std::all_of(names.begin(), names.end(), + [&](const Identifier &name) { return columns.ColumnExists(name); })) { + continue; + } + column_binding_set_t key; + bool usable = true; + for (auto &column : unique.GetLogicalIndexes(columns)) { + auto entry = column_bindings.find(column.index); + if (entry == column_bindings.end() || + (!unique.IsPrimaryKey() && not_null_columns.find(column.index) == not_null_columns.end())) { + usable = false; + break; + } + key.insert(entry->second); + } + if (usable && !key.empty()) { + result.push_back(std::move(key)); + } + } + return result; +} + +vector Distinctness::ComputeAggregateUniqueSets(LogicalAggregate &aggr) { + // the groups of the grouping set of an aggregate with a single grouping set + // TODO: use child FDs to simplify groupings. + vector result; + if (aggr.groups.empty() || aggr.grouping_sets.size() > 1 || !aggr.grouping_functions.empty()) { + return result; + } + column_binding_set_t key; + if (aggr.grouping_sets.empty()) { + for (auto group_idx : ProjectionIndex::GetIndexes(aggr.groups.size())) { + key.insert(ColumnBinding(aggr.group_index, group_idx)); + } + } else { + for (auto group_idx : aggr.grouping_sets[0]) { + if (group_idx.GetIndex() >= aggr.groups.size()) { + return result; + } + key.insert(ColumnBinding(aggr.group_index, group_idx)); + } + } + if (!key.empty()) { + result.push_back(std::move(key)); + } + return result; +} + +vector Distinctness::ComputeProjectionUniqueSets(LogicalProjection &projection) { + // cache one representative output binding per input binding + vector result; + auto &child_sets = GetUniqueSets(*projection.children[0]); + if (child_sets.empty()) { + return result; + } + column_binding_map_t forwarded; + for (auto expr_idx : ProjectionIndex::GetIndexes(projection.expressions.size())) { + auto binding = GetInjectiveColumnBinding(*projection.expressions[expr_idx], context); + if (binding) { + forwarded.emplace(*binding, ColumnBinding(projection.table_index, expr_idx)); + } + } + for (auto &child_set : child_sets) { + column_binding_set_t key; + bool complete = true; + for (auto &binding : child_set) { + auto entry = forwarded.find(binding); + if (entry == forwarded.end()) { + complete = false; + break; + } + key.insert(entry->second); + } + if (complete) { + result.push_back(std::move(key)); + } + } + return result; +} + +vector Distinctness::ComputeUniqueSets(LogicalOperator &op) { + if (ForwardsChildUniqueSets(op.type, propagation)) { + return GetUniqueSets(*op.children[0]); + } + switch (op.type) { + case LogicalOperatorType::LOGICAL_GET: + return ComputeScanUniqueSets(op.Cast()); + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + return ComputeAggregateUniqueSets(op.Cast()); + case LogicalOperatorType::LOGICAL_PROJECTION: + return ComputeProjectionUniqueSets(op.Cast()); + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + if (propagation != DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS) { + break; + } + return ComputeJoinUniqueSets(op.Cast()); + default: + break; + } + // we don't know if the operator preserves the unique sets of its children + return vector(); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp index 518e685c6..751459449 100644 --- a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp @@ -4,6 +4,7 @@ #include "duckdb/storage/statistics/node_statistics.hpp" #include "duckdb/storage/statistics/numeric_stats.hpp" #include "duckdb/optimizer/aggregate_rewrite_helper.hpp" +#include "duckdb/optimizer/expression_heuristics.hpp" #include "duckdb/optimizer/join_filter_pushdown_optimizer.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" @@ -11,6 +12,7 @@ #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_operator_expression.hpp" #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" @@ -117,33 +119,63 @@ static optional_idx GroupKeyIndex(LogicalAggregate &aggregate, idx_t key, const return index; } -static optional_ptr FindAggregate(LogicalOperator &op, idx_t key) { +struct AggregateKeyMatch { + reference aggregate; + vector group_indices; +}; + +//! Trace output positions to the complete grouping key. +static optional FindAggregate(LogicalOperator &op, vector keys) { if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { for (auto &expression : op.expressions) { if (expression->CanThrow() || expression->IsVolatile()) { - return nullptr; + return {}; } } - auto index = ReferenceIndex(*op.expressions[key], *op.children[0]); - return index.IsValid() ? FindAggregate(*op.children[0], index.GetIndex()) : nullptr; + for (auto &key : keys) { + if (key >= op.expressions.size()) { + return {}; + } + auto index = ReferenceIndex(*op.expressions[key], *op.children[0]); + if (!index.IsValid()) { + return {}; + } + key = index.GetIndex(); + } + return FindAggregate(*op.children[0], std::move(keys)); } - if (op.type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY || key != 0) { - return nullptr; + if (op.type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + return {}; } auto &aggregate = op.Cast(); - if (aggregate.preserve_input_order || aggregate.groups.size() != 1 || !HasSimpleGrouping(aggregate) || - !ReferenceIndex(*aggregate.groups[0], *aggregate.children[0]).IsValid()) { - return nullptr; + if (aggregate.preserve_input_order || aggregate.groups.size() != keys.size() || !HasSimpleGrouping(aggregate)) { + return {}; + } + vector matched(keys.size(), false); + for (auto key : keys) { + if (key >= keys.size() || matched[key] || + !ReferenceIndex(*aggregate.groups[key], *aggregate.children[0]).IsValid()) { + return {}; + } + matched[key] = true; } for (auto &expression : aggregate.expressions) { bool supported = true; ExpressionIterator::EnumerateChildren(*expression, [&](const Expression &child) { supported &= IsWorkReference(child); }); if (!supported) { - return nullptr; + return {}; } } - return LogicalSubtreeIsRepeatable(aggregate) ? &aggregate : nullptr; + if (!LogicalSubtreeIsRepeatable(aggregate)) { + return {}; + } + return AggregateKeyMatch {aggregate, std::move(keys)}; +} + +static optional_ptr FindAggregate(LogicalOperator &op, idx_t key) { + auto match = FindAggregate(op, vector {key}); + return match ? &match->aggregate.get() : nullptr; } //! An upper bound from the actual closed input, not a cardinality estimate. @@ -270,6 +302,12 @@ static bool CopyExactFixedKeys(LogicalOperator &op, idx_t key, const LogicalType enum class RestrictionAction { KEEP, REPLACE, REMOVE }; +//! The chosen action and the work saved if the restriction is removed. +struct RestrictionDecision { + RestrictionAction action = RestrictionAction::KEEP; + double removal_savings = 0; +}; + static unique_ptr CreateKeyDomain(Optimizer &optimizer, unique_ptr input, unique_ptr key) { auto domain = make_uniq(optimizer.binder.GenerateTableIndex(), @@ -391,7 +429,7 @@ class DomainAggregateBounds { children.push_back(stats ? stats->Copy() : BaseStatistics::CreateUnknown(child->GetReturnType())); } NodeStatistics rows(maximum.GetIndex(), maximum.GetIndex()); - AggregateStatisticsInput statistics(copy.BindInfo(), children, &rows); + AggregateStatisticsInput statistics(copy.BindInfoMutable(), children, &rows); return copy.Function().GetCallbacks().GetStatisticsCallback()(context, copy, statistics); } @@ -474,8 +512,18 @@ class DomainRestriction { public: DomainRestriction(ClientContext &context, const vector> &scopes, LogicalAggregate &aggregate_p, ExpressionType consumer_comparison_p) - : aggregate(aggregate_p), consumer_comparison(consumer_comparison_p), bounds(context, scopes) { - join = Find(*aggregate.children[0], *aggregate.groups[0]); + : DomainRestriction(context, scopes, aggregate_p, vector {consumer_comparison_p}) { + } + + DomainRestriction(ClientContext &context, const vector> &scopes, + LogicalAggregate &aggregate_p, const vector &comparisons) + : aggregate(aggregate_p), consumer_comparisons(comparisons), bounds(context, scopes) { + vector> keys; + for (auto &group : aggregate.groups) { + keys.push_back(*group); + } + D_ASSERT(keys.size() == comparisons.size()); + join = Find(*aggregate.children[0], keys); } public: @@ -485,46 +533,77 @@ class DomainRestriction { bool HasSimpleProjections() const; bool CanRemove() const; - bool FiltersNullKeys() const { - return join->conditions[0].GetComparisonType() == ExpressionType::COMPARE_EQUAL && - consumer_comparison == ExpressionType::COMPARE_NOT_DISTINCT_FROM; + const JoinCondition &GetCondition(idx_t key) const { + return join->conditions[conditions[key]]; + } + bool FiltersNullKey(idx_t key) const { + return GetCondition(key).GetComparisonType() == ExpressionType::COMPARE_EQUAL && + consumer_comparisons[key] == ExpressionType::COMPARE_NOT_DISTINCT_FROM; + } + idx_t NullFilterCount() const { + idx_t count = 0; + for (idx_t key = 0; key < conditions.size(); key++) { + count += FiltersNullKey(key); + } + return count; } void Apply(unique_ptr &domain, RestrictionAction action); + void Remove(); private: - optional_ptr Find(LogicalOperator &input, const Expression &key); + optional_ptr Find(LogicalOperator &input, const vector> &keys); private: LogicalAggregate &aggregate; - ExpressionType consumer_comparison; + vector consumer_comparisons; + vector conditions; DomainAggregateBounds bounds; optional_ptr join; vector> projections; }; -optional_ptr DomainRestriction::Find(LogicalOperator &input, const Expression &key) { +optional_ptr DomainRestriction::Find(LogicalOperator &input, + const vector> &keys) { if (input.type == LogicalOperatorType::LOGICAL_PROJECTION) { - auto index = ReferenceIndex(key, input); - if (!index.IsValid()) { - return nullptr; + vector> projected; + for (auto &key : keys) { + auto index = ReferenceIndex(key, input); + if (!index.IsValid()) { + return nullptr; + } + projected.push_back(*input.expressions[index.GetIndex()]); } projections.push_back(input.Cast()); - return Find(*input.children[0], *input.expressions[index.GetIndex()]); + return Find(*input.children[0], projected); } if (input.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { return nullptr; } auto &join = input.Cast(); - if (join.join_type != JoinType::SEMI || join.conditions.size() != 1 || !join.expressions.empty() || - !join.duplicate_eliminated_columns.empty() || join.filter_pushdown || !join.conditions[0].IsComparison()) { + if (join.join_type != JoinType::SEMI || join.conditions.size() != keys.size() || !join.expressions.empty() || + !join.duplicate_eliminated_columns.empty() || join.filter_pushdown) { return nullptr; } - auto &condition = join.conditions[0]; - if ((condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL && - condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) || - !key.Equals(condition.GetLHS()) || !ReferenceIndex(key, *join.children[0]).IsValid() || - !ReferenceIndex(condition.GetRHS(), *join.children[1]).IsValid()) { - return nullptr; + vector matched(keys.size(), false); + for (auto &key : keys) { + optional_idx found; + for (idx_t index = 0; index < join.conditions.size(); index++) { + auto &condition = join.conditions[index]; + if (matched[index] || !condition.IsComparison() || + (condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL && + condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) || + !key.get().Equals(condition.GetLHS()) || !ReferenceIndex(key, *join.children[0]).IsValid() || + !ReferenceIndex(condition.GetRHS(), *join.children[1]).IsValid()) { + continue; + } + found = index; + break; + } + if (!found.IsValid()) { + return nullptr; + } + matched[found.GetIndex()] = true; + conditions.push_back(found.GetIndex()); } return join; } @@ -551,29 +630,75 @@ void DomainRestriction::Apply(unique_ptr &domain, RestrictionA auto &restriction = *join; auto &condition = restriction.conditions[0]; if (action == RestrictionAction::REPLACE) { + D_ASSERT(conditions.size() == 1 && domain); condition.RightReference() = DomainKey(*domain); restriction.children[1] = std::move(domain); } else { D_ASSERT(action == RestrictionAction::REMOVE); - auto &slot = projections.empty() ? aggregate.children[0] : projections.back().get().children[0]; - D_ASSERT(slot.get() == &restriction); - auto input = std::move(restriction.children[0]); - if (FiltersNullKeys()) { - auto predicate = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, - LogicalType::BOOLEAN, condition.GetLHS().Copy()); - auto filter = make_uniq(std::move(predicate)); - filter->children.push_back(std::move(input)); - input = std::move(filter); + Remove(); + } +} + +void DomainRestriction::Remove() { + auto &restriction = *join; + auto &slot = projections.empty() ? aggregate.children[0] : projections.back().get().children[0]; + D_ASSERT(slot.get() == &restriction); + auto input = std::move(restriction.children[0]); + auto filter = make_uniq(); + for (idx_t key = 0; key < conditions.size(); key++) { + if (FiltersNullKey(key)) { + filter->expressions.push_back(make_uniq( + ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN, GetCondition(key).GetLHS().Copy())); } - slot = LogicalJoin::PromoteJoinSide(std::move(input), std::move(restriction.left_projection_map)); - join = nullptr; } + if (!filter->expressions.empty()) { + filter->children.push_back(std::move(input)); + input = std::move(filter); + } + slot = LogicalJoin::PromoteJoinSide(std::move(input), std::move(restriction.left_projection_map)); + join = nullptr; +} + +static double EstimateFixedDomainWork(double key_rows, double distinct_key_rows) { + return 2 * key_rows + distinct_key_rows + 3; } -//! Compare alternatives for one aggregate using the same statistics source and domain-production costs. +static double EstimateKeyProductionWork(RelationStatsExtractor &extractor, LogicalOperator &input) { + if (input.type == LogicalOperatorType::LOGICAL_PROJECTION) { + return EstimateKeyProductionWork(extractor, *input.children[0]); + } + auto rows = extractor.Extract(input); + if (!rows) { + return 0; + } + if (input.type == LogicalOperatorType::LOGICAL_CTE_REF) { + // This reader disappears; its shared definition may still be used elsewhere. + return static_cast(rows->cardinality) * static_cast(input.GetColumnBindings().size()); + } + if (input.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + auto child_rows = extractor.Extract(*input.children[0]); + if (child_rows) { + return EstimateFixedDomainWork(static_cast(child_rows->cardinality), + static_cast(rows->cardinality)) + + EstimateKeyProductionWork(extractor, *input.children[0]); + } + } + return 0; +} + +struct ReleasedDomainWork { + optional_ptr production; + optional_ptr source; +}; + +//! Compare alternatives using the same statistics source and domain-production costs. //! Statistics are extracted for each decision, never retained across a plan rewrite. class DomainCostModel { public: + DomainCostModel(RelationStatsExtractor &extractor_p, LogicalAggregate &aggregate_p) + : extractor(extractor_p), aggregate(aggregate_p) { + } + DomainCostModel(RelationStatsExtractor &extractor_p, LogicalAggregate &aggregate_p, double key_input_rows_p, double source_read_write_work_p) : extractor(extractor_p), aggregate(aggregate_p), key_input_rows(key_input_rows_p), @@ -582,24 +707,54 @@ class DomainCostModel { public: bool IsProfitable(LogicalComparisonJoin &restriction, LogicalOperator &domain); - RestrictionAction ChooseRestrictionAction(const DomainRestriction &existing, LogicalAggregate &domain, - bool keys_may_expand = false); + //! Keeping and safe removal are always considered; a supplied domain also permits scalar replacement. + RestrictionDecision ChooseRestrictionAction(const DomainRestriction &existing, + optional_ptr domain, bool keys_may_expand = false); + //! Price only producers that the caller has proven will stop. + static double EstimateReleasedWork(RelationStatsExtractor &extractor, ReleasedDomainWork released); + void SetReleasedWork(const ReleasedDomainWork &released); + static bool IsRecoveryProfitable(double outer_rows, const RelationStats &domain, double expression_work, + idx_t single_row_joins, double released_work, double restriction_savings); private: static bool IsCheaper(double candidate, double original); static double EstimateSemiJoinWork(double input_rows, double output_rows, double key_rows); + static double EstimateRecoveryDomainRows(const RelationStats &domain); + static double EstimateRecoveryRowWork(double expression_work, idx_t single_row_joins); double EstimateAggregateWork(double input_rows, double group_count) const; - double EstimateAggregateWork(const RelationStats &input, ColumnBinding group_binding) const; - static double EstimateFixedDomainWork(double key_rows, double distinct_key_rows); - double EstimateKeyProductionWork(LogicalOperator &input); + double EstimateAggregateWork(const RelationStats &input, const vector &group_bindings) const; + optional EstimateRestriction(const DomainRestriction &existing, + const RelationStats &input, const RelationStats &keys); private: RelationStatsExtractor &extractor; LogicalAggregate &aggregate; - double key_input_rows; - double source_read_write_work; + double key_input_rows = 0; + double source_read_write_work = 0; + double released_work = 0; }; +double DomainCostModel::EstimateReleasedWork(RelationStatsExtractor &extractor, ReleasedDomainWork released) { + // The unit of this model is one row through a hash table. Producing the key domain and materializing its source + // are counted per value by the formulas, but measured they cost about one such unit per source row each (0.25 to + // 0.46 of the formula for sources of 3 columns and 1 column), so the released work is scaled down. + static constexpr double RELEASED_WORK_SCALE = 0.3; + auto production_work = released.production ? EstimateKeyProductionWork(extractor, *released.production) : 0; + double source_values = 0; + if (released.source) { + auto stats = extractor.Extract(*released.source); + if (stats) { + source_values = static_cast(stats->cardinality) * + static_cast(released.source->GetColumnBindings().size()); + } + } + return RELEASED_WORK_SCALE * (production_work + source_values); +} + +void DomainCostModel::SetReleasedWork(const ReleasedDomainWork &released) { + released_work = EstimateReleasedWork(extractor, released); +} + bool DomainCostModel::IsCheaper(double candidate, double original) { auto tolerance = 32 * std::numeric_limits::epsilon() * MaxValue(original, candidate); return std::isfinite(original) && std::isfinite(candidate) && original - candidate > tolerance; @@ -614,40 +769,49 @@ double DomainCostModel::EstimateSemiJoinWork(double input_rows, double output_ro return key_rows + input_rows + output_rows; } -double DomainCostModel::EstimateFixedDomainWork(double key_rows, double distinct_key_rows) { - return 2 * key_rows + distinct_key_rows + 3; +double DomainCostModel::EstimateRecoveryDomainRows(const RelationStats &domain) { + idx_t distinct_count = 1; + for (auto &column : domain.columns) { + // Key independence and range-based estimates can hide repeated tuples. + if (column.total_domain.source == DistinctCountSource::HLL || + column.total_domain.source == DistinctCountSource::EXACT) { + distinct_count = MaxValue(distinct_count, column.current_domain.distinct_count); + } + } + return static_cast(MinValue(distinct_count, domain.cardinality)); } -double DomainCostModel::EstimateKeyProductionWork(LogicalOperator &input) { - if (input.type == LogicalOperatorType::LOGICAL_PROJECTION) { - return EstimateKeyProductionWork(*input.children[0]); - } - auto rows = extractor.Extract(input); - if (!rows) { - return 0; - } - if (input.type == LogicalOperatorType::LOGICAL_CTE_REF) { - // This reader disappears; its shared definition may still be used elsewhere. - return static_cast(rows->cardinality) * static_cast(input.GetColumnBindings().size()); - } - if (input.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { - auto child_rows = extractor.Extract(*input.children[0]); - if (child_rows) { - return EstimateFixedDomainWork(static_cast(child_rows->cardinality), - static_cast(rows->cardinality)) + - EstimateKeyProductionWork(*input.children[0]); - } +double DomainCostModel::EstimateRecoveryRowWork(double expression_work, idx_t single_row_joins) { + // Scalar-expression scores and conditionless row processing are cheaper than hash-table row work. + static constexpr double EXPRESSION_WORK_PER_HASH_ROW = 64; + static constexpr double SINGLE_ROW_JOIN_WORK = 0.3; + return expression_work / EXPRESSION_WORK_PER_HASH_ROW + + static_cast(single_row_joins) * SINGLE_ROW_JOIN_WORK; +} + +bool DomainCostModel::IsRecoveryProfitable(double outer_rows, const RelationStats &domain, double expression_work, + idx_t single_row_joins, double released_work, double restriction_savings) { + auto domain_rows = EstimateRecoveryDomainRows(domain); + if (outer_rows <= domain_rows) { + return true; } - return 0; + // Cancelling unchanged joins leaves one domain-sized build, probe and output. + auto saved_work = EstimateSemiJoinWork(domain_rows, domain_rows, domain_rows) + released_work + restriction_savings; + auto added_work = (outer_rows - domain_rows) * EstimateRecoveryRowWork(expression_work, single_row_joins); + return std::isfinite(saved_work) && std::isfinite(added_work) && added_work <= saved_work; } -double DomainCostModel::EstimateAggregateWork(const RelationStats &input, ColumnBinding group_binding) const { - auto column = input.GetColumnStats(group_binding); - if (!column) { - return std::numeric_limits::quiet_NaN(); +double DomainCostModel::EstimateAggregateWork(const RelationStats &input, + const vector &group_bindings) const { + vector domains; + for (auto &binding : group_bindings) { + auto column = input.GetColumnStats(binding); + if (!column) { + return std::numeric_limits::quiet_NaN(); + } + domains.push_back(column->current_domain); } - auto group_count = - RelationStatisticsHelper::EstimateDistinctCardinality({column->current_domain}, input.cardinality); + auto group_count = RelationStatisticsHelper::EstimateDistinctCardinality(domains, input.cardinality); return EstimateAggregateWork(static_cast(input.cardinality), static_cast(group_count)); } @@ -662,6 +826,28 @@ static optional EstimateRestrictionStats(LogicalComparisonJoin &r return restricted; } +optional DomainCostModel::EstimateRestriction(const DomainRestriction &existing, + const RelationStats &input, + const RelationStats &keys) { + auto &restriction = *existing.GetJoin(); + if (aggregate.groups.size() == 1) { + auto restricted = EstimateRestrictionStats(restriction, input, keys); + if (!restricted) { + return {}; + } + auto binding = existing.GetCondition(0).GetLHS().Cast().Binding(); + auto column = restricted->GetColumnStats(binding); + if (!column) { + return {}; + } + auto groups = + RelationStatisticsHelper::EstimateDistinctCardinality({column->current_domain}, restricted->cardinality); + return TupleDomainRestrictionEstimate {static_cast(restricted->cardinality), + static_cast(groups)}; + } + return RelationStatisticsHelper::EstimateTupleDomainRestriction(restriction, input, keys, extractor); +} + bool DomainCostModel::IsProfitable(LogicalComparisonJoin &restriction, LogicalOperator &domain) { auto input = extractor.Extract(*aggregate.children[0]); auto groups = extractor.Extract(aggregate); @@ -693,41 +879,31 @@ bool DomainCostModel::IsProfitable(LogicalComparisonJoin &restriction, LogicalOp return IsCheaper(candidate, canonical); } -RestrictionAction DomainCostModel::ChooseRestrictionAction(const DomainRestriction &existing, LogicalAggregate &domain, - bool keys_may_expand) { +RestrictionDecision DomainCostModel::ChooseRestrictionAction(const DomainRestriction &existing, + optional_ptr domain, + bool keys_may_expand) { if (keys_may_expand && !existing.CanRemove()) { - return RestrictionAction::KEEP; + return {}; } auto &restriction = *existing.GetJoin(); - auto &condition = restriction.conditions[0]; auto input = extractor.Extract(*restriction.children[0]); auto old_keys = extractor.Extract(*restriction.children[1]); - auto new_keys = extractor.Extract(domain); - if (!input || !old_keys || !new_keys) { - return RestrictionAction::KEEP; + if (!input || !old_keys) { + return {}; } - LogicalComparisonJoin replacement(JoinType::SEMI); - replacement.conditions.emplace_back(condition.GetLHS().Copy(), DomainKey(domain), condition.GetComparisonType()); - auto restricted = EstimateRestrictionStats(replacement, *input, *new_keys); - auto old_input = EstimateRestrictionStats(restriction, *input, *old_keys); + auto old_input = EstimateRestriction(existing, *input, *old_keys); auto old_key_rows = static_cast(old_keys->cardinality); - auto distinct_key_rows = static_cast(new_keys->cardinality); - auto new_producer_work = EstimateFixedDomainWork(key_input_rows, distinct_key_rows) + source_read_write_work; - auto new_key_work = distinct_key_rows + new_producer_work; - auto old_producer_work = EstimateKeyProductionWork(*restriction.children[1]); - if (!old_input) { - // Key containment bounds aggregation/probe work; cheaper key production/build can justify replacement. - // Missing old selectivity cannot justify removal. - return !keys_may_expand && IsCheaper(new_key_work, old_key_rows + old_producer_work) - ? RestrictionAction::REPLACE - : RestrictionAction::KEEP; - } - // The projections preserve row counts and directly alias this grouping key. - auto group_binding = condition.GetLHS().Cast().Binding(); + auto old_producer_work = EstimateKeyProductionWork(extractor, *restriction.children[1]); + vector group_bindings; + for (idx_t key = 0; key < aggregate.groups.size(); key++) { + group_bindings.push_back(existing.GetCondition(key).GetLHS().Cast().Binding()); + } auto input_rows = static_cast(input->cardinality); - auto old_input_rows = static_cast(old_input->cardinality); - auto best_work = EstimateAggregateWork(*old_input, group_binding) + - EstimateSemiJoinWork(input_rows, old_input_rows, old_key_rows) + old_producer_work; + auto best_work = old_input ? EstimateAggregateWork(old_input->rows, old_input->groups) + + EstimateSemiJoinWork(input_rows, old_input->rows, old_key_rows) + + old_producer_work + released_work + : std::numeric_limits::quiet_NaN(); + auto original_work = best_work; auto action = RestrictionAction::KEEP; auto consider = [&](double work, RestrictionAction alternative) { if (IsCheaper(work, best_work)) { @@ -735,21 +911,44 @@ RestrictionAction DomainCostModel::ChooseRestrictionAction(const DomainRestricti action = alternative; } }; - if (restricted) { - consider(EstimateAggregateWork(*restricted, group_binding) + - EstimateSemiJoinWork(input_rows, static_cast(restricted->cardinality), distinct_key_rows) + - new_producer_work, - RestrictionAction::REPLACE); - } else if (!keys_may_expand) { - // Containment bounds the new aggregation/probe work by the old work; compare only the changed key costs. - consider(best_work - old_key_rows - old_producer_work + new_key_work, RestrictionAction::REPLACE); - } - if (keys_may_expand || existing.CanRemove()) { - // Charge the NULL filter without taking credit for rows it removes. - consider(EstimateAggregateWork(*input, group_binding) + (existing.FiltersNullKeys() ? input_rows : 0), + if (domain) { + D_ASSERT(aggregate.groups.size() == 1); + auto new_keys = extractor.Extract(*domain); + if (new_keys) { + auto &condition = existing.GetCondition(0); + LogicalComparisonJoin replacement(JoinType::SEMI); + replacement.conditions.emplace_back(condition.GetLHS().Copy(), DomainKey(*domain), + condition.GetComparisonType()); + auto restricted = EstimateRestrictionStats(replacement, *input, *new_keys); + auto distinct_key_rows = static_cast(new_keys->cardinality); + auto new_producer_work = + EstimateFixedDomainWork(key_input_rows, distinct_key_rows) + source_read_write_work; + auto new_key_work = distinct_key_rows + new_producer_work; + if (!old_input) { + // Containment can justify cheaper key production, but missing selectivity cannot justify removal. + if (!keys_may_expand && IsCheaper(new_key_work, old_key_rows + old_producer_work)) { + return {RestrictionAction::REPLACE, 0}; + } + return {}; + } + if (restricted) { + consider(EstimateAggregateWork(*restricted, group_bindings) + + EstimateSemiJoinWork(input_rows, static_cast(restricted->cardinality), + distinct_key_rows) + + new_producer_work, + RestrictionAction::REPLACE); + } else if (!keys_may_expand) { + consider(best_work - old_key_rows - old_producer_work + new_key_work, RestrictionAction::REPLACE); + } + } + } + if (old_input && (keys_may_expand || existing.CanRemove())) { + // Charge each required NULL filter without taking credit for rows it removes. + consider(EstimateAggregateWork(*input, group_bindings) + + static_cast(existing.NullFilterCount()) * input_rows, RestrictionAction::REMOVE); } - return action; + return {action, action == RestrictionAction::REMOVE ? original_work - best_work : 0}; } static bool HasSharedSource(LogicalOperator &op) { @@ -801,7 +1000,7 @@ static bool TryOptimizeRestriction(Optimizer &optimizer, LogicalAggregate &aggre } RelationStatsExtractor extractor(optimizer.context); DomainCostModel costs(extractor, aggregate, static_cast(fixed.expressions.size()), 0); - auto action = costs.ChooseRestrictionAction(existing, *domain); + auto action = costs.ChooseRestrictionAction(existing, *domain).action; if (action == RestrictionAction::KEEP) { return false; } @@ -879,19 +1078,32 @@ static bool CanChangeRuntimeKeyReaders(LogicalOperator &op, const vector(); - auto owner = FindVisibleOwner(cte.cte_index, cte_scopes); - if (!owner || cte.is_recurring || cte.correlated_columns) { + if (cte.is_recurring || cte.correlated_columns) { return false; } - auto entry = checked_owners.emplace(cte.cte_index, false); - if (!entry.second) { - return entry.first->second; + auto checked = checked_owners.find(cte.cte_index); + if (checked != checked_owners.end()) { + return checked->second; } + auto owner = FindVisibleOwner(cte.cte_index, cte_scopes); + if (!owner) { + return false; + } + checked_owners.emplace(cte.cte_index, false); // Reader changes can expose or prevent producer filters and alter volatile payload evaluation. auto repeatable = CanChangeRuntimeKeyReaders(*owner->children[0], cte_scopes, checked_owners); checked_owners[cte.cte_index] = repeatable; return repeatable; } + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + // A materialized CTE inside the subtree is read by the subtree only: its definition is checked here, once, + // for all of its references. + if (!CanChangeRuntimeKeyReaders(*op.children[0], cte_scopes, checked_owners)) { + return false; + } + checked_owners[op.Cast().table_index] = true; + return CanChangeRuntimeKeyReaders(*op.children[1], cte_scopes, checked_owners); + } for (auto &child : op.children) { if (!CanChangeRuntimeKeyReaders(*child, cte_scopes, checked_owners)) { return false; @@ -924,87 +1136,107 @@ static bool TryGetRuntimeDomainSource(LogicalOperator &demand, idx_t demand_inde return true; } -static void TraceSharedKeys(LogicalOperator &op, idx_t key, const LogicalType &type, +using SharedKeyTuples = unordered_map>; + +static void TraceSharedKeys(LogicalOperator &op, vector keys, const vector &types, const vector> &cte_scopes, bool allow_filters, - column_binding_set_t &keys) { + SharedKeyTuples &tuples) { optional_ptr current = op; - auto binding = op.GetColumnBindings()[key]; while (true) { - BoundColumnRefExpression reference(type, binding); - auto index = ReferenceIndex(reference, *current); - if (!index.IsValid()) { - return; - } - switch (current->type) { - case LogicalOperatorType::LOGICAL_PROJECTION: { - auto &expression = *current->expressions[index.GetIndex()]; - if (!ReferenceIndex(expression, *current->children[0], type).IsValid()) { + auto bindings = current->GetColumnBindings(); + vector child_keys; + for (idx_t key = 0; key < keys.size(); key++) { + if (keys[key] >= bindings.size()) { return; } - binding = expression.Cast().Binding(); - break; - } - case LogicalOperatorType::LOGICAL_FILTER: - if (!allow_filters) { + optional_idx index; + switch (current->type) { + case LogicalOperatorType::LOGICAL_PROJECTION: + index = ReferenceIndex(*current->expressions[keys[key]], *current->children[0], types[key]); + break; + case LogicalOperatorType::LOGICAL_FILTER: { + if (!allow_filters) { + return; + } + BoundColumnRefExpression reference(types[key], bindings[keys[key]]); + index = ReferenceIndex(reference, *current->children[0]); + break; + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + index = GroupKeyIndex(current->Cast(), keys[key], types[key]); + break; + case LogicalOperatorType::LOGICAL_CTE_REF: { + auto &cte = current->Cast(); + if (keys[key] >= cte.chunk_types.size() || + !types[key].EqualsIncludingCollation(cte.chunk_types[keys[key]])) { + return; + } + index = keys[key]; + break; + } + default: return; } - break; - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { - auto &aggregate = current->Cast(); - if (!GroupKeyIndex(aggregate, index.GetIndex(), type).IsValid()) { + if (!index.IsValid()) { return; } - auto &expression = *aggregate.groups[index.GetIndex()]; - binding = expression.Cast().Binding(); - break; + child_keys.push_back(index.GetIndex()); } - case LogicalOperatorType::LOGICAL_CTE_REF: { + if (current->type == LogicalOperatorType::LOGICAL_CTE_REF) { auto &cte = current->Cast(); auto owner = FindVisibleOwner(cte.cte_index, cte_scopes); if (!owner || cte.is_recurring || cte.correlated_columns || - !keys.emplace(cte.cte_index, ProjectionIndex(index.GetIndex())).second) { + !tuples.emplace(cte.cte_index, child_keys).second) { return; } current = *owner->children[0]; - binding = current->GetColumnBindings()[index.GetIndex()]; - continue; - } - default: - return; + } else { + current = *current->children[0]; } - current = *current->children[0]; + keys = std::move(child_keys); } } -static RestrictionAction TryOptimizeRuntimeRestriction(ClientContext &context, DomainCostModel &costs, - LogicalAggregate &aggregate, LogicalOperator &demand, - idx_t demand_index, unique_ptr &domain, - ExpressionType consumer_comparison, - const vector> &cte_scopes, - bool keys_may_expand = false) { - DomainRestriction existing(context, cte_scopes, aggregate, consumer_comparison); +static bool RuntimeRestrictionContainsDemand(const DomainRestriction &existing, LogicalOperator &demand, + const vector &demand_indices, + const vector> &cte_scopes) { auto restriction = existing.GetJoin(); if (!restriction || !existing.HasSimpleProjections()) { - return RestrictionAction::KEEP; + return false; } unordered_map checked_owners; if (!CanChangeRuntimeKeyReaders(*restriction->children[1], cte_scopes, checked_owners)) { - return RestrictionAction::KEEP; + return false; } - auto &condition = restriction->conditions[0]; - auto key = ReferenceIndex(condition.GetRHS(), *restriction->children[1]).GetIndex(); - column_binding_set_t demanded_keys, original_keys; - TraceSharedKeys(demand, demand_index, condition.GetRHS().GetReturnType(), cte_scopes, true, demanded_keys); - TraceSharedKeys(*restriction->children[1], key, condition.GetRHS().GetReturnType(), cte_scopes, false, - original_keys); + vector keys; + vector types; + for (idx_t key = 0; key < demand_indices.size(); key++) { + auto &condition = existing.GetCondition(key); + keys.push_back(ReferenceIndex(condition.GetRHS(), *restriction->children[1]).GetIndex()); + types.push_back(condition.GetRHS().GetReturnType()); + } + SharedKeyTuples demanded_keys, original_keys; + TraceSharedKeys(demand, demand_indices, types, cte_scopes, true, demanded_keys); + TraceSharedKeys(*restriction->children[1], std::move(keys), types, cte_scopes, false, original_keys); bool contains_demand = false; - for (auto &binding : original_keys) { - contains_demand |= demanded_keys.count(binding) != 0; + for (auto &entry : original_keys) { + auto found = demanded_keys.find(entry.first); + contains_demand |= found != demanded_keys.end() && found->second == entry.second; } - if (!contains_demand) { + return contains_demand; +} + +static RestrictionAction TryOptimizeRuntimeRestriction(ClientContext &context, DomainCostModel &costs, + LogicalAggregate &aggregate, LogicalOperator &demand, + idx_t demand_index, unique_ptr &domain, + ExpressionType consumer_comparison, + const vector> &cte_scopes, + bool keys_may_expand = false) { + DomainRestriction existing(context, cte_scopes, aggregate, consumer_comparison); + if (!RuntimeRestrictionContainsDemand(existing, demand, {demand_index}, cte_scopes)) { return RestrictionAction::KEEP; } - auto action = costs.ChooseRestrictionAction(existing, *domain, keys_may_expand); + auto action = costs.ChooseRestrictionAction(existing, domain.get(), keys_may_expand).action; if (action != RestrictionAction::KEEP) { existing.Apply(domain, action); } @@ -1086,6 +1318,357 @@ static void FindScanKeySource(const unique_ptr &input, idx_t ke } } +//! A join whose RHS recovers the keys without a group of a correlated aggregate: a LEFT join of the +//! duplicate-eliminated keys of the join's own LHS against the grouped aggregate (FindOuterDomainJoin). +struct OuterDomainJoin { + //! The number of operators between the join and the LEFT join against the key domain + idx_t chain_length = 0; + //! The LEFT join against the key domain + optional_ptr domain_join; + //! Per key: the binding of the domain column and the binding of the LHS column it duplicates + vector> keys; + //! Demand indices and comparisons in aggregate grouping-key order + vector demand_indices; + vector comparisons; + //! The materialized CTE both the LHS and the key domain read + TableIndex source; + //! The aggregate, when the restriction decision can handle the operators above it + optional_ptr aggregate; +}; + +//! The (CTE, column) an output column reads from a materialized CTE through plain projections. With `distinct` the +//! column must pass exactly one duplicate elimination of `group_count` groups (inline or as a visible CTE); `group` +//! is the group of that duplicate elimination the column reads. +static bool TraceSourceColumn(LogicalOperator &op, idx_t column, + const vector> &cte_scopes, bool distinct, + idx_t group_count, TableIndex &source, idx_t &source_column, idx_t &group) { + reference current = op; + bool seen_distinct = false; + while (true) { + auto &node = current.get(); + switch (node.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + if (column >= node.expressions.size()) { + return false; + } + auto index = ReferenceIndex(*node.expressions[column], *node.children[0]); + if (!index.IsValid()) { + return false; + } + column = index.GetIndex(); + current = *node.children[0]; + break; + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &aggregate = node.Cast(); + if (!distinct || seen_distinct || !aggregate.expressions.empty() || + aggregate.groups.size() != group_count) { + return false; + } + auto index = GroupKeyIndex(aggregate, column); + if (!index.IsValid()) { + return false; + } + group = column; + column = index.GetIndex(); + seen_distinct = true; + current = *node.children[0]; + break; + } + case LogicalOperatorType::LOGICAL_CTE_REF: { + auto &reference = node.Cast(); + if (reference.is_recurring || reference.correlated_columns) { + return false; + } + if (distinct == seen_distinct) { + source = reference.cte_index; + source_column = column; + return true; + } + auto owner = FindVisibleOwner(reference.cte_index, cte_scopes); + if (!owner) { + return false; + } + current = *owner->children[0]; + break; + } + default: + return false; + } + } +} + +//! `depends` caches, for one walk, whether the definition of a visible CTE reads the source: every reference of such a +//! CTE counts, but its definition is walked once. +static idx_t CountSourceReaders(LogicalOperator &op, TableIndex source, + const vector> &cte_scopes, + unordered_map &depends) { + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &reference = op.Cast(); + if (reference.cte_index == source) { + return 1; + } + auto known = depends.find(reference.cte_index); + if (known != depends.end()) { + return known->second ? 1 : 0; + } + // The owner is an ancestor of `op`: its definition cannot contain `op`. + auto owner = FindVisibleOwner(reference.cte_index, cte_scopes); + bool reads_source = owner && CountSourceReaders(*owner->children[0], source, cte_scopes, depends) > 0; + depends[reference.cte_index] = reads_source; + return reads_source ? 1 : 0; + } + idx_t count = 0; + for (auto &child : op.children) { + count += CountSourceReaders(*child, source, cte_scopes, depends); + } + return count; +} + +//! The number of references below `op` that read the materialized CTE `source`, directly or through a visible CTE +//! whose definition does. +static idx_t CountSourceReaders(LogicalOperator &op, TableIndex source, + const vector> &cte_scopes) { + unordered_map depends; + return CountSourceReaders(op, source, cte_scopes, depends); +} + +//! An aggregate without groups below plain projections. +static bool IsSingleRow(LogicalOperator &op) { + reference current = op; + while (current.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { + current = *current.get().children[0]; + } + if (current.get().type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + return false; + } + auto &aggregate = current.get().Cast(); + return aggregate.groups.empty() && aggregate.grouping_sets.size() <= 1; +} + +//! The RHS of the equality join is grouped by (a subset of) the join keys. +static bool JoinRHSIsDeduplicated(LogicalComparisonJoin &join) { + vector bindings; + for (auto &condition : join.conditions) { + if (!condition.IsComparison() || condition.GetRHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + condition.GetRHS().Cast().Depth() != 0) { + return false; + } + bindings.push_back(condition.GetRHS().Cast().Binding()); + } + return LogicalAggregate::KeysAreUnique(*join.children[1], std::move(bindings)); +} + +static bool ProjectionOnlyPassesKey(LogicalOperator &op, idx_t passthrough, ColumnBinding key) { + for (idx_t index = 0; index < op.expressions.size(); index++) { + if (index == passthrough) { + continue; + } + bool observes_key = false; + ExpressionIterator::EnumerateExpression(op.expressions[index], [&](const Expression &child) { + switch (child.GetExpressionClass()) { + case ExpressionClass::BOUND_COLUMN_REF: { + auto &column = child.Cast(); + observes_key |= column.Depth() != 0 || column.Binding() == key; + break; + } + case ExpressionClass::BOUND_LAMBDA: + case ExpressionClass::BOUND_LAMBDA_REF: + case ExpressionClass::BOUND_SUBQUERY: + case ExpressionClass::BOUND_REF: + observes_key = true; + break; + default: + break; + } + }); + if (observes_key) { + return false; + } + } + return true; +} + +//! Matches, at an INNER / LEFT / SINGLE join, +//! +//! JOIN (l.k IS NOT DISTINCT FROM p.k) +//! L: a reference of a materialized CTE +//! PROJECTION p (.., d.k) the empty-input substitution +//! LEFT JOIN (no condition) one row of empty-input aggregate values +//! LEFT JOIN (d.k = a.k) +//! d: the distinct keys of the CTE L reads +//! a: an aggregate grouped by the keys +//! +//! Only operators that compute one row from one row of the inner LEFT join may sit above it. +static bool FindOuterDomainJoin(LogicalOperator &op, const vector> &cte_scopes, + OuterDomainJoin &result) { + auto &join = op.Cast(); + if ((join.join_type != JoinType::SINGLE && join.join_type != JoinType::LEFT && join.join_type != JoinType::INNER) || + !join.left_projection_map.empty() || !join.expressions.empty() || !join.duplicate_eliminated_columns.empty() || + join.filter_pushdown || join.children[1]->type != LogicalOperatorType::LOGICAL_PROJECTION) { + return false; + } + vector> chain; + reference current = *join.children[1]; + while (true) { + auto &node = current.get(); + if (node.type == LogicalOperatorType::LOGICAL_PROJECTION) { + for (auto &expression : node.expressions) { + if (expression->CanThrow() || expression->IsVolatile()) { + return false; + } + } + } else if (node.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &inner = node.Cast(); + if (inner.join_type != JoinType::LEFT || inner.HasProjectionMap() || !inner.expressions.empty() || + !inner.duplicate_eliminated_columns.empty() || inner.filter_pushdown) { + return false; + } + if (!inner.conditions.empty()) { + break; + } + if (!IsSingleRow(*inner.children[1])) { + return false; + } + } else { + return false; + } + chain.push_back(node); + current = *node.children[0]; + } + auto &domain_join = current.get().Cast(); + auto &domain = *domain_join.children[0]; + auto domain_bindings = domain.GetColumnBindings(); + auto key_count = domain_bindings.size(); + if (key_count == 0 || domain_join.conditions.size() != key_count || join.conditions.size() != key_count || + !JoinRHSIsDeduplicated(domain_join)) { + return false; + } + + // The inner LEFT join compares every domain column with a group of the aggregate. The domain columns are the + // groups of the duplicate elimination, each of them exactly once: a group that is not output, or one that is output + // twice in place of another, leaves several domain rows per key and would multiply the rows of the LHS. + vector sources; + vector domain_groups(key_count, false); + for (idx_t index = 0; index < key_count; index++) { + idx_t compared = 0; + for (auto &condition : domain_join.conditions) { + if (!condition.IsComparison() || + (condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL && + condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { + continue; + } + auto &left = condition.GetLHS(); + if (left.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && + left.Cast().Depth() == 0 && + left.Cast().Binding() == domain_bindings[index]) { + compared++; + } + } + TableIndex cte; + idx_t column; + idx_t group = 0; + if (compared != 1 || !TraceSourceColumn(domain, index, cte_scopes, true, key_count, cte, column, group) || + group >= key_count || domain_groups[group]) { + return false; + } + domain_groups[group] = true; + if (index == 0) { + result.source = cte; + } else if (result.source != cte) { + return false; + } + sources.push_back(column); + } + + // The outer join compares the LHS column each domain column duplicates with that column, passed through. + vector matched(key_count, false); + result.keys.resize(key_count); + vector demand_indices(key_count); + for (auto &condition : join.conditions) { + if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM || + condition.GetLHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + condition.GetRHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + condition.GetRHS().Cast().Depth() != 0) { + return false; + } + auto left_index = ReferenceIndex(condition.GetLHS(), *join.children[0]); + TableIndex cte; + idx_t column; + idx_t group = 0; + if (!left_index.IsValid() || + !TraceSourceColumn(*join.children[0], left_index.GetIndex(), cte_scopes, false, 0, cte, column, group)) { + return false; + } + auto binding = condition.GetRHS().Cast().Binding(); + auto &type = condition.GetLHS().GetReturnType(); + const auto sensitive_key = !BoundComparisonExpression::EqualityPreservesValueRepresentation(type); + if (sensitive_key) { + auto outputs = join.GetColumnBindings(); + if (!type.IsFloating() || std::find(outputs.begin(), outputs.end(), binding) != outputs.end()) { + return false; + } + } + for (auto &above : chain) { + if (above.get().type != LogicalOperatorType::LOGICAL_PROJECTION) { + continue; + } + auto outputs = above.get().GetColumnBindings(); + auto entry = std::find(outputs.begin(), outputs.end(), binding); + if (entry == outputs.end()) { + return false; + } + auto projection_index = NumericCast(entry - outputs.begin()); + auto &expression = *above.get().expressions[projection_index]; + if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + expression.Cast().Depth() != 0) { + return false; + } + binding = expression.Cast().Binding(); + if (sensitive_key && !ProjectionOnlyPassesKey(above.get(), projection_index, binding)) { + return false; + } + } + auto entry = std::find(domain_bindings.begin(), domain_bindings.end(), binding); + if (entry == domain_bindings.end()) { + return false; + } + auto index = NumericCast(entry - domain_bindings.begin()); + if (cte != result.source || column != sources[index] || matched[index]) { + return false; + } + matched[index] = true; + result.keys[index] = make_pair(binding, condition.GetLHS().Cast().Binding()); + demand_indices[index] = left_index.GetIndex(); + } + + auto &aggregate_side = *domain_join.children[1]; + result.chain_length = chain.size(); + result.domain_join = &domain_join; + vector aggregate_indices, domain_indices; + for (auto &condition : domain_join.conditions) { + auto index = ReferenceIndex(condition.GetRHS(), aggregate_side); + auto domain_index = ReferenceIndex(condition.GetLHS(), domain); + if (!index.IsValid() || !domain_index.IsValid()) { + return true; + } + aggregate_indices.push_back(index.GetIndex()); + domain_indices.push_back(domain_index.GetIndex()); + } + auto aggregate_match = FindAggregate(aggregate_side, std::move(aggregate_indices)); + if (aggregate_match) { + result.aggregate = aggregate_match->aggregate.get(); + result.demand_indices.resize(key_count); + result.comparisons.resize(key_count); + for (idx_t index = 0; index < key_count; index++) { + auto group = aggregate_match->group_indices[index]; + result.demand_indices[group] = demand_indices[domain_indices[index]]; + result.comparisons[group] = domain_join.conditions[index].GetComparisonType(); + } + } + return true; +} + static BindingReplacementGraph MaterializeRuntimeDomain(Optimizer &optimizer, unique_ptr &op, idx_t demand_side, const LogicalCTERef &domain) { BindingReplacementGraph replacements; @@ -1148,6 +1731,7 @@ bool DuplicateEliminatedDomainOptimizer::TryOptimizeRuntimeDomain(unique_ptr(type, scan->GetColumnBindings()[scan_source.key]); scan_domain = CreateKeyDomain(optimizer, std::move(scan), std::move(key)); DomainCostModel costs(extractor, aggregate, scan_source.rows, scan_source.scan_rows); + // A scan supplies the keys: the demand's source is released either way. if (TryOptimizeRuntimeRestriction(optimizer.context, costs, aggregate, demand, demand_index, scan_domain, comparison, cte_scopes, true) != RestrictionAction::KEEP) { return true; @@ -1192,6 +1776,211 @@ bool DuplicateEliminatedDomainOptimizer::TryOptimizeRuntimeDomain(unique_ptr().cte_index == cte ? 1 : 0; + } + idx_t count = 0; + for (auto &child : op.children) { + count += CountReferences(*child, cte); + } + return count; +} + +//! Which producers stop when the restriction of the aggregate input to the keys of `domain` is removed and the outer +//! side `demand` takes the place of the domain. The restriction keys and the domain go away with the rewrite; their +//! producers only stop when nothing else reads them: +//! - the duplicate elimination behind the domain, when it is inline or a CTE that only the domain and the restriction +//! keys reference; +//! - the materialization of the source, when the demand is its only remaining reference and the CTE is not +//! materialized on request (it is then inlined). +static ReleasedDomainWork FindReleasedDomainWork(LogicalOperator &demand, LogicalOperator &domain, + optional_ptr restriction_keys, TableIndex source, + const vector> &cte_scopes) { + ReleasedDomainWork released; + reference production = domain; + while (production.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { + production = *production.get().children[0]; + } + auto released_source_references = + CountReferences(domain, source) + (restriction_keys ? CountReferences(*restriction_keys, source) : 0); + bool production_stops = true; + if (production.get().type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto index = production.get().Cast().cte_index; + auto owner = FindVisibleOwner(index, cte_scopes); + production_stops = + owner && index != source && + CountReferences(*owner->children[1], index) == + CountReferences(domain, index) + (restriction_keys ? CountReferences(*restriction_keys, index) : 0); + if (production_stops) { + production = *owner->children[0]; + released_source_references += CountReferences(production, source); + } + } + if (production_stops) { + released.production = production.get(); + } + auto owner = FindVisibleOwner(source, cte_scopes); + if (owner && owner->materialize != CTEMaterialize::CTE_MATERIALIZE_ALWAYS && CountReferences(demand, source) == 1 && + CountReferences(*owner->children[1], source) == 1 + released_source_references) { + released.source = *owner->children[0]; + } + return released; +} + +static bool RecoveryIsProfitable(LogicalComparisonJoin &join, const OuterDomainJoin &matched, + RelationStatsExtractor &extractor, const ReleasedDomainWork &released, + double restriction_savings) { + double expression_work = 0; + idx_t single_row_joins = 0; + optional_ptr current = *join.children[1]; + for (idx_t depth = 0; depth < matched.chain_length; depth++) { + if (current->type == LogicalOperatorType::LOGICAL_PROJECTION) { + for (auto &expression : current->expressions) { + if (!IsWorkReference(*expression)) { + expression_work += static_cast(ExpressionHeuristics::Cost(*expression)); + } + } + } else { + single_row_joins++; + } + current = *current->children[0]; + } + if (expression_work == 0 && single_row_joins == 0) { + return true; + } + auto outer = extractor.Extract(*join.children[0]); + auto domain = extractor.Extract(*matched.domain_join->children[0]); + if (!outer || !domain) { + return false; + } + auto outer_rows = static_cast(outer->cardinality); + return DomainCostModel::IsRecoveryProfitable(outer_rows, *domain, expression_work, single_row_joins, + DomainCostModel::EstimateReleasedWork(extractor, released), + restriction_savings); +} + +//! Replace the recovery domain by the outer rows when the saved join pays for additional evaluation. +bool DuplicateEliminatedDomainOptimizer::TryPullUpOuterDomainJoin(unique_ptr &op) { + OuterDomainJoin matched; + if (!FindOuterDomainJoin(*op, cte_scopes, matched)) { + return false; + } + RelationStatsExtractor extractor(optimizer.context, [&](TableIndex index) -> optional_ptr { + auto owner = FindVisibleOwner(index, cte_scopes); + return owner ? owner->children[0].get() : nullptr; + }); + auto collapse_released = FindReleasedDomainWork(*op->children[0], *matched.domain_join->children[0], nullptr, + matched.source, cte_scopes); + optional restriction; + RestrictionDecision decision; + if (matched.aggregate) { + restriction.emplace(optimizer.context, cte_scopes, *matched.aggregate, matched.comparisons); + auto restriction_join = restriction->GetJoin(); + auto &aggregate_side = *matched.domain_join->children[1]; + if (restriction_join && + CountSourceReaders(aggregate_side, matched.source, cte_scopes) == + CountSourceReaders(*restriction_join->children[1], matched.source, cte_scopes) && + RuntimeRestrictionContainsDemand(*restriction, *op->children[0], matched.demand_indices, cte_scopes)) { + auto released = FindReleasedDomainWork(*op->children[0], *matched.domain_join->children[0], + *restriction_join->children[1], matched.source, cte_scopes); + // Only credit work that survives collapse with the restriction kept. + if (collapse_released.production) { + released.production = nullptr; + } + if (collapse_released.source) { + released.source = nullptr; + } + DomainCostModel costs(extractor, *matched.aggregate); + costs.SetReleasedWork(released); + decision = costs.ChooseRestrictionAction(*restriction, nullptr); + } + } + if (!RecoveryIsProfitable(op->Cast(), matched, extractor, collapse_released, + decision.removal_savings)) { + return false; + } + if (decision.action == RestrictionAction::REMOVE) { + restriction->Remove(); + } + + auto old_bindings = op->GetColumnBindings(); + auto &join = op->Cast(); + join.children[0]->ResolveOperatorTypes(); + auto left_types = join.children[0]->types; + auto left_bindings = join.children[0]->GetColumnBindings(); + auto right_projection_map = std::move(join.right_projection_map); + join.right_projection_map.clear(); + + // The join takes the place of the LEFT join against the key domain. + ColumnBindingReplacer replacer; + for (auto &key : matched.keys) { + replacer.replacement_bindings.emplace_back(key.first, key.second); + } + auto chain_top = std::move(join.children[1]); + vector> chain; + reference> slot = chain_top; + for (idx_t depth = 0; depth < matched.chain_length; depth++) { + chain.push_back(*slot.get()); + slot = slot.get()->children[0]; + } + auto &domain_join = slot.get()->Cast(); + join.children[1] = std::move(domain_join.children[1]); + join.conditions = std::move(domain_join.conditions); + for (auto &condition : join.conditions) { + replacer.VisitExpression(&condition.LeftReference()); + } + join.join_type = JoinType::LEFT; + slot.get() = std::move(op); + + // The operators above read the LHS keys instead of the domain and pass the LHS through. + auto current_left = left_bindings; + idx_t top_column_count = 0; + for (idx_t depth = chain.size(); depth-- > 0;) { + auto &node = chain[depth].get(); + if (node.type != LogicalOperatorType::LOGICAL_PROJECTION) { + continue; + } + auto table_index = node.Cast().table_index; + for (auto &expression : node.expressions) { + replacer.VisitExpression(&expression); + } + top_column_count = node.expressions.size(); + for (idx_t column = 0; column < current_left.size(); column++) { + auto passed = ColumnBinding::PushExpression( + node.expressions, make_uniq(left_types[column], current_left[column])); + current_left[column] = ColumnBinding(table_index, passed); + } + } + + // Restore the column order of the join: its LHS, then its RHS. + auto projection = LogicalProjection::CreateIdentity(optimizer.binder.GenerateTableIndex(), std::move(chain_top)); + auto right_expressions = std::move(projection->expressions); + projection->expressions.clear(); + for (idx_t column = top_column_count; column < right_expressions.size(); column++) { + projection->expressions.push_back(std::move(right_expressions[column])); + } + if (right_projection_map.empty()) { + for (idx_t column = 0; column < top_column_count; column++) { + projection->expressions.push_back(std::move(right_expressions[column])); + } + } else { + for (auto &index : right_projection_map) { + projection->expressions.push_back(right_expressions[index.GetIndex()]->Copy()); + } + } + projection->ResolveOperatorTypes(); + auto new_bindings = projection->GetColumnBindings(); + op = std::move(projection); + for (idx_t column = 0; column < old_bindings.size(); column++) { + if (old_bindings[column] != new_bindings[column] && !replacements.Find(old_bindings[column])) { + replacements.Add(old_bindings[column], new_bindings[column]); + } + } + return true; +} + bool DuplicateEliminatedDomainOptimizer::TryOptimizeDomain(unique_ptr &op, idx_t aggregate_side, idx_t condition_index) { auto &join = op->Cast(); @@ -1266,7 +2055,7 @@ void DuplicateEliminatedDomainOptimizer::VisitOperator(unique_ptrtype == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && !TryPullUpOuterDomainJoin(op)) { auto &join = op->Cast(); bool safe_conditions = true; LogicalOperatorVisitor::EnumerateExpressions(join, [&](const unique_ptr *expression) { diff --git a/src/duckdb/src/optimizer/expression_heuristics.cpp b/src/duckdb/src/optimizer/expression_heuristics.cpp index 9cfad2969..05967ff00 100644 --- a/src/duckdb/src/optimizer/expression_heuristics.cpp +++ b/src/duckdb/src/optimizer/expression_heuristics.cpp @@ -132,11 +132,22 @@ idx_t ExpressionHeuristics::ExpressionCost(const BoundFunctionExpression &expr) if (BoundCastExpression::IsCast(expr)) { return CastExpressionCost(expr); } - identifier_map_t function_costs = {{"+", 5}, {"-", 5}, {"&", 5}, {"#", 5}, - {">>", 5}, {"<<", 5}, {"abs", 5}, {"*", 10}, - {"%", 10}, {"/", 15}, {"date_part", 20}, {"year", 20}, - {"round", 100}, {"~~", 200}, {"!~~", 200}, {"regexp_matches", 200}, - {"||", 200}}; + if (expr.Function().GetName() == OptionalFilterScalarFun::NAME) { + return 0; + } + if (expr.Function().GetName() == SelectivityOptionalFilterScalarFun::NAME) { + auto child = ExpressionFilter::GetOptionalFilterChild(expr); + return child ? Cost(*child) : 0; + } + identifier_map_t function_costs = {{"+", 5}, {"-", 5}, + {"&", 5}, {"#", 5}, + {">>", 5}, {"<<", 5}, + {"abs", 5}, {"*", 10}, + {"%", 10}, {"/", 15}, + {"date_part", 20}, {"year", 20}, + {"round", 100}, {"~~", 200}, + {"!~~", 200}, {"regexp_matches", 200}, + {"||", 200}, {PrefixRangeScalarFun::NAME, 20}}; idx_t cost_children = 0; for (auto &child : expr.GetChildren()) { @@ -160,6 +171,8 @@ idx_t ExpressionHeuristics::ExpressionCost(const BoundOperatorExpression &expr, // OPERATOR_IS_NULL, OPERATOR_IS_NOT_NULL if (expr_type == ExpressionType::OPERATOR_IS_NULL || expr_type == ExpressionType::OPERATOR_IS_NOT_NULL) { return sum + 5; + } else if (expr_type == ExpressionType::OPERATOR_COALESCE) { + return sum + 5 * (expr.GetChildren().size() - 1); } else if (expr_type == ExpressionType::COMPARE_IN || expr_type == ExpressionType::COMPARE_NOT_IN) { // COMPARE_IN, COMPARE_NOT_IN return sum + (expr.GetChildren().size() - 1) * 100; @@ -227,9 +240,7 @@ idx_t ExpressionHeuristics::Cost(const Expression &expr) { return 1000; } -idx_t ExpressionHeuristics::Cost(const TableFilter &filter) { - auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter, "ExpressionHeuristics::Cost"); - auto &expr = *expr_filter.expr; +static idx_t TableFilterExpressionCost(const Expression &expr) { if (ExpressionBarrier::Contains(expr)) { // a barrier filter is always evaluated last, so that it never runs on rows another filter removes return NumericLimits::Maximum(); @@ -237,6 +248,18 @@ idx_t ExpressionHeuristics::Cost(const TableFilter &filter) { if (ExpressionFilter::ContainsInternalFunction(expr, DynamicFilterScalarFun::NAME)) { return 0; } + if (expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + constexpr idx_t conjunction_cost = 5; + idx_t cost = conjunction_cost; + for (auto &child : expr.Cast().GetChildren()) { + auto child_cost = TableFilterExpressionCost(*child); + if (child_cost >= NumericLimits::Maximum() - cost) { + return NumericLimits::Maximum(); + } + cost += child_cost; + } + return cost == conjunction_cost ? 0 : cost; + } if (expr.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { auto &func = expr.Cast(); if (func.Function().GetName() == OptionalFilterScalarFun::NAME) { @@ -244,13 +267,15 @@ idx_t ExpressionHeuristics::Cost(const TableFilter &filter) { } if (func.Function().GetName() == SelectivityOptionalFilterScalarFun::NAME && func.BindInfo()) { auto optional_child = ExpressionFilter::GetOptionalFilterChild(func); - return optional_child ? Cost(*optional_child) : 0; + return optional_child ? TableFilterExpressionCost(*optional_child) : 0; } } - if (ExpressionFilter::IsOptionalExpression(expr)) { - return 0; - } - return Cost(expr); + return ExpressionHeuristics::Cost(expr); +} + +idx_t ExpressionHeuristics::Cost(const TableFilter &filter) { + auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter, "ExpressionHeuristics::Cost"); + return TableFilterExpressionCost(*expr_filter.expr); } vector ExpressionHeuristics::GetInitialOrder(const TableFilterSet &table_filters) { diff --git a/src/duckdb/src/optimizer/filter_combiner.cpp b/src/duckdb/src/optimizer/filter_combiner.cpp index d3ef2cc5d..920412a82 100644 --- a/src/duckdb/src/optimizer/filter_combiner.cpp +++ b/src/duckdb/src/optimizer/filter_combiner.cpp @@ -216,7 +216,7 @@ void FilterCombiner::GenerateFilters(const std::function(lower_value); auto upper_constant = make_uniq(upper_value); auto between = - BoundBetweenExpression::Create(entries[i].get().Copy(), std::move(lower_constant), + BoundBetweenExpression::Create(context, entries[i].get().Copy(), std::move(lower_constant), std::move(upper_constant), lower_inclusive, upper_inclusive); callback(std::move(between)); } @@ -291,6 +291,17 @@ static unique_ptr CreateOptionalExpressionFilter(unique_ptr(CreateOptionalFilterExpression(std::move(child_expr), col_type)); } +static unique_ptr CreateAdaptiveInFilter(unique_ptr in_expr, const LogicalType &type) { + // Keep large lists pruning-only; evaluating them per row is expensive. + if (in_expr->Cast().GetChildren().size() >= + InClauseRewriter::IN_CLAUSE_REWRITE_THRESHOLD || + !ExpressionFilterExecutor::TryCreate(*in_expr)) { + return CreateOptionalExpressionFilter(std::move(in_expr), type); + } + return ExpressionFilter::CreateSelectivityOptionalFilter(std::move(in_expr), type, + SelectivityOptionalFilterType::IN_FILTER); +} + bool FilterCombiner::ContainsNull(vector &in_list) { for (idx_t i = 0; i < in_list.size(); i++) { if (in_list[i].IsNull()) { @@ -745,10 +756,10 @@ FilterPushdownResult FilterCombiner::TryPushdownInFilter(TableFilterSet &table_f if (TryPushdownDenseInFilter(table_filters, column_ref, in_list)) { return FilterPushdownResult::PUSHED_DOWN_FULLY; } - // if this is not a dense range we can push an optional filter for zone-map pruning + // Keep the residual filter so scans can skip row filtering when it is not selective. auto in_expr = ExpressionFilter::CreateInExpression(CreateFilterTargetExpression(*func.GetChildren()[0]), std::move(in_list)); - table_filters.PushFilter(proj_index, CreateOptionalExpressionFilter(std::move(in_expr), type)); + table_filters.PushFilter(proj_index, CreateAdaptiveInFilter(std::move(in_expr), type)); return FilterPushdownResult::PUSHED_DOWN_PARTIALLY; } @@ -838,7 +849,7 @@ FilterPushdownResult FilterCombiner::TryPushdownOrClause(TableFilterSet &table_f // Push the same filter as for `col IN (...)`, which index scans can use. auto in_expr = ExpressionFilter::CreateInExpression(CreateFilterTargetExpression(*equality_column), std::move(equality_values)); - table_filters.PushFilter(proj_id, CreateOptionalExpressionFilter(std::move(in_expr), col_type)); + table_filters.PushFilter(proj_id, CreateAdaptiveInFilter(std::move(in_expr), col_type)); return FilterPushdownResult::PUSHED_DOWN_PARTIALLY; } table_filters.PushFilter(proj_id, CreateOptionalExpressionFilter(std::move(conj_filter), col_type)); @@ -855,8 +866,9 @@ static bool IsLessThan(ExpressionType type) { //! Returns the relaxation margin in native units of the source type for a temporal cast. //! Returns -1 if the cast pair is not supported for relaxed pushdown. -//! Margins: 2h for DST ambiguity (TIMESTAMP<->TIMESTAMPTZ), 24h for time-of-day loss, 1s for rounding loss. +//! Margins: 48h for timestamp casts that read the time zone, 1 day DATE->TIMESTAMPTZ, 24h for time of day, 1s rounding. static int64_t GetTemporalCastMargin(LogicalTypeId source, LogicalTypeId target) { + static constexpr int64_t TIME_ZONE_MARGIN = 2LL * Interval::MICROS_PER_DAY; // microseconds if (source == target) { switch (source) { case LogicalTypeId::DATE: @@ -874,12 +886,10 @@ static int64_t GetTemporalCastMargin(LogicalTypeId source, LogicalTypeId target) } switch (source) { case LogicalTypeId::TIMESTAMP: - case LogicalTypeId::TIMESTAMP_TZ: // native unit: microseconds switch (target) { - case LogicalTypeId::TIMESTAMP: case LogicalTypeId::TIMESTAMP_TZ: - return 2LL * Interval::MICROS_PER_HOUR; + return TIME_ZONE_MARGIN; case LogicalTypeId::DATE: return Interval::MICROS_PER_DAY; case LogicalTypeId::TIMESTAMP_MS: @@ -888,8 +898,18 @@ static int64_t GetTemporalCastMargin(LogicalTypeId source, LogicalTypeId target) default: return -1; } + case LogicalTypeId::TIMESTAMP_TZ: + // native unit: microseconds + switch (target) { + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::DATE: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP_SEC: + return TIME_ZONE_MARGIN; + default: + return -1; + } case LogicalTypeId::TIMESTAMP_NS: - case LogicalTypeId::TIMESTAMP_TZ_NS: // native unit: nanoseconds switch (target) { case LogicalTypeId::TIMESTAMP: @@ -901,6 +921,19 @@ static int64_t GetTemporalCastMargin(LogicalTypeId source, LogicalTypeId target) default: return -1; } + case LogicalTypeId::TIMESTAMP_TZ_NS: + // native unit: nanoseconds + switch (target) { + // ICU does not override these, so they only lose precision + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP_SEC: + return Interval::MICROS_PER_SEC * 1000LL; + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::DATE: + return TIME_ZONE_MARGIN * 1000LL; + default: + return -1; + } case LogicalTypeId::TIMESTAMP_MS: // native unit: milliseconds switch (target) { diff --git a/src/duckdb/src/optimizer/filter_pullup.cpp b/src/duckdb/src/optimizer/filter_pullup.cpp index 1e66a7b4e..374eef567 100644 --- a/src/duckdb/src/optimizer/filter_pullup.cpp +++ b/src/duckdb/src/optimizer/filter_pullup.cpp @@ -70,8 +70,8 @@ unique_ptr FilterPullup::PullupJoin(unique_ptr unique_ptr FilterPullup::PullupSemiJoin(unique_ptr op) { auto &join = op->Cast(); D_ASSERT(join.join_type == JoinType::SEMI); - FilterPullup left_pullup(true, can_add_column); - FilterPullup right_pullup(true, can_add_column); + FilterPullup left_pullup(context, true, can_add_column); + FilterPullup right_pullup(context, true, can_add_column); op->children[0] = left_pullup.Rewrite(std::move(op->children[0])); op->children[1] = right_pullup.Rewrite(std::move(op->children[1])); @@ -193,7 +193,7 @@ unique_ptr FilterPullup::GeneratePullupFilter(unique_ptr FilterPullup::FinishPullup(unique_ptr op) { // unhandled type, first perform filter pushdown in its children for (idx_t i = 0; i < op->children.size(); i++) { - FilterPullup pullup; + FilterPullup pullup(context); op->children[i] = pullup.Rewrite(std::move(op->children[i])); } // now pull up any existing filters diff --git a/src/duckdb/src/optimizer/filter_pushdown.cpp b/src/duckdb/src/optimizer/filter_pushdown.cpp index e6bf854f7..f89dc4816 100644 --- a/src/duckdb/src/optimizer/filter_pushdown.cpp +++ b/src/duckdb/src/optimizer/filter_pushdown.cpp @@ -1,14 +1,11 @@ #include "duckdb/optimizer/filter_pushdown.hpp" #include "duckdb/optimizer/filter_combiner.hpp" #include "duckdb/optimizer/optimizer.hpp" -#include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_join.hpp" #include "duckdb/planner/operator/logical_empty_result.hpp" #include "duckdb/planner/operator/logical_window.hpp" -#include "duckdb/planner/expression/bound_columnref_expression.hpp" -#include "duckdb/planner/logical_operator_visitor.hpp" #include "duckdb/common/algorithm.hpp" #include "duckdb/planner/expression/expression_barrier.hpp" @@ -16,67 +13,8 @@ namespace duckdb { using Filter = FilterPushdown::Filter; -static bool ExpressionsBecomeFilters(const LogicalOperator &op) { - if (op.type == LogicalOperatorType::LOGICAL_FILTER) { - return true; - } - switch (op.type) { - case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: - case LogicalOperatorType::LOGICAL_ANY_JOIN: - case LogicalOperatorType::LOGICAL_DELIM_JOIN: - return op.Cast().join_type == JoinType::INNER; - default: - return false; - } -} - -void FilterPushdown::CheckMarkToSemi(LogicalOperator &op, const unordered_set &table_bindings) { - auto referenced_bindings = table_bindings; - if (!ExpressionsBecomeFilters(op)) { - LogicalOperatorVisitor::EnumerateExpressions( - static_cast(op), [&](const unique_ptr *expression) { - ExpressionIterator::VisitExpression( - **expression, [&](const BoundColumnRefExpression &column_ref) { - referenced_bindings.insert(column_ref.Binding().table_index); - }); - }); - } - - switch (op.type) { - case LogicalOperatorType::LOGICAL_DELIM_JOIN: { - auto &join = op.Cast(); - if (join.join_type == JoinType::MARK) { - // Duplicate-eliminated correlated subqueries must keep MARK semantics; converting to SEMI can drop - // correlation for nested RHS shapes (issue #22267). - join.convert_mark_to_semi = false; - } - break; - } - case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { - auto &join = op.Cast(); - if (join.join_type != JoinType::MARK) { - break; - } - // if an operator above the mark join includes the mark join index, - // then the mark join cannot be converted to a semi join - if (referenced_bindings.find(join.mark_index) != referenced_bindings.end()) { - join.convert_mark_to_semi = false; - } - break; - } - default: - break; - } - - // Recurse into each child with the bindings referenced on this path. - for (auto &child : op.children) { - CheckMarkToSemi(*child, referenced_bindings); - } -} - -FilterPushdown::FilterPushdown(Optimizer &optimizer, bool convert_mark_joins, ProjectionMode projection_mode) - : optimizer(optimizer), combiner(optimizer.context), convert_mark_joins(convert_mark_joins), - projection_mode(projection_mode) { +FilterPushdown::FilterPushdown(Optimizer &optimizer, ProjectionMode projection_mode) + : optimizer(optimizer), combiner(optimizer.context), projection_mode(projection_mode) { } bool FilterPushdown::BarrierCanPassThrough(LogicalOperatorType type) { @@ -139,7 +77,7 @@ unique_ptr FilterPushdown::Rewrite(unique_ptr return op; case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: { // we can't push filters into the materialized CTE (LHS), but we do want to recurse into it - FilterPushdown pushdown(optimizer, convert_mark_joins, projection_mode); + FilterPushdown pushdown(optimizer, projection_mode); op->children[0] = pushdown.Rewrite(std::move(op->children[0])); // we can push filters into the rest of the query plan (RHS) op->children[1] = Rewrite(std::move(op->children[1])); @@ -271,7 +209,7 @@ unique_ptr FilterPushdown::PushFiltersIntoDelimJoin(unique_ptr< for (idx_t i = 0; i < filters.size(); i++) { auto &f = *filters[i]; for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { - FilterPushdown pushdown(optimizer, convert_mark_joins, projection_mode); + FilterPushdown pushdown(optimizer, projection_mode); // check if filter bindings can be applied to the child bindings. auto child_bindings = op->children[child_idx]->GetColumnBindings(); @@ -315,7 +253,7 @@ unique_ptr FilterPushdown::PushFiltersIntoDelimJoin(unique_ptr< unique_ptr FilterPushdown::FinishPushdown(unique_ptr op) { // unhandled type, first perform filter pushdown in its children for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { - FilterPushdown pushdown(optimizer, convert_mark_joins, projection_mode); + FilterPushdown pushdown(optimizer, projection_mode); pushdown.RewriteChild(*op, child_idx); } // now push any existing filters diff --git a/src/duckdb/src/optimizer/filter_statistics.cpp b/src/duckdb/src/optimizer/filter_statistics.cpp index 578b7b8d2..97b941895 100644 --- a/src/duckdb/src/optimizer/filter_statistics.cpp +++ b/src/duckdb/src/optimizer/filter_statistics.cpp @@ -5,7 +5,14 @@ #include "duckdb/optimizer/statistics_propagator.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" #include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_set_operation.hpp" namespace duckdb { @@ -50,8 +57,153 @@ bool FilterStatisticsOptimizer::ContainsDelimJoin(const LogicalOperator &op) con return false; } +//! Collects the columns that the filters and join conditions of the plan read +static void GetComparedBindings(LogicalOperator &op, column_binding_set_t &bindings) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + case LogicalOperatorType::LOGICAL_ANY_JOIN: + case LogicalOperatorType::LOGICAL_ASOF_JOIN: { + auto add_binding = [&](const BoundColumnRefExpression &ref) { + if (ref.Depth() == 0) { + bindings.insert(ref.Binding()); + } + }; + LogicalOperatorVisitor::EnumerateExpressions(op, [&](unique_ptr *expr) { + ExpressionIterator::VisitExpression(**expr, add_binding); + }); + break; + } + default: + break; + } + for (auto &child : op.children) { + GetComparedBindings(*child, bindings); + } +} + +//! Adds the columns that the compared columns are computed from, so that a comparison above a projection, an +//! aggregate, a set operation or a reference to a materialized CTE is traced to the scans below it. +//! Columns that any other operator computes (a window, an unnest, a recursive CTE, ...) are not traced: a comparison +//! with such a column is only folded by the statistics propagation that runs after the join order. +static void AddSourceBindings(LogicalOperator &op, column_binding_set_t &bindings, + unordered_map> &cte_bindings) { + auto is_compared = [&](TableIndex table_index, idx_t column_idx) { + return bindings.find(ColumnBinding(table_index, ProjectionIndex(column_idx))) != bindings.end(); + }; + auto add_sources = [&](const Expression &expr) { + ExpressionIterator::VisitExpression(expr, [&](const BoundColumnRefExpression &ref) { + if (ref.Depth() == 0) { + bindings.insert(ref.Binding()); + } + }); + }; + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &projection = op.Cast(); + for (idx_t i = 0; i < projection.expressions.size(); i++) { + if (is_compared(projection.table_index, i)) { + add_sources(*projection.expressions[i]); + } + } + break; + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &aggregate = op.Cast(); + for (idx_t i = 0; i < aggregate.groups.size(); i++) { + if (is_compared(aggregate.group_index, i)) { + add_sources(*aggregate.groups[i]); + } + } + break; + } + case LogicalOperatorType::LOGICAL_UNION: + case LogicalOperatorType::LOGICAL_EXCEPT: + case LogicalOperatorType::LOGICAL_INTERSECT: { + auto &setop = op.Cast(); + for (auto &child : setop.children) { + auto child_bindings = child->GetColumnBindings(); + for (idx_t i = 0; i < MinValue(setop.column_count, child_bindings.size()); i++) { + if (is_compared(setop.table_index, i)) { + bindings.insert(child_bindings[i]); + } + } + } + break; + } + case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: { + // the references to the CTE are in the query that uses it: trace that before the definition + cte_bindings[op.Cast().table_index] = op.children[0]->GetColumnBindings(); + AddSourceBindings(*op.children[1], bindings, cte_bindings); + AddSourceBindings(*op.children[0], bindings, cte_bindings); + return; + } + case LogicalOperatorType::LOGICAL_CTE_REF: { + auto &cte_ref = op.Cast(); + auto entry = cte_bindings.find(cte_ref.cte_index); + if (entry == cte_bindings.end()) { + break; + } + auto &definition_bindings = entry->second; + for (idx_t i = 0; i < MinValue(cte_ref.chunk_types.size(), definition_bindings.size()); i++) { + if (is_compared(cte_ref.table_index, i)) { + bindings.insert(definition_bindings[i]); + } + } + break; + } + default: + break; + } + for (auto &child : op.children) { + AddSourceBindings(*child, bindings, cte_bindings); + } +} + +//! Whether a scan of the plan emits one of the bindings from a column that holds only NULLs +static bool ScansAllNullBinding(ClientContext &context, LogicalOperator &op, const column_binding_set_t &bindings) { + if (op.type == LogicalOperatorType::LOGICAL_GET) { + auto &get = op.Cast(); + auto &column_ids = get.GetColumnIds(); + for (idx_t i = 0; i < column_ids.size(); i++) { + if (bindings.find(ColumnBinding(get.table_index, ProjectionIndex(i))) == bindings.end()) { + continue; + } + auto stats = StatisticsPropagator::GetColumnStatistics(context, get, column_ids[i]); + if (StatisticsPropagator::HasNoValidValue(stats.get())) { + return true; + } + } + } + for (auto &child : op.children) { + if (ScansAllNullBinding(context, *child, bindings)) { + return true; + } + } + return false; +} + +bool FilterStatisticsOptimizer::ComparesAllNullColumn(LogicalOperator &plan) const { + if (optimizer.OptimizerDisabled(OptimizerType::STATISTICS_PROPAGATION)) { + return false; + } + column_binding_set_t bindings; + GetComparedBindings(plan, bindings); + if (bindings.empty()) { + return false; + } + unordered_map> cte_bindings; + AddSourceBindings(plan, bindings, cte_bindings); + return ScansAllNullBinding(optimizer.context, plan, bindings); +} + void FilterStatisticsOptimizer::Optimize(unique_ptr &plan) { - if (ContainsDelimJoin(*plan) || !HasMultiBindingFilter(*plan)) { + if (ContainsDelimJoin(*plan)) { + return; + } + // a comparison with a column that holds only NULLs never passes: propagating the statistics here removes + // the filters and joins on it before the join order is chosen + if (!HasMultiBindingFilter(*plan) && !ComparesAllNullColumn(*plan)) { return; } @@ -67,8 +219,6 @@ void FilterStatisticsOptimizer::Optimize(unique_ptr &plan) { optimizer.RunOptimizer(OptimizerType::FILTER_PUSHDOWN, [&]() { FilterPushdown filter_pushdown(optimizer); - unordered_set top_bindings; - filter_pushdown.CheckMarkToSemi(*plan, top_bindings); plan = filter_pushdown.Rewrite(std::move(plan)); }); } diff --git a/src/duckdb/src/optimizer/join_elimination.cpp b/src/duckdb/src/optimizer/join_elimination.cpp index 1a814a70a..7177114b4 100644 --- a/src/duckdb/src/optimizer/join_elimination.cpp +++ b/src/duckdb/src/optimizer/join_elimination.cpp @@ -1,329 +1,286 @@ #include "duckdb/optimizer/join_elimination.hpp" -#include "duckdb/common/assert.hpp" -#include "duckdb/common/enums/expression_type.hpp" #include "duckdb/common/enums/join_type.hpp" #include "duckdb/common/enums/logical_operator_type.hpp" -#include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/unique_ptr.hpp" -#include "duckdb/common/unordered_map.hpp" -#include "duckdb/common/unordered_set.hpp" #include "duckdb/common/vector.hpp" +#include "duckdb/optimizer/distinctness.hpp" #include "duckdb/planner/column_binding.hpp" +#include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/logical_operator.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_cte.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" #include "duckdb/planner/operator/logical_get.hpp" -#include "duckdb/planner/operator/logical_projection.hpp" #include namespace duckdb { -void JoinElimination::OptimizeChildren(LogicalOperator &op, optional_ptr parent, idx_t idx) { - if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { - if (!parent) { - return; + +//! Whether an expression of `op` itself is volatile +static bool AnyVolatile(const LogicalOperator &op) { + bool is_volatile = false; + LogicalOperatorVisitor::EnumerateExpressions(op, [&](const unique_ptr *expr) { + if ((*expr)->IsVolatile()) { + is_volatile = true; } - D_ASSERT(!pipe_info.join_parent); - pipe_info.join_parent = parent; - pipe_info.join_index = idx; - left_child = CreateChildren(); - right_child = CreateChildren(); - // the joins below must keep the columns this join's conditions read - left_child->VisitOperatorExpressions(op); - right_child->VisitOperatorExpressions(op); - left_child->OptimizeInternal(std::move(op.children[0])); - right_child->OptimizeInternal(std::move(op.children[1])); - return; + }); + return is_volatile; +} + +RemovedSubtreeEffects::RemovedSubtreeEffects(LogicalOperator &plan) { + CollectDefinitions(plan); +} + +void RemovedSubtreeEffects::CollectDefinitions(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + materialized_ctes.emplace(op.Cast().table_index, op); + } else if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + recursive_ctes.insert(op.Cast().table_index); + } + for (auto &child : op.children) { + CollectDefinitions(*child); } +} - VisitOperatorExpressions(op); +bool RemovedSubtreeEffects::DefinitionHasEffect(TableIndex cte_index) { + auto known = definition_has_effect.find(cte_index); + if (known != definition_has_effect.end()) { + return known->second; + } + auto cte = materialized_ctes.find(cte_index); + if (cte == materialized_ctes.end()) { + // a reference to something that is not defined in this plan: assume the worst + return true; + } + // a materialized CTE cannot reference itself, so the definition is known before it is asked about again + const bool has_effect = HasEffect(*cte->second.get().children[0]); + definition_has_effect.emplace(cte_index, has_effect); + return has_effect; +} - switch (op.type) { - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { - auto &aggr = op.Cast(); - if (aggr.grouping_sets.size() > 1) { - break; - } - // only resolve group by columns for now - column_binding_set_t distinct_group; - TableIndex table_idx = aggr.group_index; - for (idx_t i = 0; i < aggr.groups.size(); i++) { - distinct_group.insert(ColumnBinding(aggr.group_index, ProjectionIndex(i))); - } - if (!distinct_group.empty()) { - pipe_info.distinct_groups[table_idx] = std::move(distinct_group); - } - if (aggr.expressions.empty() && !aggr.groups.empty()) { - // a pure deduplication (e.g. SELECT DISTINCT) also makes the grouped input columns distinct - column_binding_set_t input_group; - TableIndex input_index; - bool single_input = true; - for (auto &group : aggr.groups) { - if (group->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { - single_input = false; - break; - } - auto &binding = group->Cast().Binding(); - if (!input_group.empty() && binding.table_index != input_index) { - single_input = false; - break; - } - input_index = binding.table_index; - input_group.insert(binding); - } - if (single_input) { - pipe_info.distinct_groups[input_index] = std::move(input_group); - } +bool RemovedSubtreeEffects::HasEffect(LogicalOperator &subtree) { + if (AnyVolatile(subtree)) { + return true; + } + switch (subtree.type) { + case LogicalOperatorType::LOGICAL_INSERT: + case LogicalOperatorType::LOGICAL_DELETE: + case LogicalOperatorType::LOGICAL_UPDATE: + case LogicalOperatorType::LOGICAL_MERGE_INTO: + return true; + case LogicalOperatorType::LOGICAL_GET: + if (subtree.Cast().function.stability == FunctionStability::VOLATILE) { + return true; } break; - } - case LogicalOperatorType::LOGICAL_PROJECTION: { - auto &projection = op.Cast(); - unordered_map> reference_records; - // for select distinct * from table, first projection then distinct. distinct_groups has record projection table - // id for select * from table group by col, first aggregate then projection. projection has aggregate table id. - - // before traverse children, first check whether any distinct group ref this projection - auto it = pipe_info.distinct_groups.find(projection.table_index); - if (it != pipe_info.distinct_groups.end()) { - column_binding_set_t new_distinct_group; - auto &start_expr = projection.GetExpression(*it->second.begin()); - if (start_expr.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { - // if the expression is not a column ref, we cannot eliminate the join - break; - } - bool could_add = true; - auto ref_id = start_expr.Cast().Binding().table_index; - for (auto &col : it->second) { - auto &expression = projection.GetExpression(col); - if (expression.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { - // if the expression is not a column ref, we cannot eliminate the join - could_add = false; - break; - } - auto &col_ref = expression.Cast(); - if (ref_id != col_ref.Binding().table_index) { - could_add = false; - break; - } - new_distinct_group.insert(col_ref.Binding()); - } - if (could_add) { - pipe_info.distinct_groups[ref_id] = std::move(new_distinct_group); - } + case LogicalOperatorType::LOGICAL_CTE_REF: { + auto cte_index = subtree.Cast().cte_index; + if (recursive_ctes.find(cte_index) == recursive_ctes.end() && DefinitionHasEffect(cte_index)) { + return true; } break; } - case LogicalOperatorType::LOGICAL_LIMIT: - case LogicalOperatorType::LOGICAL_TOP_N: - case LogicalOperatorType::LOGICAL_SAMPLE: - case LogicalOperatorType::LOGICAL_WINDOW: { - // these pick rows by cardinality, or compute values that depend on row multiplicity (window), so a - // distinct group above them does not hold below them - pipe_info.distinct_groups.clear(); + default: break; } - case LogicalOperatorType::LOGICAL_GET: { - auto &get = op.Cast(); - if (get.table_filters.HasFilters()) { - pipe_info.has_filter = true; + for (auto &child : subtree.children) { + if (HasEffect(*child)) { + return true; } - break; } - default: - break; + return false; +} + +void JoinElimination::OptimizeChild(LogicalOperator &op, idx_t child_idx, JoinElimination &child_optimizer, + bool replaceable) { + // `op` may select the columns of its child by position: when a join is removed below, the selection is remapped + auto projection_map = LogicalOperatorVisitor::GetProjectionMap(op, child_idx); + const bool has_projection_map = projection_map && !projection_map->empty(); + vector bindings_before; + if (has_projection_map) { + bindings_before = op.children[child_idx]->GetColumnBindings(); } + const auto removed_before = child_optimizer.removed_joins; + child_optimizer.OptimizeOperator(op.children[child_idx], replaceable); + if (has_projection_map && child_optimizer.removed_joins != removed_before) { + LogicalOperatorVisitor::RemapProjectionMap(*projection_map, bindings_before, + op.children[child_idx]->GetColumnBindings()); + } +} - if (op.children.size() == 1) { - // UNNEST emits multiple rows per input row, so a distinct group found below it does not hold above it - const auto invalidates_distinct = op.type == LogicalOperatorType::LOGICAL_UNNEST; - unordered_map distinct_groups_above; - if (invalidates_distinct) { - distinct_groups_above = pipe_info.distinct_groups; +void JoinElimination::OptimizeJoin(unique_ptr &op) { + while (true) { + auto &join = *op; + // the pipelines of the two sides inherit the references of the operators above; whatever they find below (table + // filters) stays theirs + auto left_child = CreateChildren(); + auto right_child = CreateChildren(); + // the joins below must keep the columns this join's conditions read + left_child->VisitOperatorExpressions(join); + right_child->VisitOperatorExpressions(join); + // repeated input rows only repeat the output rows of these joins, and a SEMI or ANTI join never sees how often + // a row of its right side occurs. A volatile join condition is evaluated once per repeated row: it sees them + const bool is_volatile = AnyVolatile(join); + const bool ignores_duplicates = pipe_info.ignores_duplicates && !is_volatile; + switch (join.Cast().join_type) { + case JoinType::INNER: + case JoinType::LEFT: + case JoinType::RIGHT: + case JoinType::OUTER: + left_child->pipe_info.ignores_duplicates = ignores_duplicates; + right_child->pipe_info.ignores_duplicates = ignores_duplicates; + break; + case JoinType::SEMI: + case JoinType::ANTI: + left_child->pipe_info.ignores_duplicates = ignores_duplicates; + right_child->pipe_info.ignores_duplicates = !is_volatile; + break; + case JoinType::MARK: + case JoinType::SINGLE: + // these return every row of their left side once; their right side is left alone + left_child->pipe_info.ignores_duplicates = ignores_duplicates; + break; + default: + break; } - OptimizeChildren(*op.children[0], op, idx); - if (invalidates_distinct) { - pipe_info.distinct_groups = std::move(distinct_groups_above); + OptimizeJoinChild(join, 0, *left_child); + OptimizeJoinChild(join, 1, *right_child); + removed_joins += left_child->removed_joins + right_child->removed_joins; + if (!TryEliminateJoin(op, *left_child, *right_child)) { + return; } - } else { - children_root = op; - for (auto &child : op.children) { - auto child_optimizer = CreateChildren(); - child_optimizer->OptimizeInternal(std::move(child)); - children.emplace_back(std::move(child_optimizer)); + removed_joins++; + // the outer side took the place of the join: when it is a join, it is tried in this pipeline in turn + if (op->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return; } + } +} + +void JoinElimination::OptimizeJoinChild(LogicalOperator &join, idx_t child_idx, JoinElimination &child) { + if (join.children[child_idx]->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + OptimizeChild(join, child_idx, child, true); return; } + // a join that is the child of a join is a pipeline of its own that inherits the references and the + // duplicate-insensitivity of this side: what is found below the nested join says nothing about its output + auto nested = child.CreateChildren(); + nested->pipe_info.ignores_duplicates = child.pipe_info.ignores_duplicates; + OptimizeChild(join, child_idx, *nested, true); + child.removed_joins += nested->removed_joins; +} - switch (op.type) { - case LogicalOperatorType::LOGICAL_PROJECTION: { - auto &projection = op.Cast(); - // after traversed children, here check whether any distinct group added in children - unordered_map ref_table_columns; - for (idx_t proj_idx = 0; proj_idx < projection.expressions.size(); proj_idx++) { - auto &expression = projection.expressions.get(proj_idx); - if (expression->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { - auto &col_ref = expression->Cast(); - auto distinct_group_it = pipe_info.distinct_groups.find(col_ref.Binding().table_index); - if (distinct_group_it == pipe_info.distinct_groups.end()) { - continue; - } - if (ref_table_columns.find(col_ref.Binding().table_index) == ref_table_columns.end()) { - auto ref = DistinctGroupRef(); - for (auto &col : distinct_group_it->second) { - ref.ref_column_ids.insert(col.column_index); - } - ref_table_columns[col_ref.Binding().table_index] = ref; - } - ref_table_columns[col_ref.Binding().table_index].distinct_group.insert( - ColumnBinding(projection.table_index, ProjectionIndex(proj_idx))); - ref_table_columns[col_ref.Binding().table_index].ref_column_ids.erase(col_ref.Binding().column_index); - } - } - for (auto &refs : ref_table_columns) { - if (refs.second.ref_column_ids.empty()) { - pipe_info.distinct_groups[projection.table_index] = std::move(refs.second.distinct_group); - } +void JoinElimination::OptimizeOperator(unique_ptr &op_ptr, bool replaceable) { + if (op_ptr->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + if (replaceable) { + OptimizeJoin(op_ptr); } - break; + return; } + // only the children of `op` are replaced from here on + auto &op = *op_ptr; + + VisitOperatorExpressions(op); + + // whether the operators above return the same result when rows of the input of `op` are repeated + switch (op.type) { + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + pipe_info.ignores_duplicates = op.Cast().IgnoresDuplicates(); + break; + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_UNNEST: + // these return the rows of a repeated input row once per repeat; a volatile expression is evaluated once per + // repeated row + pipe_info.ignores_duplicates = pipe_info.ignores_duplicates && !AnyVolatile(op); + break; default: - D_ASSERT(op.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN); + // e.g. LIMIT, SAMPLE and windows count the repeated rows + pipe_info.ignores_duplicates = false; break; } -} -unique_ptr JoinElimination::Optimize(unique_ptr op) { - OptimizeInternal(std::move(op)); - if (pipe_info.join_parent || !children.empty()) { - pipe_info.root = TryEliminateJoin(); + if (op.type == LogicalOperatorType::LOGICAL_GET && op.Cast().table_filters.HasFilters()) { + pipe_info.has_filter = true; } - return std::move(pipe_info.root); -} -void JoinElimination::OptimizeInternal(unique_ptr op) { - pipe_info.root = std::move(op); - OptimizeChildren(*pipe_info.root, nullptr, 0); -} - -unique_ptr JoinElimination::TryEliminateJoin() { - D_ASSERT(pipe_info.root); - if (!children.empty()) { - D_ASSERT(!pipe_info.join_parent); - D_ASSERT(children_root); - D_ASSERT(children.size() == children_root->children.size()); - - for (idx_t idx = 0; idx < children.size(); idx++) { - children_root->children[idx] = children[idx]->TryEliminateJoin(); - } - return std::move(pipe_info.root); + if (op.children.size() == 1) { + OptimizeChild(op, 0, *this, true); + return; } - if (!pipe_info.join_parent) { - return std::move(pipe_info.root); + // every child starts a pipeline of its own; a child that is a join stays, its columns may be read by position + for (idx_t child_idx = 0; child_idx < op.children.size(); child_idx++) { + auto child_optimizer = CreateChildren(); + OptimizeChild(op, child_idx, *child_optimizer, false); + removed_joins += child_optimizer->removed_joins; } +} - auto join_parent = pipe_info.join_parent; +unique_ptr JoinElimination::Optimize(unique_ptr op) { + effects = make_shared_ptr(*op); + OptimizeOperator(op, false); + return op; +} - auto &join_op = pipe_info.join_parent->children[pipe_info.join_index]; - join_op->children[0] = left_child->TryEliminateJoin(); - join_op->children[1] = right_child->TryEliminateJoin(); +bool JoinElimination::RemovedJoin() const { + return removed_joins > 0; +} - auto &join = join_op->Cast(); - bool is_output_unique = false; +bool JoinElimination::TryEliminateJoin(unique_ptr &op, JoinElimination &left_child, + JoinElimination &right_child) { + auto &join = op->Cast(); idx_t inner_idx = 1; idx_t outer_idx = 0; switch (join.join_type) { case JoinType::LEFT: - break; - case JoinType::SINGLE: { - is_output_unique = true; + case JoinType::SINGLE: break; case JoinType::RIGHT: inner_idx = 0; outer_idx = 1; break; - } default: - return std::move(pipe_info.root); + return false; } auto &inner_child = inner_idx == 0 ? left_child : right_child; - if (inner_child->pipe_info.has_filter) { - return std::move(pipe_info.root); - } + auto &outer_projection_map = outer_idx == 0 ? join.left_projection_map : join.right_projection_map; if (join.filter_pushdown) { - return std::move(pipe_info.root); + return false; } auto inner_bindings = join.children[inner_idx]->GetColumnBindings(); // ensure join output columns only contains outer table columns for (auto &binding : inner_bindings) { if (pipe_info.ref_table_ids.find(binding.table_index) != pipe_info.ref_table_ids.end()) { - return std::move(pipe_info.root); + return false; } } - - if (inner_idx == 1) { - for (auto &distinct : right_child->pipe_info.distinct_groups) { - pipe_info.distinct_groups[distinct.first] = distinct.second; - } - } else { - for (auto &distinct : left_child->pipe_info.distinct_groups) { - pipe_info.distinct_groups[distinct.first] = distinct.second; - } - } - - if (pipe_info.distinct_groups.empty()) { - return std::move(pipe_info.root); - } - // 1. TODO: guarantee by primary/foreign key - - if (!is_output_unique) { - is_output_unique = true; - // 2. inner table join condition columns contains a whole distinct group - vector col_bindings; - for (auto &condition : join.conditions) { - if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL || - condition.GetLHS().GetExpressionType() != ExpressionType::BOUND_COLUMN_REF || - condition.GetRHS().GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { - is_output_unique = false; - break; - } - auto inner_binding = inner_idx == 0 ? condition.GetLHS().Cast().Binding() - : condition.GetRHS().Cast().Binding(); - col_bindings.push_back(inner_binding); - } - if (is_output_unique && !ContainDistinctGroup(col_bindings)) { - is_output_unique = false; - } - } - if (!is_output_unique) { - // 3. join result columns in join condition contains a whole distinct group - auto outer_bindings = join.children[outer_idx]->GetColumnBindings(); - if (ContainDistinctGroup(outer_bindings)) { - is_output_unique = true; - } - } - - if (is_output_unique) { - join_parent->children[pipe_info.join_index] = std::move(join_op->children[outer_idx]); + // a join condition or an inner side with a volatile expression (nextval, random) stays, whatever is known about + // the join: it has an effect of its own. So does an inner side that modifies data or that reads a materialized + // CTE with such a definition + if (AnyVolatile(join) || effects->HasEffect(*join.children[inner_idx])) { + return false; } - return std::move(pipe_info.root); -} -bool JoinElimination::ContainDistinctGroup(vector &column_bindings) { - D_ASSERT(!column_bindings.empty()); - auto &column_binding = column_bindings[0]; - auto it = pipe_info.distinct_groups.find(column_binding.table_index); - if (it == pipe_info.distinct_groups.end()) { - return false; + bool is_removable = false; + if (pipe_info.ignores_duplicates && join.join_type != JoinType::SINGLE) { + // a) the operators above ignore duplicates: an outer join that nothing reads the inner side of only repeats + // its outer rows, whatever the inner side holds (a SINGLE join raises an error on a second match, so it is + // left to the proof below) + is_removable = true; + } else if (!inner_child.pipe_info.has_filter) { + // b) the inner side is distinct on the columns its equality conditions compare: every outer row finds at + // most one match, so the join returns exactly its outer rows. The other conditions only filter the matches. + // The plan below this join is not rewritten any more, so the unique sets are inferred on a stable plan + column_binding_set_t inner_keys; + Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS); + is_removable = Distinctness::GetJoinEqualityKeys(join, inner_idx, inner_keys) && + distinctness.IsDistinctOn(*join.children[inner_idx], inner_keys); } - unordered_set used_column_ids; - for (auto &binding : column_bindings) { - if (it->second.find(binding) == it->second.end()) { - continue; - } - used_column_ids.emplace(binding.column_index); + if (is_removable) { + op = LogicalJoin::PromoteJoinSide(std::move(join.children[outer_idx]), std::move(outer_projection_map)); } - return used_column_ids.size() == it->second.size(); + return is_removable; } unique_ptr JoinElimination::VisitReplace(BoundColumnRefExpression &expr, unique_ptr *expr_ptr) { diff --git a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp index 158610a82..07759139e 100644 --- a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp +++ b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp @@ -188,7 +188,9 @@ bool JoinFilterPushdownUtil::JoinTypeIsSupported(JoinType join_type) { // cannot generate join filters for these join types // mark/single - cannot change cardinality of probe side // left/outer always need to include every row from probe side - // FIXME: anti/right_anti - we could do this, but need to invert the join conditions + // anti - the probe rows without a match are the result + // right_anti - join filters are generated (see CanGenerateJoinFilters), but the build side optimizer, which + // asks this function as well, does not take them into account return false; default: return true; @@ -744,7 +746,10 @@ static void SimplifyJoinFilterCastChain(ClientContext &context, JoinFilterPushdo } bool JoinFilterPushdownOptimizer::CanGenerateJoinFilters(const LogicalComparisonJoin &join) { - if (!JoinFilterPushdownUtil::JoinTypeIsSupported(join.join_type)) { + // a RIGHT ANTI join emits the build rows without a match: its probe rows only mark build rows as matched. + // a probe row whose key is not in the build side cannot mark anything, so it can be filtered out like for + // a RIGHT SEMI join + if (join.join_type != JoinType::RIGHT_ANTI && !JoinFilterPushdownUtil::JoinTypeIsSupported(join.join_type)) { return false; } for (auto &condition : join.conditions) { diff --git a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp index 0286bcb3a..2c0a0ef4f 100644 --- a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp +++ b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp @@ -14,7 +14,7 @@ struct DomainEstimate { DomainEstimate(); public: - idx_t GetDistinctCount(const JoinPredicate &predicate) const; + double GetDistinctCount(const JoinPredicate &predicate) const; bool HasReliableDistinctCount() const; idx_t GetReliableDistinctCount() const; void Update(ColumnBinding binding, const DistinctCount &distinct_count, @@ -35,7 +35,7 @@ struct DomainEstimate { DomainEstimate::DomainEstimate() { } -idx_t DomainEstimate::GetDistinctCount(const JoinPredicate &predicate) const { +double DomainEstimate::GetDistinctCount(const JoinPredicate &predicate) const { auto domain = estimate; for (bool left : {true, false}) { auto entry = local_fallbacks.find(predicate.GetStatsBinding(left)); @@ -44,11 +44,20 @@ idx_t DomainEstimate::GetDistinctCount(const JoinPredicate &predicate) const { } } if (!domain) { - return NumericLimits::Maximum(); + return static_cast(NumericLimits::Maximum()); } auto result = domain->distinct_count; + auto comparison = predicate.GetComparisonType(); + if (domain->source == DistinctCountSource::CARDINALITY && estimate && result > 0 && + predicate.GetJoinType() == JoinType::INNER && + (comparison == ExpressionType::COMPARE_EQUAL || comparison == ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { + // Discount scan-backed domains before applying predicate-local bounds. + return MinValue(static_cast(result), + MaxValue(1.0, static_cast(estimate->distinct_count) * + RelationStatisticsHelper::DEFAULT_SELECTIVITY)); + } if (!HasReliableDistinctCount() || reliable_source_count != 1) { - return result; + return static_cast(result); } auto key_domain = NumericLimits::Maximum(); for (auto candidate : min_max_candidates) { @@ -56,7 +65,7 @@ idx_t DomainEstimate::GetDistinctCount(const JoinPredicate &predicate) const { key_domain = MinValue(key_domain, candidate); } } - return key_domain == NumericLimits::Maximum() ? result : key_domain; + return static_cast(key_domain == NumericLimits::Maximum() ? result : key_domain); } bool DomainEstimate::HasReliableDistinctCount() const { @@ -142,7 +151,7 @@ struct FilterInfoWithTotalDomains { public: reference predicate; reference domain_estimate; - idx_t distinct_count; + double distinct_count; }; struct SelectivitySubgraph { @@ -214,7 +223,7 @@ CardinalityEstimator::~CardinalityEstimator() { } double FilterInfoWithTotalDomains::GetDistinctCount() const { - return static_cast(distinct_count); + return distinct_count; } bool FilterInfoWithTotalDomains::HasReliableDistinctCount() const { diff --git a/src/duckdb/src/optimizer/join_order/join_order_operator.cpp b/src/duckdb/src/optimizer/join_order/join_order_operator.cpp index c5dca69e6..095dad670 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_operator.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_operator.cpp @@ -1,11 +1,13 @@ #include "duckdb/optimizer/join_order/join_order_operator.hpp" #include "duckdb/common/assert.hpp" +#include "duckdb/common/unordered_set.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_operator_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/expression_nullability.hpp" namespace duckdb { @@ -224,15 +226,106 @@ static void SimplifyConflictRules(JoinOrderOperator &op, JoinRelationSetManager op.right_total_set = set_manager.Intersection(op.total_set, op.right_relations); } +static bool ConditionsHaveEffects(const JoinOrderOperator &op) { + for (auto &condition : op.conditions) { + auto &lhs = condition.IsComparison() ? condition.GetLHS() : condition.GetJoinExpression(); + if (lhs.IsVolatile() || lhs.CanThrow()) { + return true; + } + if (condition.IsComparison() && (condition.GetRHS().IsVolatile() || condition.GetRHS().CanThrow())) { + return true; + } + } + return false; +} + +static bool ConditionsAreIndependent(const JoinOrderOperator &op, JoinRelationSetManager &set_manager, + const unordered_map &relation_mapping) { + if (op.conditions.empty()) { + return false; + } + vector> filtering_children; + for (idx_t side = 0; side < 2; side++) { + const auto &children = side == 0 ? op.left_operators : op.right_operators; + for (auto &child : children) { + if (child.get().type == JoinOrderOperatorType::SEMI || child.get().type == JoinOrderOperatorType::ANTI) { + if (ConditionsHaveEffects(child.get())) { + return false; + } + filtering_children.push_back(child); + } + } + } + if (ConditionsHaveEffects(op)) { + return false; + } + for (auto &condition : op.conditions) { + if (!condition.IsComparison()) { + return false; + } + unordered_set bindings; + bool valid_bindings = true; + auto collect_bindings = [&](const Expression &expression) { + ExpressionIterator::VisitExpression( + expression, [&](const BoundColumnRefExpression &column) { + auto entry = relation_mapping.find(column.Binding().table_index); + if (column.Depth() != 0 || entry == relation_mapping.end()) { + valid_bindings = false; + } else { + bindings.insert(entry->second); + } + }); + for (auto expr_class : {ExpressionClass::BOUND_REF, ExpressionClass::BOUND_SUBQUERY}) { + ExpressionIterator::VisitExpressionClass(expression, expr_class, + [&](const Expression &) { valid_bindings = false; }); + } + }; + collect_bindings(condition.GetLHS()); + collect_bindings(condition.GetRHS()); + if (!valid_bindings || bindings.empty()) { + return false; + } + for (auto &child_ref : filtering_children) { + auto &child = child_ref.get(); + auto &requirement = PredicateIntersectionOrInput(set_manager, child.left_relations, child.syntactic_set); + bool contains_requirement = true; + for (idx_t relation_idx = 0; relation_idx < requirement.count; relation_idx++) { + contains_requirement &= bindings.count(requirement.relations[relation_idx]) != 0; + } + bool touches_child = false; + for (auto binding : bindings) { + touches_child |= + ContainsRelation(child.left_relations, binding) || ContainsRelation(child.right_relations, binding); + } + // External predicates can execute independently of the complete filtering join. + if (!contains_requirement && touches_child) { + return false; + } + } + } + return true; +} + void JoinOrderConflictDetector::Build(vector> &operators, JoinRelationSetManager &set_manager, const unordered_map &relation_mapping) { + bool has_left_join = false; + for (auto &op : operators) { + has_left_join |= op->type == JoinOrderOperatorType::LEFT; + } for (auto &op : operators) { D_ASSERT(!JoinRelationSet::Intersects(op->left_relations, op->right_relations)); BuildConflictRules(*op, set_manager, relation_mapping); - op->must_apply_as_operator = op->type != JoinOrderOperatorType::CROSS_PRODUCT && - (op->type != JoinOrderOperatorType::INNER || !op->conflict_rules.empty()); + auto has_conflicts = !op->conflict_rules.empty(); + // Nullable inputs still require the original operator boundary. + auto can_split_conditions = op->type == JoinOrderOperatorType::INNER && !has_left_join && has_conflicts && + ConditionsAreIndependent(*op, set_manager, relation_mapping); SimplifyConflictRules(*op, set_manager); + can_split_conditions &= + op->conflict_rules.empty() && op->total_set.get().count == op->syntactic_set.get().count; + op->must_apply_as_operator = + op->type != JoinOrderOperatorType::CROSS_PRODUCT && + (op->type != JoinOrderOperatorType::INNER || (has_conflicts && !can_split_conditions)); D_ASSERT(ContainedInUnion(op->total_set, op->left_relations, op->right_relations)); #ifdef D_ASSERT_IS_ENABLED for (auto &rule : op->conflict_rules) { diff --git a/src/duckdb/src/optimizer/join_order/relation_manager.cpp b/src/duckdb/src/optimizer/join_order/relation_manager.cpp index 722f7dbbc..7ffd48bdb 100644 --- a/src/duckdb/src/optimizer/join_order/relation_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/relation_manager.cpp @@ -405,6 +405,16 @@ static bool JoinIsReorderable(LogicalOperator &op) { if (join.HasProjectionMap()) { return false; } + // Keep constant membership filters local instead of expanding the join search. + if (join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI) { + optional_ptr rhs = join.children[1].get(); + while (rhs->type == LogicalOperatorType::LOGICAL_PROJECTION && rhs->children.size() == 1) { + rhs = rhs->children[0].get(); + } + if (rhs->type == LogicalOperatorType::LOGICAL_CHUNK_GET) { + return false; + } + } // Preserve the input rows on which volatile condition operands are evaluated. for (auto &cond : join.conditions) { bool is_volatile = cond.IsComparison() ? cond.GetLHS().IsVolatile() || cond.GetRHS().IsVolatile() diff --git a/src/duckdb/src/optimizer/outer_join_simplification.cpp b/src/duckdb/src/optimizer/join_simplification.cpp similarity index 52% rename from src/duckdb/src/optimizer/outer_join_simplification.cpp rename to src/duckdb/src/optimizer/join_simplification.cpp index 14fa7468d..5375a126f 100644 --- a/src/duckdb/src/optimizer/outer_join_simplification.cpp +++ b/src/duckdb/src/optimizer/join_simplification.cpp @@ -1,5 +1,6 @@ -#include "duckdb/optimizer/outer_join_simplification.hpp" +#include "duckdb/optimizer/join_simplification.hpp" +#include "duckdb/optimizer/join_to_semi_join.hpp" #include "duckdb/planner/operator/list.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" @@ -8,6 +9,7 @@ #include "duckdb/planner/expression/bound_operator_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" namespace duckdb { @@ -15,18 +17,84 @@ namespace duckdb { // Setup //===--------------------------------------------------------------------===// -OuterJoinSimplification::OuterJoinSimplification() { +JoinSimplification::JoinSimplification(ClientContext &context, JoinSimplificationPhase phase_p) : phase(phase_p) { + if (phase == JoinSimplificationPhase::BEFORE_FILTER_PUSHDOWN) { + owned_join_to_semi_join = make_uniq(context); + join_to_semi_join = owned_join_to_semi_join.get(); + } +} + +JoinSimplification::JoinSimplification(JoinSimplification &parent_context, column_binding_set_t required_columns_p) + : phase(parent_context.phase), join_to_semi_join(parent_context.join_to_semi_join), + required_columns(std::move(required_columns_p)), initialized_required_columns(true) { } -OuterJoinSimplification::OuterJoinSimplification(column_binding_set_t required_columns_p) - : required_columns(std::move(required_columns_p)), initialized_required_columns(true) { +JoinSimplification::~JoinSimplification() { +} + +void JoinSimplification::Optimize(unique_ptr &plan) { + if (join_to_semi_join) { + join_to_semi_join->Initialize(*plan); + } + VisitOperator(plan); +} + +//===--------------------------------------------------------------------===// +// Parent Info +//===--------------------------------------------------------------------===// + +JoinSimplification::ParentInfo JoinSimplification::UnknownInfo() { + return ParentInfo(); +} + +JoinSimplification::ParentInfo JoinSimplification::PassThroughInfo(const LogicalOperator &op, + bool ignores_duplicates) const { + ParentInfo info; + info.ignores_duplicates = ignores_duplicates; + info.reads_known = parent.reads_known; + if (parent.reads_known) { + info.read_tables = parent.read_tables; + JoinToSemiJoin::AddReadTables(op, info.read_tables); + } + info.in_region = JoinToSemiJoin::IsRegionNode(op); + return info; +} + +//! Visits `op.children[child_index]` through `visit`; a projection map `op` holds for the child is remapped to the +//! child's bindings afterwards, as LogicalOperatorVisitor does +template +static void VisitChildWithProjectionMap(LogicalOperator &op, idx_t child_index, const VISIT &visit) { + auto &child = op.children[child_index]; + auto projection_map = LogicalOperatorVisitor::GetProjectionMap(op, child_index); + if (!projection_map) { + visit(child); + return; + } + const auto child_bindings_before = child->GetColumnBindings(); + visit(child); + LogicalOperatorVisitor::RemapProjectionMap(*projection_map, child_bindings_before, child->GetColumnBindings()); +} + +void JoinSimplification::VisitChild(LogicalOperator &op, idx_t child_index, ParentInfo info) { + auto saved = std::move(parent); + parent = std::move(info); + VisitChildWithProjectionMap(op, child_index, [&](unique_ptr &child) { VisitOperator(child); }); + parent = std::move(saved); +} + +void JoinSimplification::VisitChildInNewContext(LogicalOperator &op, idx_t child_index, + column_binding_set_t child_required_columns, ParentInfo info) { + JoinSimplification child_simplification(*this, std::move(child_required_columns)); + child_simplification.parent = std::move(info); + VisitChildWithProjectionMap(op, child_index, + [&](unique_ptr &child) { child_simplification.VisitOperator(child); }); } //===--------------------------------------------------------------------===// // Column Binding Helpers //===--------------------------------------------------------------------===// -void OuterJoinSimplification::AddColumnReferences(const Expression &expr, column_binding_set_t &bindings) { +void JoinSimplification::AddColumnReferences(const Expression &expr, column_binding_set_t &bindings) { ExpressionIterator::VisitExpression(expr, [&](const BoundColumnRefExpression &colref) { if (colref.Depth() == 0) { bindings.insert(colref.Binding()); @@ -34,11 +102,11 @@ void OuterJoinSimplification::AddColumnReferences(const Expression &expr, column }); } -void OuterJoinSimplification::AddRequiredColumns(const Expression &expr) { +void JoinSimplification::AddRequiredColumns(const Expression &expr) { AddColumnReferences(expr, required_columns); } -void OuterJoinSimplification::AddRequiredColumns(const JoinCondition &condition) { +void JoinSimplification::AddRequiredColumns(const JoinCondition &condition) { if (condition.IsComparison()) { AddRequiredColumns(condition.GetLHS()); AddRequiredColumns(condition.GetRHS()); @@ -47,13 +115,13 @@ void OuterJoinSimplification::AddRequiredColumns(const JoinCondition &condition) } } -void OuterJoinSimplification::AddRequiredColumns(const vector &conditions) { +void JoinSimplification::AddRequiredColumns(const vector &conditions) { for (const auto &condition : conditions) { AddRequiredColumns(condition); } } -bool OuterJoinSimplification::GetColumnBinding(const Expression &expr, ColumnBinding &binding) { +bool JoinSimplification::GetColumnBinding(const Expression &expr, ColumnBinding &binding) { if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { if (!BoundCastExpression::IsCast(expr)) { return false; @@ -66,7 +134,7 @@ bool OuterJoinSimplification::GetColumnBinding(const Expression &expr, ColumnBin return true; } -bool OuterJoinSimplification::GetNullPreservingColumnBinding(const Expression &expr, ColumnBinding &binding) { +bool JoinSimplification::GetNullPreservingColumnBinding(const Expression &expr, ColumnBinding &binding) { if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { if (!BoundCastExpression::IsCast(expr)) { return false; @@ -87,14 +155,14 @@ bool OuterJoinSimplification::GetNullPreservingColumnBinding(const Expression &e // NULL Constraint Tracking //===--------------------------------------------------------------------===// -void OuterJoinSimplification::HandleExpression(const Expression &expr) { +void JoinSimplification::HandleExpression(const Expression &expr) { ColumnBinding binding; if (GetColumnBinding(expr, binding)) { null_filtered_columns.insert(binding); } } -void OuterJoinSimplification::HandleFilterExpression(const Expression &expr) { +void JoinSimplification::HandleFilterExpression(const Expression &expr) { if (expr.GetExpressionClass() == ExpressionClass::BOUND_OPERATOR && expr.GetExpressionType() == ExpressionType::OPERATOR_IS_NOT_NULL) { const auto &is_not_null = expr.Cast(); @@ -126,7 +194,7 @@ void OuterJoinSimplification::HandleFilterExpression(const Expression &expr) { HandleExpression(BoundComparisonExpression::Right(comparison)); } -bool OuterJoinSimplification::HandleIsNullExpression(const Expression &expr) { +bool JoinSimplification::HandleIsNullExpression(const Expression &expr) { ColumnBinding binding; if (GetNullPreservingColumnBinding(expr, binding)) { null_required_columns.insert(binding); @@ -135,7 +203,7 @@ bool OuterJoinSimplification::HandleIsNullExpression(const Expression &expr) { return false; } -bool OuterJoinSimplification::IsNullFilter(const Expression &expr, ColumnBinding &binding) { +bool JoinSimplification::IsNullFilter(const Expression &expr, ColumnBinding &binding) { if (expr.GetExpressionClass() != ExpressionClass::BOUND_OPERATOR || expr.GetExpressionType() != ExpressionType::OPERATOR_IS_NULL) { return false; @@ -145,7 +213,7 @@ bool OuterJoinSimplification::IsNullFilter(const Expression &expr, ColumnBinding return GetNullPreservingColumnBinding(child, binding); } -void OuterJoinSimplification::InitializeRequiredColumns(LogicalOperator &op) { +void JoinSimplification::InitializeRequiredColumns(LogicalOperator &op) { if (initialized_required_columns) { return; } @@ -155,7 +223,7 @@ void OuterJoinSimplification::InitializeRequiredColumns(LogicalOperator &op) { initialized_required_columns = true; } -bool OuterJoinSimplification::FiltersNulls(ExpressionType comparison_type) { +bool JoinSimplification::FiltersNulls(ExpressionType comparison_type) { return comparison_type != ExpressionType::COMPARE_DISTINCT_FROM && comparison_type != ExpressionType::COMPARE_NOT_DISTINCT_FROM; } @@ -164,11 +232,11 @@ bool OuterJoinSimplification::FiltersNulls(ExpressionType comparison_type) { // Join Rewrite Helpers //===--------------------------------------------------------------------===// -vector OuterJoinSimplification::GetRightBindings(LogicalJoin &join) { +vector JoinSimplification::GetRightBindings(LogicalJoin &join) { return LogicalOperator::MapBindings(join.children[1]->GetColumnBindings(), join.right_projection_map); } -bool OuterJoinSimplification::HasNullRequiredColumns(const vector &bindings) { +bool JoinSimplification::HasNullRequiredColumns(const vector &bindings) { for (const auto &binding : bindings) { if (null_required_columns.find(binding) != null_required_columns.end()) { return true; @@ -177,7 +245,7 @@ bool OuterJoinSimplification::HasNullRequiredColumns(const vector return false; } -bool OuterJoinSimplification::HasRequiredColumns(const vector &bindings) { +bool JoinSimplification::HasRequiredColumns(const vector &bindings) { for (const auto &binding : bindings) { if (required_columns.find(binding) != required_columns.end()) { return true; @@ -186,19 +254,19 @@ bool OuterJoinSimplification::HasRequiredColumns(const vector &bi return false; } -void OuterJoinSimplification::EraseNullRequiredColumns(LogicalOperator &child) { +void JoinSimplification::EraseNullRequiredColumns(LogicalOperator &child) { for (const auto &binding : child.GetColumnBindings()) { null_required_columns.erase(binding); } } -void OuterJoinSimplification::MarkEliminatedNullColumns(const vector &bindings) { +void JoinSimplification::MarkEliminatedNullColumns(const vector &bindings) { for (const auto &binding : bindings) { eliminated_null_columns.insert(binding); } } -bool OuterJoinSimplification::TryConvertLeftToAntiJoin(LogicalComparisonJoin &join) { +bool JoinSimplification::TryConvertLeftToAntiJoin(LogicalComparisonJoin &join) { if (join.join_type != JoinType::LEFT) { return false; } @@ -233,7 +301,7 @@ bool OuterJoinSimplification::TryConvertLeftToAntiJoin(LogicalComparisonJoin &jo return false; } -void OuterJoinSimplification::SimplifyOuterJoinType(LogicalComparisonJoin &join) { +void JoinSimplification::SimplifyOuterJoinType(LogicalComparisonJoin &join) { bool preserves_null_extended_rows[2] = {join.join_type == JoinType::LEFT || join.join_type == JoinType::OUTER, join.join_type == JoinType::RIGHT || join.join_type == JoinType::OUTER}; for (idx_t child_idx = 0; child_idx < 2; child_idx++) { @@ -267,24 +335,77 @@ void OuterJoinSimplification::SimplifyOuterJoinType(LogicalComparisonJoin &join) // Operator Visitors //===--------------------------------------------------------------------===// -void OuterJoinSimplification::VisitComparisonJoin(LogicalComparisonJoin &join, LogicalOperator &op) { +//! Which children of a join of this type may see repeated rows of their input without a change of the result of a +//! parent that ignores duplicates (`ignores`): the rows INNER and outer joins emit, as a set, depend on their inputs +//! as sets only, and the right side of a SEMI, ANTI or MARK join only says whether a match exists +static void JoinSidesIgnoreDuplicates(JoinType join_type, bool ignores, bool &left, bool &right) { + left = false; + right = false; + switch (join_type) { + case JoinType::INNER: + case JoinType::LEFT: + case JoinType::RIGHT: + case JoinType::OUTER: + left = right = ignores; + break; + case JoinType::SEMI: + case JoinType::ANTI: + case JoinType::MARK: + left = ignores; + right = true; + break; + case JoinType::RIGHT_SEMI: + case JoinType::RIGHT_ANTI: + left = true; + right = ignores; + break; + default: + break; + } +} + +void JoinSimplification::VisitJoinChildren(LogicalOperator &op, bool left_ignores_duplicates, + bool right_ignores_duplicates, bool keep_context) { + const bool deterministic = !JoinToSemiJoin::HasVolatileExpression(op); + auto left_info = PassThroughInfo(op, left_ignores_duplicates && deterministic); + auto right_info = PassThroughInfo(op, right_ignores_duplicates && deterministic); + if (keep_context) { + VisitChild(op, 0, std::move(left_info)); + VisitChild(op, 1, std::move(right_info)); + return; + } + // the column sets do not pass through this join: each child starts with all of its columns required + for (idx_t child_idx = 0; child_idx < 2; child_idx++) { + column_binding_set_t child_required_columns; + for (const auto &binding : op.children[child_idx]->GetColumnBindings()) { + child_required_columns.insert(binding); + } + VisitChildInNewContext(op, child_idx, std::move(child_required_columns), + child_idx == 0 ? std::move(left_info) : std::move(right_info)); + } +} + +void JoinSimplification::VisitComparisonJoin(LogicalComparisonJoin &join, unique_ptr &op_ptr) { switch (join.join_type) { case JoinType::INNER: case JoinType::SEMI: - VisitInnerOrSemiJoin(join, op); + VisitInnerOrSemiJoin(join, *op_ptr); return; case JoinType::LEFT: case JoinType::RIGHT: case JoinType::OUTER: - VisitOuterJoin(join, op); + VisitOuterJoin(join, op_ptr); return; default: break; } - VisitUnsupportedOperator(op); + bool left; + bool right; + JoinSidesIgnoreDuplicates(join.join_type, parent.ignores_duplicates, left, right); + VisitJoinChildren(*op_ptr, left, right, false); } -void OuterJoinSimplification::VisitInnerOrSemiJoin(LogicalComparisonJoin &join, LogicalOperator &op) { +void JoinSimplification::VisitInnerOrSemiJoin(LogicalComparisonJoin &join, LogicalOperator &op) { for (const auto &condition : join.conditions) { if (!condition.IsComparison()) { continue; @@ -296,24 +417,33 @@ void OuterJoinSimplification::VisitInnerOrSemiJoin(LogicalComparisonJoin &join, HandleExpression(condition.GetLHS()); HandleExpression(condition.GetRHS()); } - VisitOperatorChildren(op); + bool left; + bool right; + JoinSidesIgnoreDuplicates(join.join_type, parent.ignores_duplicates, left, right); + VisitJoinChildren(op, left, right, true); } -void OuterJoinSimplification::VisitOuterJoin(LogicalComparisonJoin &join, LogicalOperator &op) { - if (TryConvertLeftToAntiJoin(join)) { +void JoinSimplification::VisitOuterJoin(LogicalComparisonJoin &join, unique_ptr &op_ptr) { + auto &op = *op_ptr; + bool left; + bool right; + if (SimplifiesOuterJoins() && TryConvertLeftToAntiJoin(join)) { auto right_bindings = GetRightBindings(join); AddRequiredColumns(join.conditions); EraseNullRequiredColumns(*join.children[1]); - VisitOperatorChildren(op); + JoinSidesIgnoreDuplicates(join.join_type, parent.ignores_duplicates, left, right); + VisitJoinChildren(op, left, right, true); // only operators above the join see the right side as NULL, not the right child itself MarkEliminatedNullColumns(right_bindings); return; } - SimplifyOuterJoinType(join); - if (join.join_type == JoinType::INNER) { - VisitOperator(op); - return; + if (SimplifiesOuterJoins()) { + SimplifyOuterJoinType(join); + if (join.join_type == JoinType::INNER) { + VisitInnerOrSemiJoin(join, op); + return; + } } AddRequiredColumns(join.conditions); @@ -325,10 +455,11 @@ void OuterJoinSimplification::VisitOuterJoin(LogicalComparisonJoin &join, Logica if (join.join_type == JoinType::RIGHT || join.join_type == JoinType::OUTER) { EraseNullRequiredColumns(*join.children[0]); } - VisitOperatorChildren(op); + JoinSidesIgnoreDuplicates(join.join_type, parent.ignores_duplicates, left, right); + VisitJoinChildren(op, left, right, true); } -void OuterJoinSimplification::VisitProjection(LogicalProjection &projection, LogicalOperator &op) { +void JoinSimplification::VisitProjection(LogicalProjection &projection, LogicalOperator &op) { vector> direct_projection_map; for (idx_t col_idx = 0; col_idx < projection.expressions.size(); col_idx++) { auto &expr = *projection.expressions[col_idx]; @@ -347,7 +478,12 @@ void OuterJoinSimplification::VisitProjection(LogicalProjection &projection, Log null_required_columns.insert(input_binding); } } - VisitOperatorChildren(op); + // everything above reads the columns the projection computes, not the columns below it + ParentInfo info; + info.ignores_duplicates = parent.ignores_duplicates && !JoinToSemiJoin::HasVolatileExpression(op); + info.reads_known = true; + JoinToSemiJoin::AddReadTables(op, info.read_tables); + VisitChild(op, 0, std::move(info)); for (const auto &entry : direct_projection_map) { auto col_idx = entry.first; @@ -362,12 +498,15 @@ void OuterJoinSimplification::VisitProjection(LogicalProjection &projection, Log } } -void OuterJoinSimplification::VisitFilter(LogicalFilter &filter, LogicalOperator &op) { - filter.SplitPredicates(filter.expressions); +void JoinSimplification::VisitFilter(LogicalFilter &filter, LogicalOperator &op) { + if (SimplifiesOuterJoins()) { + // before filter pushdown the filters stay as the region rewrite collected them + filter.SplitPredicates(filter.expressions); + } for (const auto &expr : filter.expressions) { HandleFilterExpression(*expr); } - VisitOperatorChildren(op); + VisitChild(op, 0, PassThroughInfo(op, parent.ignores_duplicates && !JoinToSemiJoin::HasVolatileExpression(op))); for (idx_t i = 0; i < filter.expressions.size(); i++) { ColumnBinding binding; @@ -382,22 +521,21 @@ void OuterJoinSimplification::VisitFilter(LogicalFilter &filter, LogicalOperator } } -void OuterJoinSimplification::VisitOrder(LogicalOrder &order, LogicalOperator &op) { +void JoinSimplification::VisitOrder(LogicalOrder &order, LogicalOperator &op) { for (const auto &order_node : order.orders) { AddRequiredColumns(*order_node.expression); } - VisitOperatorChildren(op); + VisitChild(op, 0, UnknownInfo()); } -void OuterJoinSimplification::VisitTopN(LogicalTopN &top_n, LogicalOperator &op) { +void JoinSimplification::VisitTopN(LogicalTopN &top_n, LogicalOperator &op) { for (const auto &order_node : top_n.orders) { AddRequiredColumns(*order_node.expression); } - OuterJoinSimplification child_simplification(required_columns); - child_simplification.VisitOperator(*op.children[0]); + VisitChildInNewContext(op, 0, required_columns, UnknownInfo()); } -void OuterJoinSimplification::VisitAggregate(LogicalAggregate &aggregate, LogicalOperator &op) { +void JoinSimplification::VisitAggregate(LogicalAggregate &aggregate, LogicalOperator &op) { column_binding_set_t child_required_columns; for (const auto &expr : aggregate.groups) { AddColumnReferences(*expr, child_required_columns); @@ -405,28 +543,53 @@ void OuterJoinSimplification::VisitAggregate(LogicalAggregate &aggregate, Logica for (const auto &expr : aggregate.expressions) { AddColumnReferences(*expr, child_required_columns); } - OuterJoinSimplification child_simplification(std::move(child_required_columns)); - child_simplification.VisitOperator(*op.children[0]); + // everything above reads the columns the aggregate computes, not the columns below it + ParentInfo info; + info.ignores_duplicates = aggregate.IgnoresDuplicates(); + info.reads_known = true; + JoinToSemiJoin::AddReadTables(op, info.read_tables); + VisitChildInNewContext(op, 0, std::move(child_required_columns), std::move(info)); } -void OuterJoinSimplification::VisitUnsupportedOperator(LogicalOperator &op) { - for (auto &child : op.children) { +void JoinSimplification::VisitUnsupportedOperator(LogicalOperator &op) { + if (join_to_semi_join && op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + join_to_semi_join->VisitMaterializedCTE(op); + } + // these read their children's columns by position, or hold references this traversal does not follow + for (idx_t child_idx = 0; child_idx < op.children.size(); child_idx++) { column_binding_set_t child_required_columns; - for (const auto &binding : child->GetColumnBindings()) { + for (const auto &binding : op.children[child_idx]->GetColumnBindings()) { child_required_columns.insert(binding); } - OuterJoinSimplification outer_join_simplification(std::move(child_required_columns)); - outer_join_simplification.VisitOperator(*child); + VisitChildInNewContext(op, child_idx, std::move(child_required_columns), UnknownInfo()); } } -void OuterJoinSimplification::VisitOperator(LogicalOperator &op) { +void JoinSimplification::VisitOperator(unique_ptr &op_ptr) { + if (join_to_semi_join && !parent.in_region && parent.reads_known) { + // the root of a region of filters, cross products and INNER joins + while (JoinToSemiJoin::IsRegionNode(*op_ptr) && + join_to_semi_join->RewriteRegion(op_ptr, parent.ignores_duplicates, parent.read_tables)) { + } + } + auto &op = *op_ptr; InitializeRequiredColumns(op); switch (op.type) { case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { auto &join = op.Cast(); - VisitComparisonJoin(join, op); + VisitComparisonJoin(join, op_ptr); + return; + } + case LogicalOperatorType::LOGICAL_ANY_JOIN: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: { + // the column sets do not pass through these, the rest does + bool left = parent.ignores_duplicates; + bool right = parent.ignores_duplicates; + if (op.type == LogicalOperatorType::LOGICAL_ANY_JOIN) { + JoinSidesIgnoreDuplicates(op.Cast().join_type, parent.ignores_duplicates, left, right); + } + VisitJoinChildren(op, left, right, false); return; } case LogicalOperatorType::LOGICAL_PROJECTION: { @@ -450,8 +613,7 @@ void OuterJoinSimplification::VisitOperator(LogicalOperator &op) { return; } case LogicalOperatorType::LOGICAL_LIMIT: { - OuterJoinSimplification child_simplification(required_columns); - child_simplification.VisitOperator(*op.children[0]); + VisitChildInNewContext(op, 0, required_columns, UnknownInfo()); return; } case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { diff --git a/src/duckdb/src/optimizer/join_to_semi_join.cpp b/src/duckdb/src/optimizer/join_to_semi_join.cpp new file mode 100644 index 000000000..fbc964926 --- /dev/null +++ b/src/duckdb/src/optimizer/join_to_semi_join.cpp @@ -0,0 +1,697 @@ +// An INNER join against a relation that is only read by predicates becomes a SEMI join on the one relation those +// predicates compare it with. +// +// SELECT DISTINCT f.k FROM f, d, p WHERE f.dk = d.dk AND d.x > p.lo +// +// `p` contributes no column: it only says which rows of `d` qualify, and it repeats every qualifying row once per +// matching row of `p`. The join order keeps a relation without an equality predicate for last, so the predicate runs +// over (f JOIN d) x p. As `d SEMI JOIN p ON d.x > p.lo` it filters `d` before the join with `f` and +// repeats nothing. +// +// JoinSimplification calls this for every region it reaches in its first phase, with what it knows about the operators +// above: whether they ignore duplicates and which tables they read. +// +// What must hold, in the plan as bound (the rewrite runs before filter pushdown, which then pushes the remaining +// filters below the new join): a region of filters, cross products and INNER joins below a projection or an +// aggregate, and in it a relation R such that +// - no operator above the region reads a column of R: its columns occur in predicates of the region only; +// - every predicate that reads R reads, besides R, columns of one other relation L of the region, and at least one +// does; none of them holds an equality (an equality join is a hash join the join order places well, and its build +// side feeds runtime filters; an OR of equalities is the disjunctive join rewrite's); +// - no expression of the region is volatile or can throw, neither a predicate nor an expression inside one of its +// relations (or the definition of a CTE read there): a volatile one would be evaluated on fewer rows, and one +// that can throw (a cast that can fail, arithmetic that can overflow) on other rows than before, because the +// SEMI join changes which joins of the region run first and which relations are read to the end. That is within +// what the join order may do anyway, but a query that ran must not start to fail because of this rewrite, nor +// the other way round. For the same reason no relation of the region does more than return rows: none modifies +// data (an INSERT, UPDATE, DELETE or MERGE INTO read through a CTE) and none scans a table function that declares +// itself VOLATILE (duckdb_memory(), glob()). The SEMI join reads such a relation once in full, as the INNER join +// did, so the rewrite changes neither its effects nor its rows; it is left alone all the same, as join elimination +// leaves it, so that what a query does besides returning rows never depends on this rewrite; +// - repeats of the region's rows do not matter: the parent chain ignores duplicates (a GROUP BY whose aggregates +// ignore them, LogicalAggregate::IgnoresDuplicates: min, max, bool_and, bool_or and DISTINCT ones; a DISTINCT; the +// right side of a SEMI / ANTI / MARK join, through projections, filters and joins without volatile expressions), or R +// holds exactly one row (a projection over a dummy scan) and the region has a third relation (with L and R alone the +// SEMI join would sit where the INNER join sits); +// - the SEMI join is not slower than the join it replaces. What the two are depends on the predicates between L and +// R, split into their conjuncts (a BETWEEN is two range comparisons): +// * none is a comparison of an expression over L with one over R: the INNER join is a cross product with a filter +// or a blockwise nested-loop join, and so is the SEMI join, which emits less; +// * one comparison and nothing else, against an R that may hold several rows: the same range or nested-loop +// join either way; a single range comparison may also swap its sides to build the smaller relation and keep +// the runtime filter on the scan of the larger one, as the INNER join does; +// * anything else: no rewrite. Two or more comparisons, a comparison next to another predicate, or a comparison +// against an R known to hold at most one row (an ungrouped aggregate, a LIMIT 1) make the INNER join a range or +// nested-loop join whose build side feeds runtime filters into the scan of L. The SEMI join would be a blockwise +// or nested-loop join that compares every row of L with every row of R without those filters (an IE join only +// for two range comparisons in a plan without materialized or recursive CTEs, which later optimizers may still +// add): orders of magnitude slower on a large L. Taking such a SEMI join where it pays off needs the join +// algorithm and the lost runtime filters costed. +// +// Then L becomes `L SEMI JOIN R ON ` and R leaves the region. The rows of the region +// are, as a set, the rows of the region without R whose L row has a match in R, which is what the SEMI join keeps; +// with a one-row R every such row occurs exactly once in both. +#include "duckdb/optimizer/join_to_semi_join.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_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_any_join.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_cross_product.hpp" +#include "duckdb/planner/operator/logical_cte.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_limit.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" +#include "duckdb/planner/operator/logical_top_n.hpp" + +namespace duckdb { + +class JoinRegionRewriter { +public: + using table_set_t = unordered_set; + + explicit JoinRegionRewriter(ClientContext &context) : context(context) { + } + + void Initialize(LogicalOperator &plan) { + // the CTEs whose definition is unstable (IsUnstable), directly or through another CTE: a fixpoint, a + // definition may read a CTE that is found later + vector> ctes; + CollectCTEs(plan, ctes); + for (bool changed = true; changed;) { + changed = false; + for (auto &cte : ctes) { + auto &op = cte.get(); + auto index = op.Cast().table_index; + if (unstable_ctes.count(index) > 0) { + continue; + } + // a recursive CTE runs both of its children once per iteration + const bool recursive = op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE; + if (IsUnstable(*op.children[0]) || (recursive && IsUnstable(*op.children[1]))) { + unstable_ctes.insert(index); + changed = true; + } + } + } + } + + //! Notes a materialized CTE whose definition holds at most one row; the traversal calls this before it visits + //! the references + void VisitMaterializedCTE(const LogicalOperator &op) { + if (HoldsAtMostOneRow(*op.children[0])) { + single_row_ctes.insert(op.Cast().table_index); + } + } + + //! A relation of the region + struct Leaf { + //! The child indexes that lead from the root of the region to the relation + vector path; + table_set_t tables; + bool one_row; + bool at_most_one_row; + //! Whether the relation is unstable (IsUnstable) + bool unstable; + }; + + //! Where a predicate of the region lives in its operator + enum class PredicateSlot : uint8_t { FILTER_EXPRESSION, JOIN_CONDITION, ANY_JOIN_CONDITION }; + + //! A predicate of the region + struct Predicate { + //! The child indexes that lead from the root of the region to the operator that holds the predicate + vector path; + PredicateSlot slot; + //! The position among the expressions of the filter / the conditions of the join + idx_t index; + table_set_t tables; + bool is_volatile; + bool can_throw; + bool equality; + //! The predicate, or for a comparison condition of a join its two sides + optional_ptr expression; + optional_ptr lhs; + optional_ptr rhs; + ExpressionType comparison_type = ExpressionType::INVALID; + }; + + //! The conjuncts of the predicates between two relations, by what a join can do with them + struct PredicateShape { + //! <, <=, >, >= between an expression over one relation and an expression over the other + idx_t range_comparisons = 0; + //! <>, IS [NOT] DISTINCT FROM between an expression over one relation and an expression over the other + idx_t other_comparisons = 0; + //! Anything else + idx_t other_predicates = 0; + }; + + //! `semi_leaf` gets a SEMI join against `removed_leaf` on `predicates` + struct Rewrite { + idx_t removed_leaf; + idx_t semi_leaf; + vector predicates; + }; + +public: + static void ExpressionTables(const Expression &expr, table_set_t &tables) { + ExpressionIterator::VisitExpression( + expr, [&](const BoundColumnRefExpression &colref) { tables.insert(colref.Binding().table_index); }); + } + + //! The tables the expressions of `op` read + static void OperatorTables(const LogicalOperator &op, table_set_t &tables) { + LogicalOperatorVisitor::EnumerateExpressions( + op, [&](const unique_ptr *expr) { ExpressionTables(**expr, tables); }); + } + + static bool HasVolatileExpression(const LogicalOperator &op) { + bool result = false; + LogicalOperatorVisitor::EnumerateExpressions( + op, [&](const unique_ptr *expr) { result = result || (*expr)->IsVolatile(); }); + return result; + } + + static bool IsEquality(ExpressionType type) { + return type == ExpressionType::COMPARE_EQUAL || type == ExpressionType::COMPARE_NOT_DISTINCT_FROM; + } + + static bool Intersects(const table_set_t &a, const table_set_t &b) { + for (auto &table : a) { + if (b.count(table) > 0) { + return true; + } + } + return false; + } + + static bool Subset(const table_set_t &a, const table_set_t &b) { + for (auto &table : a) { + if (b.count(table) == 0) { + return false; + } + } + return true; + } + + static bool IsRangeComparison(ExpressionType type) { + switch (type) { + case ExpressionType::COMPARE_LESSTHAN: + case ExpressionType::COMPARE_GREATERTHAN: + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + return true; + default: + return false; + } + } + + //! Whether one of the two expressions reads `tables` only and the other does not read them: the two sides of a + //! join condition + static bool OnOppositeSides(const Expression &a, const Expression &b, const table_set_t &tables) { + table_set_t a_tables; + table_set_t b_tables; + ExpressionTables(a, a_tables); + ExpressionTables(b, b_tables); + if (a_tables.empty() || b_tables.empty()) { + return false; + } + const bool a_inside = Subset(a_tables, tables); + const bool b_inside = Subset(b_tables, tables); + return (a_inside && !Intersects(b_tables, tables)) || (b_inside && !Intersects(a_tables, tables)); + } + + static void AddComparison(ExpressionType type, const Expression &lhs, const Expression &rhs, + const table_set_t &tables, PredicateShape &shape) { + if (!OnOppositeSides(lhs, rhs, tables)) { + shape.other_predicates++; + } else if (IsRangeComparison(type)) { + shape.range_comparisons++; + } else { + shape.other_comparisons++; + } + } + + //! Adds the conjuncts of `expr`, a predicate between the relation of `tables` and another one, to `shape` + static void AddPredicate(const Expression &expr, const table_set_t &tables, PredicateShape &shape) { + switch (expr.GetExpressionType()) { + case ExpressionType::CONJUNCTION_AND: + for (auto &child : expr.Cast().GetChildren()) { + AddPredicate(*child, tables, shape); + } + return; + case ExpressionType::COMPARE_BETWEEN: { + auto &between = expr.Cast(); + auto &input = BoundBetweenExpression::Input(between); + AddComparison(ExpressionType::COMPARE_GREATERTHANOREQUALTO, input, + BoundBetweenExpression::LowerBound(between), tables, shape); + AddComparison(ExpressionType::COMPARE_LESSTHANOREQUALTO, input, BoundBetweenExpression::UpperBound(between), + tables, shape); + return; + } + default: + break; + } + if (BoundComparisonExpression::IsComparison(expr)) { + auto &comparison = expr.Cast(); + AddComparison(expr.GetExpressionType(), BoundComparisonExpression::Left(comparison), + BoundComparisonExpression::Right(comparison), tables, shape); + return; + } + shape.other_predicates++; + } + + //! Whether `expr` holds an equality anywhere + static bool HasEquality(const Expression &expr) { + if (IsEquality(expr.GetExpressionType())) { + return true; + } + bool result = false; + ExpressionIterator::EnumerateChildren(expr, + [&](const Expression &child) { result = result || HasEquality(child); }); + return result; + } + + //! A node of a join region: a filter, a cross product or a plain INNER join + static bool IsRegionNode(const LogicalOperator &op) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_FILTER: + return !op.HasProjectionMap(); + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + return true; + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { + auto &join = op.Cast(); + return join.join_type == JoinType::INNER && !join.HasProjectionMap() && !join.filter_pushdown && + join.duplicate_eliminated_columns.empty(); + } + case LogicalOperatorType::LOGICAL_ANY_JOIN: { + auto &join = op.Cast(); + return join.join_type == JoinType::INNER && !join.HasProjectionMap(); + } + default: + return false; + } + } + + //! Exactly one row: projections over a dummy scan + static bool HoldsOneRow(const LogicalOperator &op) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_DUMMY_SCAN: + return true; + case LogicalOperatorType::LOGICAL_PROJECTION: + return op.children.size() == 1 && HoldsOneRow(*op.children[0]); + default: + return false; + } + } + + //! At most one row: exactly one, an ungrouped aggregate, a LIMIT 1, a reference to such a CTE; through + //! projections and filters + bool HoldsAtMostOneRow(const LogicalOperator &op) const { + switch (op.type) { + case LogicalOperatorType::LOGICAL_DUMMY_SCAN: + return true; + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &aggregate = op.Cast(); + return aggregate.groups.empty() && aggregate.grouping_sets.size() <= 1; + } + case LogicalOperatorType::LOGICAL_LIMIT: { + auto &limit = op.Cast().limit_val; + return limit.Type() == LimitNodeType::CONSTANT_VALUE && limit.GetConstantValue() <= 1; + } + case LogicalOperatorType::LOGICAL_TOP_N: + return op.Cast().limit <= 1; + case LogicalOperatorType::LOGICAL_CTE_REF: + return single_row_ctes.count(op.Cast().cte_index) > 0; + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_FILTER: + return op.children.size() == 1 && HoldsAtMostOneRow(*op.children[0]); + default: + return false; + } + } + + static void CollectCTEs(LogicalOperator &op, vector> &ctes) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || + op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + ctes.push_back(op); + } + for (auto &child : op.children) { + CollectCTEs(*child, ctes); + } + } + + //! Whether evaluating `op` does more than return rows, or may fail: an expression of it or below it, or of the + //! definition of a CTE read there, is volatile or can throw; an operator modifies data; a scan runs a table + //! function that declares itself VOLATILE + bool IsUnstable(const LogicalOperator &op) const { + switch (op.type) { + case LogicalOperatorType::LOGICAL_CTE_REF: + if (unstable_ctes.count(op.Cast().cte_index) > 0) { + return true; + } + break; + case LogicalOperatorType::LOGICAL_GET: + if (op.Cast().function.stability == FunctionStability::VOLATILE) { + return true; + } + break; + case LogicalOperatorType::LOGICAL_INSERT: + case LogicalOperatorType::LOGICAL_DELETE: + case LogicalOperatorType::LOGICAL_UPDATE: + case LogicalOperatorType::LOGICAL_MERGE_INTO: + return true; + default: + break; + } + bool result = false; + LogicalOperatorVisitor::EnumerateExpressions(op, [&](const unique_ptr *expr) { + result = result || (*expr)->IsVolatile() || (*expr)->CanThrow(); + }); + for (idx_t i = 0; i < op.children.size() && !result; i++) { + result = IsUnstable(*op.children[i]); + } + return result; + } + + static unique_ptr &SlotAt(unique_ptr &op, const vector &path) { + reference> slot = op; + for (auto child : path) { + slot = slot.get()->children[child]; + } + return slot.get(); + } + + //! The relations and the predicates of the region rooted at `op` + void CollectRegion(LogicalOperator &op, vector &path, vector &leaves, vector &predicates) { + if (!IsRegionNode(op)) { + Leaf leaf; + leaf.path = path; + for (auto &binding : op.GetColumnBindings()) { + leaf.tables.insert(binding.table_index); + } + leaf.one_row = HoldsOneRow(op); + leaf.at_most_one_row = HoldsAtMostOneRow(op); + leaf.unstable = IsUnstable(op); + leaves.push_back(std::move(leaf)); + return; + } + auto add = [&](PredicateSlot slot, idx_t index, const Expression &expr) { + Predicate predicate; + predicate.path = path; + predicate.slot = slot; + predicate.index = index; + ExpressionTables(expr, predicate.tables); + predicate.is_volatile = expr.IsVolatile(); + predicate.can_throw = expr.CanThrow(); + predicate.equality = HasEquality(expr); + predicate.expression = expr; + predicates.push_back(std::move(predicate)); + }; + switch (op.type) { + case LogicalOperatorType::LOGICAL_FILTER: + for (idx_t i = 0; i < op.expressions.size(); i++) { + add(PredicateSlot::FILTER_EXPRESSION, i, *op.expressions[i]); + } + break; + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { + auto &conditions = op.Cast().conditions; + for (idx_t i = 0; i < conditions.size(); i++) { + auto &condition = conditions[i]; + if (!condition.IsComparison()) { + add(PredicateSlot::JOIN_CONDITION, i, condition.GetJoinExpression()); + continue; + } + Predicate predicate; + predicate.path = path; + predicate.slot = PredicateSlot::JOIN_CONDITION; + predicate.index = i; + ExpressionTables(condition.GetLHS(), predicate.tables); + ExpressionTables(condition.GetRHS(), predicate.tables); + predicate.is_volatile = condition.GetLHS().IsVolatile() || condition.GetRHS().IsVolatile(); + predicate.can_throw = condition.GetLHS().CanThrow() || condition.GetRHS().CanThrow(); + predicate.equality = IsEquality(condition.GetComparisonType()) || HasEquality(condition.GetLHS()) || + HasEquality(condition.GetRHS()); + predicate.lhs = condition.GetLHS(); + predicate.rhs = condition.GetRHS(); + predicate.comparison_type = condition.GetComparisonType(); + predicates.push_back(std::move(predicate)); + } + break; + } + case LogicalOperatorType::LOGICAL_ANY_JOIN: { + add(PredicateSlot::ANY_JOIN_CONDITION, 0, *op.Cast().condition); + break; + } + default: + break; + } + for (idx_t i = 0; i < op.children.size(); i++) { + path.push_back(i); + CollectRegion(*op.children[i], path, leaves, predicates); + path.pop_back(); + } + } + + //! A relation of the region that only filters one other relation of it + bool FindRewrite(unique_ptr &op, bool ignores, const table_set_t &used, const vector &leaves, + const vector &predicates, Rewrite &rewrite) const { + if (leaves.size() < 2) { + return false; + } + for (auto &predicate : predicates) { + // a volatile predicate anywhere in the region is evaluated once per row of the region: fewer rows, fewer + // evaluations. One that can throw is evaluated on the rows the join order leaves it, and the SEMI join + // changes that order: for the predicates it takes with it and for the ones that stay + if (predicate.is_volatile || predicate.can_throw) { + return false; + } + } + for (auto &leaf : leaves) { + // the same for the expressions inside the relations: which of them run to the end, and which stop + // early because another one turned out empty, depends on how the region is joined; and a relation that + // modifies data or scans a VOLATILE table function stays where it is + if (leaf.unstable) { + return false; + } + } + for (idx_t r = 0; r < leaves.size(); r++) { + auto &removed = leaves[r]; + if (!(ignores || (removed.one_row && leaves.size() >= 3)) || Intersects(removed.tables, used)) { + continue; + } + // its parent goes with it: a cross product, or a join all of whose conditions read it + if (removed.path.empty()) { + continue; + } + vector parent_path(removed.path.begin(), removed.path.end() - 1); + if (SlotAt(op, parent_path)->type == LogicalOperatorType::LOGICAL_FILTER) { + continue; + } + vector reading; + vector cross; + optional_idx semi; + bool valid = true; + for (idx_t p = 0; p < predicates.size() && valid; p++) { + auto &predicate = predicates[p]; + if (!Intersects(predicate.tables, removed.tables)) { + // a condition of the parent that does not read the relation would lose its join + valid = predicate.path != parent_path; + continue; + } + reading.push_back(p); + bool reads_other = false; + for (auto &table : predicate.tables) { + if (removed.tables.count(table) > 0) { + continue; + } + optional_idx other; + for (idx_t l = 0; l < leaves.size(); l++) { + if (leaves[l].tables.count(table) > 0) { + other = l; + break; + } + } + if (!other.IsValid()) { + // a column of no relation of the region + return false; + } + if (semi.IsValid() && semi.GetIndex() != other.GetIndex()) { + valid = false; + break; + } + semi = other; + reads_other = true; + } + if (!valid) { + break; + } + if (reads_other) { + if (predicate.equality) { + valid = false; + break; + } + cross.push_back(p); + } + } + if (!valid || !semi.IsValid() || semi.GetIndex() == r) { + continue; + } + PredicateShape shape; + for (auto p : cross) { + auto &predicate = predicates[p]; + if (predicate.expression) { + AddPredicate(*predicate.expression, removed.tables, shape); + } else { + AddComparison(predicate.comparison_type, *predicate.lhs, *predicate.rhs, removed.tables, shape); + } + } + if (!SemiJoinIsNoSlower(shape, leaves[r])) { + continue; + } + rewrite.removed_leaf = r; + rewrite.semi_leaf = semi.GetIndex(); + rewrite.predicates = std::move(reading); + return true; + } + return false; + } + + //! Whether a SEMI join against `removed` on predicates of `shape` is planned as a join that is no slower than the + //! INNER join it replaces (see the top of this file) + static bool SemiJoinIsNoSlower(const PredicateShape &shape, const Leaf &removed) { + const auto comparisons = shape.range_comparisons + shape.other_comparisons; + if (comparisons == 0) { + // a cross product with a filter or a blockwise nested-loop join either way + return true; + } + if (comparisons == 1 && shape.other_predicates == 0 && !removed.at_most_one_row) { + // the same range or nested-loop join either way + return true; + } + // the INNER join is a range or nested-loop join with runtime filters into the scan of L, the SEMI join would + // be a blockwise one that compares every row of L with every row of R + return false; + } + + //! A filter of the region that lost every predicate goes + static void RemoveEmptyFilters(unique_ptr &op) { + while (op->type == LogicalOperatorType::LOGICAL_FILTER && IsRegionNode(*op) && op->expressions.empty()) { + auto child = std::move(op->children[0]); + op = std::move(child); + } + if (IsRegionNode(*op)) { + for (auto &child : op->children) { + RemoveEmptyFilters(child); + } + } + } + + //! Applies one rewrite to the region rooted at `op`; returns whether it did + bool RewriteRegion(unique_ptr &op, bool ignores, const table_set_t &used) { + vector leaves; + vector predicates; + vector path; + CollectRegion(*op, path, leaves, predicates); + Rewrite rewrite; + if (!FindRewrite(op, ignores, used, leaves, predicates, rewrite)) { + return false; + } + // the predicates leave their operators, last position first so that the earlier positions stay valid + vector> moved; + for (auto p : rewrite.predicates) { + moved.push_back(predicates[p]); + } + std::sort(moved.begin(), moved.end(), [](const Predicate &a, const Predicate &b) { return a.index > b.index; }); + vector> expressions; + for (auto &entry : moved) { + auto &predicate = entry.get(); + auto &node = SlotAt(op, predicate.path); + switch (predicate.slot) { + case PredicateSlot::FILTER_EXPRESSION: + expressions.push_back(std::move(node->expressions[predicate.index])); + node->expressions.erase_at(predicate.index); + break; + case PredicateSlot::JOIN_CONDITION: { + auto &conditions = node->Cast().conditions; + expressions.push_back(JoinCondition::CreateExpression(std::move(conditions[predicate.index]))); + conditions.erase_at(predicate.index); + if (conditions.empty()) { + node = make_uniq(std::move(node->children[0]), std::move(node->children[1])); + } + break; + } + case PredicateSlot::ANY_JOIN_CONDITION: + expressions.push_back(std::move(node->Cast().condition)); + node = make_uniq(std::move(node->children[0]), std::move(node->children[1])); + break; + } + } + // L SEMI JOIN R takes the place of L + auto &removed = leaves[rewrite.removed_leaf]; + auto &semi = leaves[rewrite.semi_leaf]; + auto &semi_slot = SlotAt(op, semi.path); + auto left = std::move(semi_slot); + auto right = std::move(SlotAt(op, removed.path)); + vector conditions; + LogicalComparisonJoin::ExtractJoinConditions(context, JoinType::SEMI, JoinRefType::REGULAR, left, right, + semi.tables, removed.tables, expressions, conditions); + semi_slot = LogicalComparisonJoin::CreateJoin(JoinType::SEMI, JoinRefType::REGULAR, std::move(left), + std::move(right), std::move(conditions)); + // the cross product that held R is its other child now + vector parent_path(removed.path.begin(), removed.path.end() - 1); + auto &parent = SlotAt(op, parent_path); + auto other = std::move(parent->children[1 - removed.path.back()]); + parent = std::move(other); + RemoveEmptyFilters(op); + return true; + } + +public: + ClientContext &context; + //! The materialized CTEs seen so far whose definition holds at most one row + table_set_t single_row_ctes; + //! The CTEs whose definition is unstable (IsUnstable) + table_set_t unstable_ctes; +}; + +JoinToSemiJoin::JoinToSemiJoin(ClientContext &context) : rewriter(make_uniq(context)) { +} + +JoinToSemiJoin::~JoinToSemiJoin() { +} + +void JoinToSemiJoin::Initialize(LogicalOperator &plan) { + rewriter->Initialize(plan); +} + +bool JoinToSemiJoin::IsRegionNode(const LogicalOperator &op) { + return JoinRegionRewriter::IsRegionNode(op); +} + +bool JoinToSemiJoin::RewriteRegion(unique_ptr &op, bool ignores_duplicates, + const unordered_set &read_tables) { + return rewriter->RewriteRegion(op, ignores_duplicates, read_tables); +} + +void JoinToSemiJoin::VisitMaterializedCTE(const LogicalOperator &op) { + rewriter->VisitMaterializedCTE(op); +} + +void JoinToSemiJoin::AddReadTables(const LogicalOperator &op, unordered_set &tables) { + JoinRegionRewriter::OperatorTables(op, tables); +} + +bool JoinToSemiJoin::HasVolatileExpression(const LogicalOperator &op) { + return JoinRegionRewriter::HasVolatileExpression(op); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/mark_join_simplifier.cpp b/src/duckdb/src/optimizer/mark_join_simplifier.cpp new file mode 100644 index 000000000..32550da1a --- /dev/null +++ b/src/duckdb/src/optimizer/mark_join_simplifier.cpp @@ -0,0 +1,246 @@ +#include "duckdb/optimizer/mark_join_simplifier.hpp" + +#include "duckdb/execution/expression_executor.hpp" +#include "duckdb/optimizer/column_binding_replacer.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/planner/binder.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_iterator.hpp" +#include "duckdb/planner/expression_nullability.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/subquery/has_volatile_expressions.hpp" + +namespace duckdb { + +MarkJoinSimplifier::MarkJoinSimplifier(Optimizer &optimizer) : optimizer(optimizer) { +} + +static bool ComparisonInputIsNotNull(NotNullExpressionAnalyzer &analyzer, LogicalOperator &op, const Expression &expr) { + // These comparisons can produce NULL from nested members. + if (expr.GetReturnType().id() == LogicalTypeId::TUPLE || expr.GetReturnType().id() == LogicalTypeId::UNION) { + return false; + } + return analyzer.IsNotNull(op, expr); +} + +static bool JoinConditionsCannotBeNull(NotNullExpressionAnalyzer &analyzer, LogicalComparisonJoin &join) { + for (auto &condition : join.conditions) { + if (!condition.IsComparison()) { + return false; + } + if (condition.GetComparisonType() == ExpressionType::COMPARE_DISTINCT_FROM || + condition.GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + continue; + } + if (!ComparisonInputIsNotNull(analyzer, *join.children[0], condition.GetLHS()) || + !ComparisonInputIsNotNull(analyzer, *join.children[1], condition.GetRHS())) { + return false; + } + } + return true; +} + +static bool IsMarker(const Expression &expr, ColumnBinding marker) { + if (expr.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + return false; + } + const auto &column = expr.Cast(); + return column.Depth() == 0 && column.Binding() == marker; +} + +static bool IsMarkerPredicate(const Expression &expr, ColumnBinding marker) { + if (expr.GetReturnType() != LogicalType::BOOLEAN) { + return false; + } + if (IsMarker(expr, marker)) { + return true; + } + switch (expr.GetExpressionType()) { + case ExpressionType::VALUE_CONSTANT: + return true; + case ExpressionType::OPERATOR_NOT: + case ExpressionType::OPERATOR_IS_NULL: + case ExpressionType::OPERATOR_IS_NOT_NULL: + case ExpressionType::CONJUNCTION_AND: + case ExpressionType::CONJUNCTION_OR: + break; + default: + if (!BoundComparisonExpression::IsComparison(expr)) { + return false; + } + } + bool supported = true; + ExpressionIterator::EnumerateChildren( + expr, [&](const Expression &child) { supported &= IsMarkerPredicate(child, marker); }); + return supported; +} + +struct MarkerPredicate { + bool accepts_true = false; + bool accepts_false = false; + bool accepts_null = false; + + bool AcceptsOnlyTrue() const { + return accepts_true && !accepts_false && !accepts_null; + } + + bool AcceptsOneNonNullValue() const { + return accepts_true != accepts_false; + } +}; + +static MarkerPredicate AnalyzeMarkerPredicate(ClientContext &context, const Expression &expr, ColumnBinding marker) { + MarkerPredicate result; + if (IsMarker(expr, marker)) { + result.accepts_true = true; + return result; + } + if (expr.GetExpressionType() == ExpressionType::OPERATOR_NOT && + IsMarker(*expr.Cast().GetChildren()[0], marker)) { + result.accepts_false = true; + return result; + } + if (!IsMarkerPredicate(expr, marker)) { + return result; + } + auto evaluate = [&](const Value &marker_value, bool &accepted) { + auto copy = expr.Copy(); + ExpressionIterator::VisitExpressionMutable( + copy, [&](BoundColumnRefExpression &, unique_ptr &ref) { + ref = make_uniq(marker_value); + }); + Value evaluated; + if (!ExpressionExecutor::TryEvaluateScalar(context, *copy, evaluated)) { + return false; + } + accepted = !evaluated.IsNull() && evaluated.GetValue(); + return true; + }; + if (!evaluate(Value::BOOLEAN(true), result.accepts_true) || + !evaluate(Value::BOOLEAN(false), result.accepts_false) || + !evaluate(Value(LogicalType::BOOLEAN), result.accepts_null)) { + return {}; + } + return result; +} + +static void SimplifyNullSafeSemiJoinConditions(NotNullExpressionAnalyzer &analyzer, LogicalComparisonJoin &join) { + for (auto &condition : join.conditions) { + if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + continue; + } + // A UNION's active member may be NULL even when the UNION itself is not. + if (condition.GetLHS().GetReturnType().id() == LogicalTypeId::UNION) { + continue; + } + if (analyzer.IsNotNull(*join.children[0], condition.GetLHS()) || + analyzer.IsNotNull(*join.children[1], condition.GetRHS())) { + condition.SetComparisonType(ExpressionType::COMPARE_EQUAL); + } + } +} + +bool MarkJoinSimplifier::TrySimplify(unique_ptr &op, NotNullExpressionAnalyzer &nullability, + BindingReplacementGraph &replacements) { + auto &filter = op->Cast(); + if (filter.children[0]->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return false; + } + auto &join = filter.children[0]->Cast(); + if (join.join_type != JoinType::MARK || !join.duplicate_eliminated_columns.empty()) { + // Retain unresolved correlation and DELIM semantics (issue #22267). + return false; + } + const ColumnBinding marker(join.mark_index, ProjectionIndex(0)); + for (idx_t i = 0; i < filter.expressions.size(); i++) { + auto predicate = AnalyzeMarkerPredicate(optimizer.context, *filter.expressions[i], marker); + auto target_type = JoinType::INVALID; + if (predicate.AcceptsOnlyTrue()) { + target_type = JoinType::SEMI; + } else if (predicate.AcceptsOneNonNullValue() && JoinConditionsCannotBeNull(nullability, join)) { + target_type = predicate.accepts_true ? JoinType::SEMI : JoinType::ANTI; + } + if (target_type == JoinType::INVALID) { + continue; + } + // Reordering the converted join can change which rows evaluate volatile expressions. + if (HasVolatileExpressionsIgnoringError(filter)) { + return false; + } + for (auto &condition : join.conditions) { + // Reordering can evaluate conditions on rows removed by other joins. + auto can_throw = condition.IsComparison() ? condition.GetLHS().CanThrow() || condition.GetRHS().CanThrow() + : condition.GetJoinExpression().CanThrow(); + if (can_throw) { + return false; + } + // MARK tuple inequality uses row equality, unlike ordinary nested inequality. + if (condition.IsComparison() && condition.GetComparisonType() == ExpressionType::COMPARE_NOTEQUAL && + condition.GetLHS().GetReturnType().id() == LogicalTypeId::TUPLE) { + return false; + } + } + join.ResolveOperatorTypes(); + const auto old_bindings = join.GetColumnBindings(); + vector> expressions; + for (idx_t col_idx = 0; col_idx < old_bindings.size(); col_idx++) { + if (old_bindings[col_idx] == marker) { + expressions.push_back( + make_uniq(Value::BOOLEAN(target_type == JoinType::SEMI))); + } else { + expressions.push_back(make_uniq(join.types[col_idx], old_bindings[col_idx])); + } + } + filter.expressions.erase_at(i); + auto projection = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(expressions)); + BindingReplacementGraph local_replacements; + auto new_bindings = projection->GetColumnBindings(); + for (idx_t col_idx = 0; col_idx < old_bindings.size(); col_idx++) { + if (!local_replacements.Find(old_bindings[col_idx])) { + local_replacements.Add(old_bindings[col_idx], new_bindings[col_idx]); + } + } + ColumnBindingRewrite::RewriteChild( + op, 0, [&](unique_ptr &child, BindingReplacementGraph &child_replacements) { + join.join_type = target_type; + join.mark_types.clear(); + if (target_type == JoinType::SEMI) { + SimplifyNullSafeSemiJoinConditions(nullability, join); + } + projection->children.push_back(std::move(child)); + child = std::move(projection); + child_replacements.Merge(local_replacements); + }); + replacements.Merge(local_replacements); + return true; + } + return false; +} + +void MarkJoinSimplifier::Rewrite(unique_ptr &op, NotNullExpressionAnalyzer &nullability, + BindingReplacementGraph &replacements) { + for (auto &child : op->children) { + Rewrite(child, nullability, replacements); + } + // Visit original consumers before adding their enclosing conversion's replacement edges. + ColumnBindingRewrite::ApplyToOperatorBindings(*op, replacements); + if (op->type == LogicalOperatorType::LOGICAL_FILTER && TrySimplify(op, nullability, replacements)) { + auto &filter = op->Cast(); + if (filter.expressions.empty() && !filter.HasProjectionMap()) { + op = std::move(filter.children[0]); + } + } +} + +void MarkJoinSimplifier::Optimize(unique_ptr &plan) { + NotNullExpressionAnalyzer nullability(optimizer.context, *plan); + BindingReplacementGraph replacements; + Rewrite(plan, nullability, replacements); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/optimizer.cpp b/src/duckdb/src/optimizer/optimizer.cpp index 45df21e00..9001df91e 100644 --- a/src/duckdb/src/optimizer/optimizer.cpp +++ b/src/duckdb/src/optimizer/optimizer.cpp @@ -25,9 +25,12 @@ #include "duckdb/optimizer/join_elimination.hpp" #include "duckdb/optimizer/join_filter_pushdown_optimizer.hpp" #include "duckdb/optimizer/join_order/join_order_optimizer.hpp" +#include "duckdb/optimizer/join_simplification.hpp" #include "duckdb/optimizer/limit_pushdown.hpp" +#include "duckdb/optimizer/mark_join_simplifier.hpp" #include "duckdb/optimizer/regex_range_filter.hpp" #include "duckdb/optimizer/remove_duplicate_groups.hpp" +#include "duckdb/optimizer/remove_redundant_distinct.hpp" #include "duckdb/optimizer/remove_redundant_order.hpp" #include "duckdb/optimizer/remove_redundant_order_keys.hpp" #include "duckdb/optimizer/remove_unused_columns.hpp" @@ -36,6 +39,7 @@ #include "duckdb/optimizer/scalar_aggregate_merger.hpp" #include "duckdb/optimizer/scalar_fn_pushdown.hpp" #include "duckdb/optimizer/self_join_aggregate.hpp" +#include "duckdb/optimizer/set_operation_aggregate.hpp" #include "duckdb/optimizer/statistics_propagator.hpp" #include "duckdb/optimizer/aggregate_function_rewriter.hpp" #include "duckdb/optimizer/aggregate_reuse.hpp" @@ -48,9 +52,9 @@ #include "duckdb/optimizer/partitioned_execution.hpp" #include "duckdb/optimizer/window_join_pushdown.hpp" #include "duckdb/optimizer/window_self_join.hpp" +#include "duckdb/optimizer/window_fusion.hpp" #include "duckdb/optimizer/row_number_rewriter.hpp" #include "duckdb/optimizer/optimizer_extension.hpp" -#include "duckdb/optimizer/outer_join_simplification.hpp" #include "duckdb/optimizer/partial_aggregate_pushdown.hpp" #include "duckdb/optimizer/projection_pullup.hpp" #include "duckdb/optimizer/projection_placement.hpp" @@ -125,24 +129,6 @@ static void ClearProjectionMaps(LogicalOperator &op) { } } -static bool ContainsDML(const LogicalOperator &op) { - switch (op.type) { - case LogicalOperatorType::LOGICAL_INSERT: - case LogicalOperatorType::LOGICAL_UPDATE: - case LogicalOperatorType::LOGICAL_DELETE: - case LogicalOperatorType::LOGICAL_MERGE_INTO: - return true; - default: - break; - } - for (auto &child : op.children) { - if (ContainsDML(*child)) { - return true; - } - } - return false; -} - static bool ContainsDataSource(const LogicalOperator &op) { if (op.type == LogicalOperatorType::LOGICAL_GET) { return true; @@ -155,24 +141,6 @@ static bool ContainsDataSource(const LogicalOperator &op) { return false; } -// Returns true if the plan contains a DML statement inside a CTE body. A top-level -// DML statement is not flagged. COPY TO is side-effecting, but does not invalidate -// table statistics and is deliberately excluded here. -static bool CTEContainsDML(const LogicalOperator &op) { - if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || - op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { - if (!op.children.empty() && ContainsDML(*op.children[0])) { - return true; - } - } - for (auto &child : op.children) { - if (CTEContainsDML(*child)) { - return true; - } - } - return false; -} - void Optimizer::OptimizeStatement(unique_ptr &statement) { if (!Settings::Get(context)) { return; @@ -229,6 +197,14 @@ void Optimizer::RunBuiltInOptimizers() { plan = self_join_aggregate.Optimize(std::move(plan)); }); + // An INNER join against a relation that only predicates read, and that they compare with one other relation + // only, becomes a SEMI join on that relation when repeated rows do not matter. Runs before filter pushdown, + // which then pushes the remaining filters below the SEMI join + RunOptimizer(OptimizerType::JOIN_TO_SEMI_JOIN, [&]() { + JoinSimplification join_simplification(context, JoinSimplificationPhase::BEFORE_FILTER_PUSHDOWN); + join_simplification.Optimize(plan); + }); + // computes sibling scalar aggregates over the same table(s) in one pass, while their predicates are still filters RunOptimizer(OptimizerType::SCALAR_AGGREGATE_MERGE, [&]() { ScalarAggregateMerger scalar_aggregate_merger(*this); @@ -249,19 +225,23 @@ void Optimizer::RunBuiltInOptimizers() { // perform filter pullup RunOptimizer(OptimizerType::FILTER_PULLUP, [&]() { - FilterPullup filter_pullup; + FilterPullup filter_pullup(context); plan = filter_pullup.Rewrite(std::move(plan)); }); // perform filter pushdown RunOptimizer(OptimizerType::FILTER_PUSHDOWN, [&]() { FilterPushdown filter_pushdown(*this); - unordered_set top_bindings; - filter_pushdown.CheckMarkToSemi(*plan, top_bindings); plan = filter_pushdown.Rewrite(std::move(plan)); }); - if (!CTEContainsDML(*plan)) { + // Expose filtering joins before choosing aggregate key domains. + RunOptimizer(OptimizerType::MARK_JOIN_SIMPLIFIER, [&]() { + MarkJoinSimplifier mark_simplifier(*this); + mark_simplifier.Optimize(plan); + }); + + if (!plan->CTEContainsDML()) { RunOptimizer(OptimizerType::DUPLICATE_ELIMINATED_DOMAIN, [&]() { DuplicateEliminatedDomainOptimizer domain_optimizer(*this); domain_optimizer.Optimize(plan); @@ -322,12 +302,33 @@ void Optimizer::RunBuiltInOptimizers() { plan = empty_result_pullup.Optimize(std::move(plan)); }); + // Chooses how EXCEPT ALL / INTERSECT ALL run, which are set operations until here so that the filters could be + // moved around them: one aggregate over the UNION ALL of both children, or a join of the numbered rows. The join + // order, statistics propagation and compressed materialization then see that aggregate or join. Disabling the + // optimizer type only takes the aggregate away + const bool use_set_operation_aggregate = !OptimizerDisabled(OptimizerType::SET_OPERATION_AGGREGATE); + const auto lower_set_operations = [&]() { + SetOperationAggregate set_operation_aggregate(*this, use_set_operation_aggregate); + plan = set_operation_aggregate.Optimize(std::move(plan)); + }; + if (use_set_operation_aggregate) { + RunOptimizer(OptimizerType::SET_OPERATION_AGGREGATE, lower_set_operations); + } else { + lower_set_operations(); + } + // Replaces some window computations with self-joins RunOptimizer(OptimizerType::WINDOW_SELF_JOIN, [&]() { WindowSelfJoinOptimizer window_self_join_optimizer(*this); plan = window_self_join_optimizer.Optimize(std::move(plan)); }); + // IN-clause rewriting and delim elimination can expose more filtered markers. + RunOptimizer(OptimizerType::MARK_JOIN_SIMPLIFIER, [&]() { + MarkJoinSimplifier mark_simplifier(*this); + mark_simplifier.Optimize(plan); + }); + // Pull up projection from joins RunOptimizer(OptimizerType::PROJECTION_PULLUP, [&]() { ProjectionPullup projection_pullup(*this, plan); @@ -342,8 +343,21 @@ void Optimizer::RunBuiltInOptimizers() { // Simplifies FULL OUTER -> LEFT/RIGHT OUTER -> INNER if NULLs are filtered anyway RunOptimizer(OptimizerType::OUTER_JOIN_SIMPLIFICATION, [&]() { - OuterJoinSimplification outer_join_simplification; - outer_join_simplification.VisitOperator(*plan); + JoinSimplification join_simplification(context, JoinSimplificationPhase::AFTER_FILTER_PUSHDOWN); + join_simplification.Optimize(plan); + }); + + // removes duplicate eliminations (DISTINCT, GROUP BY without aggregates) over an input that is already distinct + RunOptimizer(OptimizerType::REDUNDANT_DISTINCT, [&]() { + RemoveRedundantDistinct remove_redundant_distinct; + remove_redundant_distinct.VisitOperator(plan); + }); + + // removes the outer joins that can be removed before the join order is chosen, so that the join order sees the + // plan without them; a second run after UNUSED_COLUMNS removes the ones only column pruning exposes + RunOptimizer(OptimizerType::JOIN_ELIMINATION, [&]() { + JoinElimination join_elimination; + plan = join_elimination.Optimize(std::move(plan)); }); // then we perform the join ordering optimization @@ -368,9 +382,12 @@ void Optimizer::RunBuiltInOptimizers() { partial_aggregate_pushdown.VisitOperator(plan); }); - RunOptimizer(OptimizerType::JOIN_ELIMINATION, [&]() { - JoinElimination join_elimination; - plan = join_elimination.Optimize(std::move(plan)); + // Rewrites f(CASE WHEN c THEN x END) -> f(x) FILTER (WHERE c). Runs after the rewrites that match aggregates + // without a filter (aggregate reuse, partial aggregate pushdown), so that these still see the CASE. + RunOptimizer(OptimizerType::CASE_TO_FILTER_AGGREGATE, [&]() { + AggregateFunctionRewriter aggregate_function_rewriter(*this); + // DML CTEs can invalidate the table statistics captured during planning. + aggregate_function_rewriter.RewriteCaseToFilter(plan, !plan->CTEContainsDML()); }); RunOptimizer(OptimizerType::REDUNDANT_ORDER_KEYS, [&]() { @@ -390,6 +407,21 @@ void Optimizer::RunBuiltInOptimizers() { unused.VisitOperator(plan); }); + // a join whose inner side was only read by columns that nothing reads can be removed now; the columns that only + // that join read are pruned in turn + bool removed_join = false; + RunOptimizer(OptimizerType::JOIN_ELIMINATION, [&]() { + JoinElimination join_elimination; + plan = join_elimination.Optimize(std::move(plan)); + removed_join = join_elimination.RemovedJoin(); + }); + if (removed_join) { + RunOptimizer(OptimizerType::UNUSED_COLUMNS, [&]() { + RemoveUnusedColumns unused(*this); + unused.VisitOperator(plan); + }); + } + // Remove duplicate groups from aggregates RunOptimizer(OptimizerType::DUPLICATE_GROUPS, [&]() { RemoveDuplicateGroups remove(*this); @@ -418,7 +450,7 @@ void Optimizer::RunBuiltInOptimizers() { // convert common subplans into materialized CTEs // Skip when the plan contains a DML CTE: table statistics are stale at plan // time and could cause incorrect deduplication of scans across a DML boundary. - if (!CTEContainsDML(*plan)) { + if (!plan->CTEContainsDML()) { RunOptimizer(OptimizerType::COMMON_SUBPLAN, [&]() { CommonSubplanOptimizer common_subplan_optimizer(*this); plan = common_subplan_optimizer.Optimize(std::move(plan)); @@ -459,7 +491,7 @@ void Optimizer::RunBuiltInOptimizers() { column_binding_map_t> statistics_map; bool propagated_statistics = false; bool removed_expressions = false; - if (!CTEContainsDML(*plan)) { + if (!plan->CTEContainsDML()) { RunOptimizer(OptimizerType::STATISTICS_PROPAGATION, [&]() { StatisticsPropagator propagator(*this, plan); propagator.PropagateStatistics(plan); @@ -483,6 +515,12 @@ void Optimizer::RunBuiltInOptimizers() { }); } + // rewrite unique ranking window function + filter on row_number to fused operator + RunOptimizer(OptimizerType::WINDOW_FUSION, [&]() { + WindowFusion window_fusion(context, &statistics_map); + plan = window_fusion.Optimize(std::move(plan)); + }); + // rewrite row_number window function + filter on row_number to aggregate bool topn_used_late_materialization = false; RunOptimizer(OptimizerType::TOP_N_WINDOW_ELIMINATION, [&]() { diff --git a/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp b/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp index 56c33f572..c17d407ed 100644 --- a/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp +++ b/src/duckdb/src/optimizer/partial_aggregate_pushdown.cpp @@ -94,7 +94,9 @@ static void CopyCardinality(LogicalOperator &dst, const LogicalOperator &src) { dst.has_estimated_cardinality = src.has_estimated_cardinality; } -static bool IsSupportedAggregate(const BoundAggregateExpression &expr) { +//! "allow_exported" accepts an aggregate that already exports its state (e.g. the finest level of a ROLLUP / CUBE +//! cascade): the one-sided pushdown moves it below the join as it is and combines the states above the join +static bool IsSupportedAggregate(const BoundAggregateExpression &expr, bool allow_exported = false) { if (expr.IsDistinct() || expr.GetFilter() || expr.GetOrderBys()) { return false; } @@ -106,7 +108,7 @@ static bool IsSupportedAggregate(const BoundAggregateExpression &expr) { return false; } } - if (expr.StateExportMode() != AggregateStateExportMode::NONE) { + if (expr.StateExportMode() != AggregateStateExportMode::NONE && !allow_exported) { return false; } if (expr.GetChildren().size() > 1) { @@ -206,6 +208,19 @@ static bool AggregateArgumentsCanThrow(Optimizer &optimizer, unique_ptrCast(); + if (aggregate.StateExportMode() != AggregateStateExportMode::NONE && + aggregate.Function().GetErrorMode() == FunctionErrors::CAN_THROW_RUNTIME_ERROR) { + return true; + } + } + return false; +} + static bool ContainsAggregateInput(const LogicalOperator &op) { if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { return true; @@ -308,7 +323,7 @@ static bool FindAggregateSide(const LogicalAggregate &aggr, PartialAggregatePush return false; } auto &aggregate = expr->Cast(); - if (!IsSupportedAggregate(aggregate)) { + if (!IsSupportedAggregate(aggregate, true)) { return false; } if (aggregate.GetChildren().empty()) { @@ -479,8 +494,12 @@ static bool BindPushdownAggregates(ClientContext &context, LogicalAggregate &agg FunctionBinder function_binder(context); for (idx_t i = 0; i < aggr.expressions.size(); i++) { - auto aggregate_copy = unique_ptr_cast(aggr.expressions[i]->Copy()); - auto lower_aggregate = ExportAggregateFunction::Bind(std::move(aggregate_copy)); + auto lower_aggregate = unique_ptr_cast(aggr.expressions[i]->Copy()); + if (lower_aggregate->StateExportMode() == AggregateStateExportMode::NONE) { + // an aggregate that already exports its state is the lower aggregate as it is: exporting it a second + // time would nest the state type + lower_aggregate = ExportAggregateFunction::Bind(std::move(lower_aggregate)); + } auto lower_type = lower_aggregate->GetReturnType(); if (!lower_type.IsAggregateState()) { return false; @@ -1306,7 +1325,8 @@ bool PartialAggregatePushdown::TryPushdownAggregate(unique_ptr return false; } // A preserved side of an outer join keeps every row, so the argument is evaluated on all of them either way. - if (join->join_type == JoinType::INNER && AggregateArgumentsCanThrow(optimizer, op)) { + if (join->join_type == JoinType::INNER && + (ExportedAggregatesCanThrow(*aggr) || AggregateArgumentsCanThrow(optimizer, op))) { return false; } @@ -1323,8 +1343,15 @@ bool PartialAggregatePushdown::TryPushdownAggregate(unique_ptr auto final_projection = BuildFinalProjection(optimizer, *aggr, std::move(upper_aggr), replacement_map, [&](idx_t j, unique_ptr ref) -> unique_ptr { + auto &original = aggr->expressions[j]->Cast(); + if (original.StateExportMode() != AggregateStateExportMode::NONE) { + // the consumers of an exported aggregate expect the state: pass the + // combined state on instead of finalizing it + D_ASSERT(ref->GetReturnType() == original.GetReturnType()); + return ref; + } auto finalized = optimizer.BindScalarFunction("finalize", std::move(ref)); - if (finalized->GetReturnType() != aggr->expressions[j]->GetReturnType()) { + if (finalized->GetReturnType() != original.GetReturnType()) { return nullptr; // state does not round-trip back to the original type } return finalized; diff --git a/src/duckdb/src/optimizer/partitioned_execution.cpp b/src/duckdb/src/optimizer/partitioned_execution.cpp index 390b9ccb7..e5f97a33e 100644 --- a/src/duckdb/src/optimizer/partitioned_execution.cpp +++ b/src/duckdb/src/optimizer/partitioned_execution.cpp @@ -504,7 +504,7 @@ void PartitionedExecutionSplitPipeline(Optimizer &optimizer, unique_ptrchildren[0] = std::move(filter); // Now push it down - FilterPushdown filter_pushdown(optimizer, false); + FilterPushdown filter_pushdown(optimizer); copy = filter_pushdown.Rewrite(std::move(copy)); // Add cardinality estimates for these GETs diff --git a/src/duckdb/src/optimizer/projection_pullup.cpp b/src/duckdb/src/optimizer/projection_pullup.cpp index 2f1d4ae09..15afb8e30 100644 --- a/src/duckdb/src/optimizer/projection_pullup.cpp +++ b/src/duckdb/src/optimizer/projection_pullup.cpp @@ -72,10 +72,14 @@ void ProjectionPullup::InsertProjectionBelowOp(unique_ptr &op, next.Optimize(child->children[0]); } -void ProjectionPullup::PullUpColrefProjection(unique_ptr &op, LogicalProjection &proj, - vector &proj_bindings) { +void ProjectionPullup::RemoveProjection(unique_ptr &op, LogicalProjection &proj, + vector &proj_bindings) { ColumnBindingReplacer replacer; for (idx_t i = 0; i < proj.expressions.size(); i++) { + if (proj.expressions[i]->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + D_ASSERT(proj.expressions[i]->GetExpressionType() == ExpressionType::VALUE_CONSTANT); + continue; + } auto &colref = proj.expressions[i]->Cast(); replacer.replacement_bindings.emplace_back(proj_bindings[i], colref.Binding()); } @@ -200,7 +204,8 @@ static bool IsThrowingProjectionFilter(const Expression &expr, } void ProjectionPullup::CanPullThrough(column_binding_map_t> &projection_map, - bool keep_throwing_filters_above, bool &can_pull_through) { + const LogicalProjection &proj, bool &can_pull_through) { + const auto keep_throwing_filters_above = HasJoinBelow(proj); // if expressions in the projections are colrefs, we can always pull it up // if it's not a colref, we can pull it up only if it does not appear in the operator enumerate expressions for (idx_t i = parents.size(); i > 0; i--) { @@ -208,6 +213,23 @@ void ProjectionPullup::CanPullThrough(column_binding_map_ttype == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY || + proj.children[0]->type == LogicalOperatorType::LOGICAL_DUMMY_SCAN) { + can_pull_through = false; + break; + } + // Keep computations below a cross product to avoid multiplying their evaluation. + for (auto &entry : projection_map) { + auto type = entry.second->GetExpressionType(); + if (type != ExpressionType::BOUND_COLUMN_REF && type != ExpressionType::VALUE_CONSTANT) { + can_pull_through = false; + return; + } + } + } + LogicalOperatorVisitor::EnumerateExpressions(parent_op, [&](unique_ptr *expr) { if (keep_throwing_filters_above && IsThrowingProjectionFilter(**expr, projection_map)) { can_pull_through = false; @@ -266,6 +288,12 @@ void ProjectionPullup::VisitOperator(unique_ptr &op) { } return; } + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: { + parents.push_back(*op); + VisitOperatorChildren(*op); + PopParents(*op); + return; + } case LogicalOperatorType::LOGICAL_ANY_JOIN: case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { auto &comp_join = op->Cast(); @@ -325,7 +353,7 @@ void ProjectionPullup::VisitOperator(unique_ptr &op) { // if expressions in the projections are colrefs, we can always pull it up // if it's not a colref, we can pull it up only if it does not appear in the operator enumerate expressions idx_t pull_up_to_here = parents.size(); - CanPullThrough(projection_map, HasJoinBelow(proj), can_pull_through); + CanPullThrough(projection_map, proj, can_pull_through); // Partial pullup is intentionally not implemented. // Pulling a projection only partially up could leave it in an intermediate state between operators. This would @@ -350,7 +378,7 @@ void ProjectionPullup::VisitOperator(unique_ptr &op) { return; } if (all_column_refs) { - PullUpColrefProjection(op, proj, proj_bindings); + RemoveProjection(op, proj, proj_bindings); return; } PullUpNonColrefProjection(op, proj, proj_bindings, pull_up_to_here); @@ -370,5 +398,34 @@ void ProjectionPullup::VisitOperator(unique_ptr &op) { // Create new optimizer for child (start fresh without any state) ProjectionPullup next(optimizer, root); next.VisitOperatorChildren(*op); + if (op->type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY && + op->children[0]->type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto &projection = op->children[0]->Cast(); + if (projection.children[0]->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return; + } + for (auto &expr : projection.expressions) { + if (expr->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF && + expr->GetExpressionType() != ExpressionType::VALUE_CONSTANT) { + return; + } + } + bool can_remove = true; + LogicalOperatorVisitor::EnumerateExpressions(*op, [&](unique_ptr *expr) { + ExpressionIterator::VisitExpression( + **expr, [&](const BoundColumnRefExpression &ref) { + if (ref.Binding().table_index == projection.table_index) { + auto &projected = *projection.expressions[ref.Binding().column_index.GetIndex()]; + can_remove &= projected.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF; + } + }); + }); + if (!can_remove) { + return; + } + // Aggregate outputs do not depend on the child's column order. + auto bindings = projection.GetColumnBindings(); + next.RemoveProjection(op->children[0], projection, bindings); + } } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/pullup/pullup_both_side.cpp b/src/duckdb/src/optimizer/pullup/pullup_both_side.cpp index 04bbb3f1b..1f648dd3d 100644 --- a/src/duckdb/src/optimizer/pullup/pullup_both_side.cpp +++ b/src/duckdb/src/optimizer/pullup/pullup_both_side.cpp @@ -3,8 +3,8 @@ namespace duckdb { unique_ptr FilterPullup::PullupBothSide(unique_ptr op) { - FilterPullup left_pullup(true, can_add_column); - FilterPullup right_pullup(true, can_add_column); + FilterPullup left_pullup(context, true, can_add_column); + FilterPullup right_pullup(context, true, can_add_column); op->children[0] = left_pullup.Rewrite(std::move(op->children[0])); op->children[1] = right_pullup.Rewrite(std::move(op->children[1])); D_ASSERT(left_pullup.can_add_column == can_add_column); diff --git a/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp b/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp index 8c6ccb2e5..1e93c0903 100644 --- a/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp +++ b/src/duckdb/src/optimizer/pullup/pullup_from_left.cpp @@ -10,8 +10,8 @@ unique_ptr FilterPullup::PullupFromLeft(unique_ptrtype == LogicalOperatorType::LOGICAL_EXCEPT || op->type == LogicalOperatorType::LOGICAL_INTERSECT || op->type == LogicalOperatorType::LOGICAL_DELIM_JOIN); - FilterPullup left_pullup(true, can_add_column); - FilterPullup right_pullup(false, can_add_column); + FilterPullup left_pullup(context, true, can_add_column); + FilterPullup right_pullup(context, false, can_add_column); op->children[0] = left_pullup.Rewrite(std::move(op->children[0])); op->children[1] = right_pullup.Rewrite(std::move(op->children[1])); diff --git a/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp b/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp index b3d09fce4..d3d7d80a2 100644 --- a/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp +++ b/src/duckdb/src/optimizer/pullup/pullup_set_operation.cpp @@ -1,32 +1,90 @@ #include "duckdb/optimizer/filter_pullup.hpp" +#include "duckdb/optimizer/filter_combiner.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" namespace duckdb { -static void ReplaceFilterTableIndex(unique_ptr &expr, LogicalSetOperation &setop) { - expr = ExpressionIterator::PreorderReplace( - std::move(expr), [&](const BoundColumnRefExpression &colref) { - D_ASSERT(colref.Depth() == 0); - return colref.WithBinding(ColumnBinding(setop.table_index, colref.Binding().column_index)); - }); +//! Whether the filter compares what a column of that child is compared as with constants: it keeps or removes all the +//! rows that the set operation treats as equal +static bool ComparesSetOperationColumn(const Expression &filter, const vector &comparisons, + bool left_child) { + auto compared = FilterCombiner::GetComparedExpression(filter); + if (!compared) { + return false; + } + for (auto &comparison : comparisons) { + if ((left_child ? comparison.GetLHS() : comparison.GetRHS()).Equals(*compared)) { + return true; + } + } + return false; } unique_ptr FilterPullup::PullupSetOperation(unique_ptr op) { D_ASSERT(op->type == LogicalOperatorType::LOGICAL_INTERSECT || op->type == LogicalOperatorType::LOGICAL_EXCEPT); - can_add_column = false; - can_pullup = true; - // EXCEPT and INTERSECT return rows of the left child, so a filter of the right child does not apply to them - op = PullupFromLeft(std::move(op)); - if (op->type == LogicalOperatorType::LOGICAL_FILTER) { - auto &filter = op->Cast(); - auto &setop = filter.children[0]->Cast(); - for (idx_t i = 0; i < filter.expressions.size(); ++i) { - ReplaceFilterTableIndex(filter.expressions[i], setop); + if (!context) { + return FinishPullup(std::move(op)); + } + auto &setop = op->Cast(); + // the children cannot get more columns to carry a filter + FilterPullup left_pullup(context, true, false); + FilterPullup right_pullup(context, op->type == LogicalOperatorType::LOGICAL_INTERSECT, false); + op->children[0] = left_pullup.Rewrite(std::move(op->children[0])); + op->children[1] = right_pullup.Rewrite(std::move(op->children[1])); + auto comparisons = setop.GetComparisons(*context); + + // EXCEPT and INTERSECT return some of the rows of the left child that they treat as equal. A filter of the left + // child may run above them if it keeps or removes all equal rows: one that compares a column with constants. + // A filter that stays below and can throw keeps the filters that guard it there + auto &left_filters = left_pullup.filters_expr_pullup; + bool keep_all = false; + for (auto &filter : left_filters) { + keep_all = keep_all || (filter->CanThrow() && !ComparesSetOperationColumn(*filter, comparisons, true)); + } + vector> kept_filters; + vector> pulled_filters; + for (auto &filter : left_filters) { + if (keep_all || !ComparesSetOperationColumn(*filter, comparisons, true)) { + kept_filters.push_back(std::move(filter)); + } else { + pulled_filters.push_back(std::move(filter)); } } - return op; + left_filters.clear(); + if (!kept_filters.empty()) { + op->children[0] = GeneratePullupFilter(std::move(op->children[0]), kept_filters); + } + if (!right_pullup.filters_expr_pullup.empty()) { + // INTERSECT: a left row with an equal right row passes what the filters of the right child imply for it + vector> right_filters; + for (auto &filter : right_pullup.filters_expr_pullup) { + right_filters.push_back(*filter); + } + FilterCombiner::GenerateJoinFilters( + comparisons, right_filters, JoinSide::LEFT, + [&](unique_ptr left_filter) { pulled_filters.push_back(std::move(left_filter)); }); + op->children[1] = GeneratePullupFilter(std::move(op->children[1]), right_pullup.filters_expr_pullup); + } + if (pulled_filters.empty()) { + return op; + } + // the filters refer to the columns of the left child: above the set operation these are its columns + auto left_bindings = op->children[0]->GetColumnBindings(); + for (auto &filter : pulled_filters) { + filter = ExpressionIterator::PreorderReplace( + std::move(filter), [&](const BoundColumnRefExpression &colref) { + D_ASSERT(colref.Depth() == 0); + for (idx_t i = 0; i < left_bindings.size(); i++) { + if (left_bindings[i] == colref.Binding()) { + return colref.WithBinding(ColumnBinding(setop.table_index, ProjectionIndex(i))); + } + } + throw InternalException("Filter of a set operation refers to a column that is not one of its child"); + }); + } + return GeneratePullupFilter(std::move(op), pulled_filters); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp index 4e0f3b9e3..c1899b91b 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp @@ -41,7 +41,7 @@ unique_ptr FilterPushdown::PushdownAggregate(unique_ptr> &filters) { unique_ptr FilterPushdown::PushdownCrossProduct(unique_ptr op) { D_ASSERT(op->children.size() > 1); - FilterPushdown left_pushdown(optimizer, convert_mark_joins, projection_mode); - FilterPushdown right_pushdown(optimizer, convert_mark_joins, projection_mode); + FilterPushdown left_pushdown(optimizer, projection_mode); + FilterPushdown right_pushdown(optimizer, projection_mode); vector> join_expressions; vector> deferred_filters; auto join_ref_type = JoinRefType::REGULAR; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp index b9c5115c6..351690036 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp @@ -112,8 +112,8 @@ unique_ptr FilterPushdown::PushdownLeftJoin(unique_ptr &left_bindings, unordered_set &right_bindings) { auto &join = op->Cast(); - FilterPushdown left_pushdown(optimizer, convert_mark_joins, projection_mode); - FilterPushdown right_pushdown(optimizer, convert_mark_joins, projection_mode); + FilterPushdown left_pushdown(optimizer, projection_mode); + FilterPushdown right_pushdown(optimizer, projection_mode); // for a comparison join we create a FilterCombiner that checks if we can push conditions on LHS join conditions // into the RHS of the join FilterCombiner filter_combiner(optimizer); diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp index 3b2a43326..44ef8c5c2 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp @@ -1,110 +1,24 @@ #include "duckdb/optimizer/filter_pushdown.hpp" -#include "duckdb/planner/expression/bound_operator_expression.hpp" -#include "duckdb/planner/expression_nullability.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" namespace duckdb { -using Filter = FilterPushdown::Filter; - -static void SimplifyNullSafeSemiJoinConditions(ClientContext &context, LogicalComparisonJoin &join) { - D_ASSERT(join.join_type == JoinType::SEMI); - NotNullExpressionAnalyzer analyzer(context); - for (auto &cond : join.conditions) { - if (!cond.IsComparison() || cond.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { - continue; - } - // Once a MARK join is reduced to SEMI, a null-safe equality is equivalent to regular equality if either - // join key is known not to be NULL. Regular equality unlocks the existing runtime-filter infrastructure. - if (!analyzer.IsNotNull(*join.children[0], cond.GetLHS()) && - !analyzer.IsNotNull(*join.children[1], cond.GetRHS())) { - continue; - } - cond = - JoinCondition(cond.LeftReference()->Copy(), cond.RightReference()->Copy(), ExpressionType::COMPARE_EQUAL); - } -} - unique_ptr FilterPushdown::PushdownMarkJoin(unique_ptr op, unordered_set &left_bindings, unordered_set &right_bindings) { - auto op_bindings = op->GetColumnBindings(); - auto &join = op->Cast(); - auto &comp_join = op->Cast(); + auto &join = op->Cast(); D_ASSERT(join.join_type == JoinType::MARK); - D_ASSERT(op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN || - op->type == LogicalOperatorType::LOGICAL_DELIM_JOIN || op->type == LogicalOperatorType::LOGICAL_ASOF_JOIN); - - right_bindings.insert(comp_join.mark_index); - FilterPushdown left_pushdown(optimizer, convert_mark_joins, projection_mode); - FilterPushdown right_pushdown(optimizer, convert_mark_joins, projection_mode); -#ifdef DEBUG - bool simplified_mark_join = false; -#endif - // now check the set of filters + right_bindings.insert(join.mark_index); + FilterPushdown left_pushdown(optimizer, projection_mode); + FilterPushdown right_pushdown(optimizer, projection_mode); for (idx_t i = 0; i < filters.size(); i++) { - auto side = JoinSide::GetJoinSide(filters[i]->bindings, left_bindings, right_bindings); - if (side == JoinSide::LEFT) { - // bindings match left side: push into left + if (JoinSide::GetJoinSide(filters[i]->bindings, left_bindings, right_bindings) == JoinSide::LEFT) { left_pushdown.filters.push_back(std::move(filters[i])); - // erase the filter from the list of filters - filters.erase_at(i); - i--; - } else if (side == JoinSide::RIGHT) { -#ifdef DEBUG - D_ASSERT(!simplified_mark_join); -#endif - // this filter references the marker - // we can turn this into a SEMI join if the filter is on only the marker - if (filters[i]->filter->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF && convert_mark_joins && - comp_join.convert_mark_to_semi) { - // filter just references the marker: turn into semi join -#ifdef DEBUG - simplified_mark_join = true; -#endif - join.join_type = JoinType::SEMI; - filters.erase_at(i); - i--; - continue; - } - // if the filter is on NOT(marker) AND the join conditions are all set to "null_values_are_equal" we can - // turn this into an ANTI join if all join conditions have null_values_are_equal=true, then the result of - // the MARK join is always TRUE or FALSE, and never NULL this happens in the case of a correlated EXISTS - // clause - if (filters[i]->filter->GetExpressionType() == ExpressionType::OPERATOR_NOT) { - auto &op_expr = filters[i]->filter->Cast(); - if (op_expr.GetChildren()[0]->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) { - // the filter is NOT(marker), check the join conditions - bool all_null_values_are_equal = true; - for (auto &cond : comp_join.conditions) { - if (!cond.IsComparison()) { - continue; - } - if (cond.GetComparisonType() != ExpressionType::COMPARE_DISTINCT_FROM && - cond.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { - all_null_values_are_equal = false; - break; - } - } - if (all_null_values_are_equal && convert_mark_joins && comp_join.convert_mark_to_semi) { -#ifdef DEBUG - simplified_mark_join = true; -#endif - // all null values are equal, convert to ANTI join - join.join_type = JoinType::ANTI; - filters.erase_at(i); - i--; - continue; - } - } - } + filters.erase_at(i--); } } left_pushdown.RewriteChild(*op, 0); right_pushdown.RewriteChild(*op, 1); - if (join.join_type == JoinType::SEMI) { - SimplifyNullSafeSemiJoinConditions(GetContext(), comp_join); - } return PushFinalFilters(std::move(op)); } diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp index 32dc2737d..8e481476d 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_outer_join.cpp @@ -181,8 +181,8 @@ unique_ptr FilterPushdown::PushdownOuterJoin(unique_ptrCast(); D_ASSERT(join.join_type == JoinType::OUTER); - FilterPushdown left_pushdown(optimizer, convert_mark_joins, projection_mode); - FilterPushdown right_pushdown(optimizer, convert_mark_joins, projection_mode); + 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)); }); diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp index 5db52b01d..baa70344c 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp @@ -162,7 +162,7 @@ unique_ptr FilterPushdown::PushdownProjection(unique_ptr> remain_expressions; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_secure_view.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_secure_view.cpp index e2f971af6..72fa75a5b 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_secure_view.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_secure_view.cpp @@ -42,7 +42,7 @@ unique_ptr FilterPushdown::PushdownSecureView(unique_ptrSetEstimatedCardinality(op->children[0]->EstimateCardinality(optimizer.GetContext())); } - FilterPushdown child_pushdown(optimizer, convert_mark_joins, projection_mode); + FilterPushdown child_pushdown(optimizer, projection_mode); for (auto &f : filters) { auto expr = std::move(f->filter); if (secure_view.has_source) { diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp index 5b5bb6fb6..66e69f92c 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp @@ -12,7 +12,7 @@ using Filter = FilterPushdown::Filter; unique_ptr FilterPushdown::PushdownSemiAntiJoin(unique_ptr op) { auto &join = op->Cast(); - FilterPushdown right_pushdown(optimizer, convert_mark_joins, projection_mode); + FilterPushdown right_pushdown(optimizer, projection_mode); if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && !filters.empty()) { // a right row that matches a left row passes what the filters imply for the right side vector> left_filters; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp index cfcf27a9d..d974ce756 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp @@ -1,4 +1,5 @@ #include "duckdb/optimizer/filter_pushdown.hpp" +#include "duckdb/optimizer/filter_combiner.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" @@ -25,21 +26,86 @@ static void ReplaceSetOpBindings(vector &bindings, Filter &filter }); } +//! Whether a filter on the left child of an EXCEPT / INTERSECT keeps or removes all the rows that the set operation +//! treats as equal. Only such a filter may run before the set operation, which returns some of the equal rows: it +//! reads only columns that are compared as they are, or it compares what a column is compared as (the column under +//! its collation) with constants. This is what a filter needs to pass the row_number() windows of CreateJoin as well. +static bool KeepsEqualRowsTogether(const Expression &filter, const vector &comparisons) { + if (filter.IsVolatile()) { + return false; + } + auto compared = FilterCombiner::GetComparedExpression(filter); + if (compared) { + for (auto &comparison : comparisons) { + if (comparison.GetLHS().Equals(*compared)) { + return true; + } + } + } + bool plain_columns = true; + ExpressionIterator::VisitExpression(filter, [&](const BoundColumnRefExpression &colref) { + bool compared_as_is = false; + for (auto &comparison : comparisons) { + auto &left = comparison.GetLHS(); + if (left.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && + left.Cast().Binding() == colref.Binding()) { + compared_as_is = true; + } + } + plain_columns = plain_columns && compared_as_is; + }); + return plain_columns; +} + unique_ptr FilterPushdown::PushdownSetOperation(unique_ptr op) { D_ASSERT(op->type == LogicalOperatorType::LOGICAL_UNION || op->type == LogicalOperatorType::LOGICAL_EXCEPT || op->type == LogicalOperatorType::LOGICAL_INTERSECT); auto &setop = op->Cast(); - for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { + if (op->type != LogicalOperatorType::LOGICAL_UNION) { + vector> remaining_filters; + // EXCEPT and INTERSECT return rows of their left child: a filter on the result applies to the left child if it + // does not tell the rows apart that the set operation treats as equal, otherwise it stays above. A right row + // that fails what the filters imply for it through the comparisons only has left rows as equals that the + // filters remove, so the implied filters apply to the right child + D_ASSERT(op->children.size() == 2); + auto comparisons = setop.GetComparisons(optimizer.context); + auto left_bindings = op->children[0]->GetColumnBindings(); + FilterPushdown left_pushdown(optimizer, projection_mode); + FilterPushdown right_pushdown(optimizer, projection_mode); + for (auto &original_filter : filters) { + auto filter = make_uniq(); + filter->filter = original_filter->filter->Copy(); + ReplaceSetOpBindings(left_bindings, *filter, filter->filter, setop); + if (!KeepsEqualRowsTogether(*filter->filter, comparisons)) { + remaining_filters.push_back(std::move(original_filter)); + continue; + } + filter->ExtractBindings(); + filter->ExtractBarrier(); + left_pushdown.filters.push_back(std::move(filter)); + } + vector> left_filters; + for (auto &filter : left_pushdown.filters) { + left_filters.push_back(*filter->filter); + } + if (!left_filters.empty()) { + FilterCombiner::GenerateJoinFilters( + comparisons, left_filters, JoinSide::RIGHT, + [&](unique_ptr right_filter) { right_pushdown.AddFilter(std::move(right_filter)); }); + right_pushdown.GenerateFilters(); + } + op->children[0] = left_pushdown.Rewrite(std::move(op->children[0])); + op->children[1] = right_pushdown.Rewrite(std::move(op->children[1])); + filters = std::move(remaining_filters); + } + + for (idx_t child_idx = 0; child_idx < op->children.size() && op->type == LogicalOperatorType::LOGICAL_UNION; + child_idx++) { auto &child = op->children[child_idx]; auto child_bindings = child->GetColumnBindings(); - FilterPushdown child_pushdown(optimizer, convert_mark_joins, projection_mode); - // a filter on the result of EXCEPT and INTERSECT only applies to their left child - if (child_idx > 0 && op->type != LogicalOperatorType::LOGICAL_UNION) { - child = child_pushdown.Rewrite(std::move(child)); - continue; - } + FilterPushdown child_pushdown(optimizer, projection_mode); for (auto &original_filter : filters) { // first create a copy of the filter auto filter = make_uniq(); @@ -58,6 +124,10 @@ unique_ptr FilterPushdown::PushdownSetOperation(unique_ptrtype == LogicalOperatorType::LOGICAL_UNION) { + // every filter went into every child + filters.clear(); + } bool all_empty = true; for (auto &child : op->children) { if (child->type != LogicalOperatorType::LOGICAL_EMPTY_RESULT) { @@ -99,7 +169,7 @@ unique_ptr FilterPushdown::PushdownSetOperation(unique_ptrchildren[0]->Cast(); projection.table_index = setop.table_index; - return std::move(op->children[0]); + return PushFinalFilters(std::move(op->children[0])); } break; case LogicalOperatorType::LOGICAL_INTERSECT: @@ -109,7 +179,7 @@ unique_ptr FilterPushdown::PushdownSetOperation(unique_ptr FilterPushdown::PushdownSingleJoin(unique_ptr &left_bindings, unordered_set &right_bindings) { D_ASSERT(op->Cast().join_type == JoinType::SINGLE); - FilterPushdown left_pushdown(optimizer, convert_mark_joins, projection_mode); - FilterPushdown right_pushdown(optimizer, convert_mark_joins, projection_mode); + FilterPushdown left_pushdown(optimizer, projection_mode); + FilterPushdown right_pushdown(optimizer, projection_mode); // now check the set of filters for (idx_t i = 0; i < filters.size(); i++) { auto side = JoinSide::GetJoinSide(filters[i]->bindings, left_bindings, right_bindings); diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_unnest.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_unnest.cpp index bd29926cd..2f6b53577 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_unnest.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_unnest.cpp @@ -12,7 +12,7 @@ unique_ptr FilterPushdown::PushdownUnnest(unique_ptr> remain_expressions; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp index dd5a6a894..e34615fc9 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp @@ -1,9 +1,13 @@ #include "duckdb/optimizer/filter_pushdown.hpp" +#include "duckdb/execution/expression_executor.hpp" #include "duckdb/function/window_function.hpp" #include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/planner/operator/logical_window.hpp" @@ -32,7 +36,7 @@ bool CanPushdownFilter(vector window_exprs_partition_bindi return filter_on_all_partitions; } -unique_ptr CreateAuxiliaryFilter(const Expression &partition, const Filter &filter) { +unique_ptr CreateAuxiliaryFilter(ClientContext &context, const Expression &partition, const Filter &filter) { // Must be comparison if (!BoundComparisonExpression::IsComparison(*filter.filter)) { return nullptr; @@ -104,8 +108,20 @@ unique_ptr CreateAuxiliaryFilter(const Expression &partition, const Filt auto e_b = partition_func.Copy(); auto c_b = partition_func.Copy(); c_b->Cast().GetChildrenMutable()[0] = children[const_idx]->Copy(); - auto aux_comp = BoundComparisonExpression::Create(aux_type, std::move(e_b), std::move(c_b)); - auto aux_filter = make_uniq(std::move(aux_comp)); + // e can be NULL for a non-NULL argument (e.g. year(infinity)), which leaves nothing to compare e(b) with + Value c_value, e_c_value; + if (!ExpressionExecutor::TryEvaluateScalar(context, *children[const_idx], c_value) || + !ExpressionExecutor::TryEvaluateScalar(context, *c_b, e_c_value) || (e_c_value.IsNull() && !c_value.IsNull())) { + return nullptr; + } + // and the rows where e(b) is NULL form a partition that has to be kept whole + auto e_b_is_null = + make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN, e_b->Copy()); + auto e_c = make_uniq(std::move(e_c_value)); + auto aux_comp = BoundComparisonExpression::Create(aux_type, std::move(e_b), std::move(e_c)); + auto aux_expr = make_uniq(ExpressionType::CONJUNCTION_OR, std::move(aux_comp), + std::move(e_b_is_null)); + auto aux_filter = make_uniq(std::move(aux_expr)); aux_filter->ExtractBindings(); aux_filter->ExtractBarrier(); @@ -160,7 +176,7 @@ bool FilterPushdown::OnlyRanksWithoutArguments(const LogicalWindow &window) { unique_ptr FilterPushdown::PushdownWindow(unique_ptr op) { D_ASSERT(op->type == LogicalOperatorType::LOGICAL_WINDOW); auto &window = op->Cast(); - FilterPushdown pushdown(optimizer, convert_mark_joins, projection_mode); + FilterPushdown pushdown(optimizer, projection_mode); // 1. Loop through the expressions, find the window expressions and investigate the partitions // if a filter applies to a partition in each window expression then you can push the filter @@ -235,7 +251,7 @@ unique_ptr FilterPushdown::PushdownWindow(unique_ptr +RelationStatisticsHelper::EstimateTupleDomainRestriction(LogicalComparisonJoin &restriction, const RelationStats &input, + const RelationStats &keys, RelationStatsExtractor &extractor) { + D_ASSERT(restriction.join_type == JoinType::SEMI && restriction.conditions.size() > 1); + if (input.cardinality == 0 || keys.cardinality == 0) { + return TupleDomainRestrictionEstimate {0, 0}; + } + if (!(input.row_retention > 0 && input.row_retention <= 1 && keys.row_retention > 0 && keys.row_retention <= 1)) { + return {}; + } + vector input_columns; + vector key_columns; + vector total_domains; + double marginal_fraction = 1; + for (auto &condition : restriction.conditions) { + D_ASSERT(condition.IsComparison()); + auto input_index = input.FindColumn(condition.GetLHS().Cast().Binding()); + auto key_index = keys.FindColumn(condition.GetRHS().Cast().Binding()); + if (!input_index.IsValid() || !key_index.IsValid()) { + return {}; + } + auto &input_column = input.columns[input_index.GetIndex()]; + auto &key_column = keys.columns[key_index.GetIndex()]; + auto total = SelectTotalDomain({input_column.total_domain, key_column.total_domain}); + if (!total || total->source == DistinctCountSource::CARDINALITY || total->distinct_count == 0) { + return {}; + } + auto supported = key_column.GetSupportedSemiAntiDomainSize(); + if (supported.IsValid()) { + marginal_fraction = MinValue(marginal_fraction, static_cast(supported.GetIndex()) / + static_cast(total->distinct_count)); + } + input_columns.push_back(input_index.GetIndex()); + key_columns.push_back(key_index.GetIndex()); + total_domains.push_back(*total); + } + auto input_groups = EstimateGroupCardinality(*restriction.children[0], input, std::move(input_columns), extractor); + auto key_groups = EstimateGroupCardinality(*restriction.children[1], keys, std::move(key_columns), extractor); + // The total tuple domain predates filters; only current tuple counts are capped by current rows. + auto source_rows = MaxValue(static_cast(input.cardinality) / input.row_retention, + static_cast(keys.cardinality) / keys.row_retention); + auto total_groups = EstimateDistinctCardinality(total_domains, CardinalityFromDouble(source_rows)); + if (total_groups == 0) { + return {}; + } + auto fraction = MinValue(marginal_fraction, static_cast(key_groups) / static_cast(total_groups)); + auto rows = MinValue(static_cast(input.cardinality), + MaxValue(1.0, round(static_cast(input.cardinality) * fraction))); + // Full marginal domains need not cover every tuple, e.g. a diagonal against a Cartesian input. + auto groups = MinValue(rows, static_cast(MinValue(input_groups, key_groups))); + return TupleDomainRestrictionEstimate {rows, groups}; +} + static bool TryMapProjectionGroups(LogicalOperator &op, vector &groups) { auto child_bindings = op.children[0]->GetColumnBindings(); vector mapped; @@ -450,6 +505,25 @@ idx_t RelationStatisticsHelper::EstimateGroupCardinality(LogicalOperator &input, return estimate; } +static optional_ptr GetSelectedValueStats(const Expression &expression, + const RelationColumnStatsLookup &child_columns) { + if (expression.GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) { + return nullptr; + } + const auto &aggregate = expression.Cast(); + if (aggregate.StateExportMode() != AggregateStateExportMode::NONE || aggregate.GetChildren().size() != 1 || + !IsFirstLastOrAnyValue(aggregate.Function())) { + return nullptr; + } + // The selected value has a known domain only for a direct, type-preserving column reference. + const auto &argument = *aggregate.GetChildren()[0]; + if (argument.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + !argument.GetReturnType().EqualsIncludingCollation(aggregate.GetReturnType())) { + return nullptr; + } + return child_columns.Find(argument.Cast().Binding()); +} + static optional ExtractAggregationStatsInternal(LogicalAggregate &aggregate, const RelationStats &child_stats, RelationStatsExtractor &extractor, @@ -510,6 +584,14 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate ? 1 : RelationStatisticsHelper::EstimateDistinctCardinality(cardinality_counts, child_stats.cardinality); } + bool has_unique_groups = false; + if (preserves_group_evidence && !aggregate.groups.empty() && aggregate.children.size() == 1) { + Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS, extractor.GetContext()); + has_unique_groups = distinctness.IsDistinctOn(*aggregate.children[0], aggregate.groups); + if (has_unique_groups) { + result.cardinality = child_stats.cardinality; + } + } for (idx_t group_idx = 0; group_idx < aggregate.groups.size(); group_idx++) { auto &group = *aggregate.groups[group_idx]; DistinctCount distinct_count(result.cardinality, DistinctCountSource::CARDINALITY); @@ -536,9 +618,32 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate result.columns.emplace_back(bindings[result.columns.size()], distinct_count, current_domain, Identifier(), semi_anti_join_domain_evidence); } - for (idx_t aggregate_idx = 0; aggregate_idx < aggregate.expressions.size(); aggregate_idx++) { - result.columns.emplace_back(bindings[result.columns.size()], - DistinctCount(result.cardinality, DistinctCountSource::CARDINALITY), Identifier()); + for (auto &expression : aggregate.expressions) { + DistinctCount total_domain(result.cardinality, DistinctCountSource::CARDINALITY); + DistinctCount current_domain = total_domain; + if (has_unique_groups && expression->GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE) { + auto &bound_aggregate = expression->Cast(); + auto &agg_children = bound_aggregate.GetChildren(); + if (bound_aggregate.CanForwardSingletonInputDomain() && !bound_aggregate.GetFilter() && + !agg_children.empty() && expression->GetReturnType() == agg_children[0]->GetReturnType() && + agg_children[0]->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto binding = agg_children[0]->Cast().Binding(); + auto child_column = child_columns.Find(binding); + if (child_column) { + result.columns.emplace_back(bindings[result.columns.size()], child_column->total_domain, + child_column->current_domain, Identifier()); + continue; + } + } + } + // A selector can bias which values survive. Only the total domain keeps the + // source confidence; the common cardinality cap below bounds the current domain. + if (auto source = GetSelectedValueStats(*expression, child_columns)) { + total_domain = source->total_domain; + current_domain.distinct_count = + MinValue(source->current_domain.distinct_count, total_domain.distinct_count); + } + result.columns.emplace_back(bindings[result.columns.size()], total_domain, current_domain, Identifier()); } for (idx_t grouping_idx = 0; grouping_idx < aggregate.grouping_functions.size(); grouping_idx++) { auto grouping_count = MinValue(result.cardinality, MaxValue(aggregate.grouping_sets.size(), 1)); diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp index cbf6e4239..4022af375 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp @@ -91,12 +91,43 @@ static vector ExtractSemiAntiJoinDomains(LogicalComparisonJo has_residual = true; continue; } + // Row-count fallbacks bound domains but do not estimate membership coverage. + if (total_domain->source == DistinctCountSource::CARDINALITY) { + has_residual = true; + } domains.push_back( {total_domain->distinct_count, rhs_current_domain.GetIndex(), lhs_preserved->binding, rhs_column->binding}); } return domains; } +static SemiAntiJoinCardinalityEstimate EstimateSemiAntiJoin(LogicalComparisonJoin &join, const RelationStats &preserved, + const RelationStats &rhs, + const vector &domains, + bool has_residual) { + auto estimate = RelationStatisticsHelper::EstimateSemiAntiJoinCardinality( + static_cast(preserved.cardinality), rhs.cardinality, rhs.row_retention, join.join_type, domains, + has_residual); + auto is_semi = join.join_type == JoinType::SEMI || join.join_type == JoinType::RIGHT_SEMI; + if (!is_semi || join.children.size() != 2) { + return estimate; + } + auto rhs_index = join.join_type == JoinType::RIGHT_SEMI ? 0 : 1; + optional_ptr rhs_op = join.children[rhs_index].get(); + while (rhs_op->type == LogicalOperatorType::LOGICAL_PROJECTION && rhs_op->children.size() == 1) { + rhs_op = rhs_op->children[0].get(); + } + if (rhs_op->type == LogicalOperatorType::LOGICAL_CHUNK_GET) { + // Constant-list domains do not describe the frequency of matching values. + auto fallback = RelationStatisticsHelper::EstimateSemiAntiJoinFallback( + static_cast(preserved.cardinality), rhs.cardinality, join.join_type); + if (estimate.cardinality < fallback.cardinality) { + return fallback; + } + } + return estimate; +} + SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinCardinality(LogicalComparisonJoin &join, const RelationStats &left, const RelationStats &right) { @@ -105,8 +136,7 @@ SemiAntiJoinCardinalityEstimate RelationStatisticsHelper::EstimateSemiAntiJoinCa auto &rhs = preserve_right ? left : right; bool has_residual; auto domains = ExtractSemiAntiJoinDomains(join, preserved, rhs, has_residual); - return EstimateSemiAntiJoinCardinality(static_cast(preserved.cardinality), rhs.cardinality, - rhs.row_retention, join.join_type, domains, has_residual); + return EstimateSemiAntiJoin(join, preserved, rhs, domains, has_residual); } void RelationStatisticsHelper::ApplySemiAntiJoinStats(LogicalComparisonJoin &join, const RelationStats &left, @@ -119,8 +149,7 @@ void RelationStatisticsHelper::ApplySemiAntiJoinStats(LogicalComparisonJoin &joi D_ASSERT(result.cardinality == preserved.cardinality); bool has_residual; auto domains = ExtractSemiAntiJoinDomains(join, preserved, rhs, has_residual); - auto estimate = EstimateSemiAntiJoinCardinality(static_cast(preserved.cardinality), rhs.cardinality, - rhs.row_retention, join.join_type, domains, has_residual); + auto estimate = EstimateSemiAntiJoin(join, preserved, rhs, domains, has_residual); result.row_retention = preserved.row_retention; // Keep exact empty-input results and the original integer upper limit across double conversion. auto cardinality = MinValue(preserved.cardinality, CardinalityFromDouble(estimate.cardinality)); @@ -378,6 +407,8 @@ RelationStatisticsHelper::ExtractOperatorStats(LogicalOperator &op, ClientContex } case LogicalOperatorType::LOGICAL_ORDER_BY: return child_stats.size() == 1 ? ProjectOutputStats(child_stats[0].get(), op) : optional(); + case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: + return child_stats.size() == 2 ? ProjectOutputStats(child_stats[1].get(), op) : optional(); case LogicalOperatorType::LOGICAL_UNNEST: return ExtractUnnestStats(op, child_stats[0].get()); case LogicalOperatorType::LOGICAL_LIMIT: { diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp index 26e9042bf..b738f0f21 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp @@ -1,9 +1,11 @@ #include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" +#include "duckdb/catalog/catalog_entry/duck_table_entry.hpp" #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/subtract.hpp" #include "duckdb/common/types/hugeint.hpp" +#include "duckdb/function/partition_stats.hpp" #include "duckdb/function/table/table_scan.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" @@ -17,6 +19,7 @@ #include "duckdb/planner/operator/logical_expression_get.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/storage/data_table.hpp" #include "duckdb/storage/statistics/numeric_stats.hpp" namespace duckdb { @@ -372,6 +375,102 @@ static void ApplyDirectFilterDomain(RelationColumnStats &column, const Expressio expression, binding, column.total_domain.distinct_count)); } +//===--------------------------------------------------------------------===// +// Zonemap bound +//===--------------------------------------------------------------------===// +struct ZonemapFilter { + ZonemapFilter(const Expression &expr, const LogicalType &column_type, StorageIndex storage_index_p) + : expr(expr), column_type(column_type), storage_index(std::move(storage_index_p)) { + } + + const Expression &expr; + const LogicalType &column_type; + StorageIndex storage_index; +}; + +//! An upper bound on the rows that a scan of a DuckDB table returns: the rows of the row groups whose zonemaps +//! can satisfy every table filter of the scan. A row group that cannot be skipped counts whole. +//! Returns an invalid index if the bound is not below the estimate that the scan already has. +static optional_idx ZonemapFilterBound(LogicalGet &get, ClientContext &context, + const vector &scan_statistics, idx_t estimate) { + //! The work per plan is limited to the row groups of a table of this many row groups (2 billion rows at the + //! default row group size). A larger table keeps its estimate: checking only some of its row groups would not + //! give a bound, as the row groups that are not checked can hold all of the matching rows + static constexpr idx_t ZONEMAP_MAX_ROW_GROUPS = 16384; + + auto table = get.GetTable(); + if (!table || !table->IsDuckTable() || !get.function.get_partition_stats) { + return optional_idx(); + } + vector filters; + for (auto &entry : get.table_filters) { + if (ExpressionFilter::IsOptionalFilter(entry.Filter())) { + // optional filters do not restrict the result of the scan + continue; + } + auto &filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "ZonemapFilterBound"); + if (filter.expr->HasParameter()) { + continue; + } + const auto column_idx = entry.GetIndex().GetIndex(); + if (column_idx >= get.GetColumnIds().size() || column_idx >= scan_statistics.size()) { + continue; + } + StorageIndex storage_index; + if (!get.TryGetStorageIndex(get.GetColumnIds()[column_idx], storage_index)) { + continue; + } + filters.emplace_back(*filter.expr, scan_statistics[column_idx].GetType(), std::move(storage_index)); + } + if (filters.empty()) { + return optional_idx(); + } + // the limit is checked before any row group is loaded or collected, and covers the row groups of the table + // and the ones that the transaction has added + auto &storage = table->Cast().GetStorage(); + if (storage.GetRowGroupCountWithoutLoading(context) > ZONEMAP_MAX_ROW_GROUPS) { + return optional_idx(); + } + + GetPartitionStatsInput input(get.function, get.bind_data.get()); + auto partitions = get.function.get_partition_stats(context, input); + if (partitions.empty() || partitions.size() > ZONEMAP_MAX_ROW_GROUPS) { + return optional_idx(); + } + // the rows of the row groups that no filter skips + idx_t matching_rows = 0; + for (auto &partition : partitions) { + bool skipped = false; + for (auto &filter : filters) { + if (!partition.partition_row_group) { + break; + } + auto stats = partition.partition_row_group->GetColumnStatistics(filter.storage_index); + if (!stats || !stats->GetType().EqualsIncludingCollation(filter.column_type)) { + // without statistics the row group cannot be skipped for this filter + continue; + } + // the check that the scan uses to skip the row group + auto pruning = ExpressionFilter::CheckExpressionStatistics(context, filter.expr, *stats); + if (pruning == FilterPropagateResult::FILTER_ALWAYS_FALSE || + pruning == FilterPropagateResult::FILTER_FALSE_OR_NULL) { + skipped = true; + break; + } + } + if (skipped) { + continue; + } + matching_rows += partition.count; + if (matching_rows >= estimate) { + // the bound only grows from here on: it cannot improve on the estimate, so the remaining row groups + // need not be read + return optional_idx(); + } + } + return MaxValue(1, matching_rows); +} + unique_ptr RelationStatisticsHelper::GetColumnStatistics(LogicalGet &get, ClientContext &context, const ColumnIndex &column_id) { if (!get.bind_data || (!get.function.statistics && !get.function.statistics_extended)) { @@ -433,6 +532,20 @@ RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientC estimate.Combine({range_cardinality, true}); } } + if (get.table_filters.HasFilters()) { + // the scan skips the row groups whose zonemaps cannot satisfy the filters: their rows bound the estimate + auto current_estimate = estimate.cardinality; + if (!estimate.supported) { + current_estimate = MinValue(current_estimate, FilterFraction(base_table_cardinality, DEFAULT_SELECTIVITY)); + } + // an estimate of at most one row cannot be improved + if (current_estimate > 1) { + auto zonemap_bound = ZonemapFilterBound(get, context, scan_statistics, current_estimate); + if (zonemap_bound.IsValid()) { + estimate.Combine({zonemap_bound.GetIndex(), true}); + } + } + } ApplyFilterEstimate(result, estimate); for (auto &column : result.columns) { for (auto &entry : get.table_filters) { diff --git a/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp b/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp index a4af565f9..1f88584e9 100644 --- a/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp +++ b/src/duckdb/src/optimizer/remote_pushdown_optimizer.cpp @@ -40,6 +40,7 @@ #include "duckdb/parser/tableref/basetableref.hpp" #include "duckdb/parser/tableref/expressionlistref.hpp" #include "duckdb/parser/tableref/joinref.hpp" +#include "duckdb/parser/tableref/pivotref.hpp" #include "duckdb/parser/tableref/subqueryref.hpp" #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/parser/expression/columnref_expression.hpp" @@ -109,18 +110,25 @@ void RemotePushdownOptimizer::FindRemoteCatalogsInSearchPath() { } } -void RemotePushdownOptimizer::ResolveQualification(const QualifiedName &name, Identifier &catalog_name, - vector &schema_path) { +bool RemotePushdownOptimizer::ResolveQualification(const QualifiedName &name, Identifier &catalog_name, + vector &schema_path, CatalogType type) { // BindTableName resolves the "x.name" catalog-or-schema ambiguity the same way the binder does, and returns // [catalog, schema path..., name] - so a nested schema path survives instead of collapsing onto Catalog() if (name.Path().empty()) { - return; + return true; } auto bound = Binder::BindTableName(binder.EntryRetriever(), name); + if (!bound.Catalog().empty()) { + auto catalog = Catalog::GetCatalogEntry(binder.context, bound.Catalog()); + if (catalog && !catalog->SupportsSchemaPath(bound, type)) { + return false; + } + } catalog_name = bound.Catalog(); bound.StripCatalog(); auto &path = bound.Path(); schema_path.assign(path.begin(), path.end() - 1); + return true; } optional_ptr RemotePushdownOptimizer::LookupEntry(const Identifier &catalog_name, @@ -630,7 +638,9 @@ CatalogPushdownResult RemotePushdownOptimizer::ResolveDDLTarget(const QualifiedN CatalogType entry_type) { Identifier catalog_name; vector schema_path; - ResolveQualification(name, catalog_name, schema_path); + if (!ResolveQualification(name, catalog_name, schema_path, entry_type)) { + return CatalogPushdownResult::Unknown(); + } if (!catalog_name.empty()) { return ResolveRemoteCatalog(catalog_name, RemoteCapability::EXECUTE_STATEMENT); } @@ -752,10 +762,6 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteStatement(DropStatement &s return CatalogPushdownResult::Unknown(); } auto target = ResolveDDLTarget(info.GetQualifiedName(), DDLTarget::EXISTING_ENTRY, info.type); - if (info.type == CatalogType::SCHEMA_ENTRY && target.catalog && !target.catalog->SupportsNestedSchemas()) { - target.catalog->CheckNestedSchemaSupport(binder.ResolveCatalog(binder.context, info.GetQualifiedName()), - info.type); - } return VerifyStatementSupport(statement, std::move(target)); } @@ -866,7 +872,10 @@ CatalogPushdownResult RemotePushdownOptimizer::RewriteTableFunctionOnly(TableFun // Figure out Identifier catalog_name; vector schema_path; - ResolveQualification(func_expr.GetQualifiedName(), catalog_name, schema_path); + if (!ResolveQualification(func_expr.GetQualifiedName(), catalog_name, schema_path)) { + TrackLocalTable(ref); + return CatalogPushdownResult::Unknown(); + } // If the function has an explicit catalog prefix, check if it's remote if (!catalog_name.empty()) { @@ -1009,7 +1018,10 @@ CatalogPushdownResult RemotePushdownOptimizer::Rewrite(BaseTableRef &ref) { // (possibly nested) schema path, so a reference like s1.child.t is not mistaken for catalog "s1" Identifier catalog_name; vector schema_path; - ResolveQualification(ref.GetQualifiedName(), catalog_name, schema_path); + if (!ResolveQualification(ref.GetQualifiedName(), catalog_name, schema_path)) { + TrackLocalTable(ref); + return CatalogPushdownResult::Unknown(); + } // Case 0: check if this is a CTE reference (must have no explicit catalog/schema) if (catalog_name.empty() && schema_path.empty()) { @@ -1088,7 +1100,9 @@ CatalogPushdownResult RemotePushdownOptimizer::CheckCatalogQualification(const P const QualifiedName &name) { Identifier catalog_name; vector schema_path; - ResolveQualification(name, catalog_name, schema_path); + if (!ResolveQualification(name, catalog_name, schema_path)) { + return CatalogPushdownResult::Unknown(); + } if (catalog_name.empty()) { return CatalogPushdownResult::NoCatalogReference(); } @@ -1357,6 +1371,24 @@ void RemotePushdownOptimizer::StripCatalogName(TableRef &ref, const Identifier & } break; } + case TableReferenceType::PIVOT: { + auto &pivot_ref = ref.Cast(); + StripCatalogName(*pivot_ref.source, catalog_name); + for (auto &aggr : pivot_ref.aggregates) { + StripCatalogName(*aggr, catalog_name); + } + for (auto &pivot : pivot_ref.pivots) { + for (auto &expr : pivot.pivot_expressions) { + StripCatalogName(*expr, catalog_name); + } + for (auto &entry : pivot.entries) { + if (entry.expr) { + StripCatalogName(*entry.expr, catalog_name); + } + } + } + break; + } default: break; } diff --git a/src/duckdb/src/optimizer/remove_duplicate_groups.cpp b/src/duckdb/src/optimizer/remove_duplicate_groups.cpp index ef7363cf5..347c807aa 100644 --- a/src/duckdb/src/optimizer/remove_duplicate_groups.cpp +++ b/src/duckdb/src/optimizer/remove_duplicate_groups.cpp @@ -1,6 +1,5 @@ #include "duckdb/optimizer/remove_duplicate_groups.hpp" -#include "duckdb/common/type_visitor.hpp" #include "duckdb/optimizer/column_binding_replacer.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/planner/binder.hpp" @@ -38,23 +37,6 @@ bool CollectColumnRefBindings(const Expression &expr, column_binding_set_t &resu return ok; } -// Bases where SQL `=` doesn't imply bit-equality are unsafe: 0e0 == -0e0 (signbit distinguishes), -// '1 day' == '24 hour' (datepart distinguishes). INTERVAL today gets wrapped in -// normalized_interval(...) by the binder, so it shouldn't reach here, but we exclude it -// defensively in case that wrapping ever changes. -bool BaseTypeAllowsCollapse(const LogicalType &type) { - return !TypeVisitor::Contains(type, [](const LogicalType &t) { - switch (t.id()) { - case LogicalTypeId::FLOAT: - case LogicalTypeId::DOUBLE: - case LogicalTypeId::INTERVAL: - return true; - default: - return false; - } - }); -} - // Derived groups must reference a single bare column-ref base; non-colref bases would need a // per-derived injectivity proof. void CollectGroupRemovals(const LogicalAggregate &aggr, vector &removals, bool &any_derived) { @@ -91,7 +73,9 @@ void CollectGroupRemovals(const LogicalAggregate &aggr, vector &re if (base_it == first_occurrence.end()) { continue; } - if (!BaseTypeAllowsCollapse(groups[base_it->second.GetIndex()]->GetReturnType())) { + // a derived group is only a function of its base if the values of an equal base are identical: 0e0 = -0e0 + // (the sign bit distinguishes them), '1 day' = '24 hours' (datepart distinguishes them) + if (!groups[base_it->second.GetIndex()]->GetReturnType().EqualValuesAreIdentical()) { continue; } removals.push_back({group_idx, base_it->second, nullptr}); diff --git a/src/duckdb/src/optimizer/remove_redundant_distinct.cpp b/src/duckdb/src/optimizer/remove_redundant_distinct.cpp new file mode 100644 index 000000000..5fb0eca5d --- /dev/null +++ b/src/duckdb/src/optimizer/remove_redundant_distinct.cpp @@ -0,0 +1,62 @@ +#include "duckdb/optimizer/remove_redundant_distinct.hpp" + +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" + +namespace duckdb { + +namespace { + +//! An aggregate whose output rows are exactly its groups: no aggregate functions, no GROUPING functions and a single +//! grouping set that contains all groups +bool IsDuplicateElimination(LogicalOperator &op) { + if (op.type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + return false; + } + auto &aggr = op.Cast(); + if (!aggr.expressions.empty() || aggr.groups.empty() || !aggr.grouping_functions.empty() || + aggr.grouping_sets.size() > 1) { + return false; + } + return aggr.grouping_sets.empty() || aggr.grouping_sets[0].size() == aggr.groups.size(); +} + +//! Replaces a duplicate elimination by a projection of its groups. The projection takes over the group index, so +//! all references to the groups stay valid +void ReplaceByProjection(unique_ptr &op) { + auto &aggr = op->Cast(); + auto projection = make_uniq(aggr.group_index, std::move(aggr.groups)); + if (aggr.has_estimated_cardinality) { + projection->SetEstimatedCardinality(aggr.estimated_cardinality); + } + projection->children.push_back(std::move(aggr.children[0])); + projection->ResolveOperatorTypes(); + op = std::move(projection); +} + +} // namespace + +void RemoveRedundantDistinct::VisitOperator(unique_ptr &op) { + // bottom-up, so that the distinctness of an input is derived from its already reduced children + for (auto &child : op->children) { + VisitOperator(child); + } + if (!IsDuplicateElimination(*op)) { + return; + } + auto &aggr = op->Cast(); + column_binding_set_t keys; + for (auto &group : aggr.groups) { + if (group->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + return; + } + keys.insert(group->Cast().Binding()); + } + if (!distinctness.IsDistinctOn(*aggr.children[0], keys)) { + return; + } + ReplaceByProjection(op); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/row_group_pruner.cpp b/src/duckdb/src/optimizer/row_group_pruner.cpp index 9a9dc4e25..4690d3a53 100644 --- a/src/duckdb/src/optimizer/row_group_pruner.cpp +++ b/src/duckdb/src/optimizer/row_group_pruner.cpp @@ -47,15 +47,17 @@ bool RowGroupPruner::TryOptimize(LogicalOperator &op) const { return false; } - const auto op_type = current_op.get().type; - if (op_type == LogicalOperatorType::LOGICAL_LIMIT) { + switch (current_op.get().type) { + case LogicalOperatorType::LOGICAL_LIMIT: return false; - } - if (op_type == LogicalOperatorType::LOGICAL_FILTER || - op_type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY || - op_type == LogicalOperatorType::LOGICAL_WINDOW) { + case LogicalOperatorType::LOGICAL_ORDER_BY: + case LogicalOperatorType::LOGICAL_PROJECTION: + break; + default: + // Any other operator can change the row count, so we only order the row groups but do not prune row_limit.SetInvalid(); row_offset.SetInvalid(); + break; } current_op = *current_op.get().children[0]; } @@ -78,8 +80,9 @@ bool RowGroupPruner::TryOptimize(LogicalOperator &op) const { // We can use the RowGroupReorderer! const auto &primary_order = logical_order->orders[0]; + const bool has_secondary_order = logical_order->orders.size() > 1; auto options = CreateRowGroupReordererOptions(row_limit, row_offset, primary_order, *logical_get, storage_index, - logical_limit); + logical_limit, has_secondary_order); if (!options) { return false; } @@ -100,6 +103,12 @@ void RowGroupPruner::GetLimitAndOffset(const LogicalLimit &logical_limit, option } else if (logical_limit.offset_val.Type() == LimitNodeType::UNSET) { row_offset = 0; } + + const auto limit_type = logical_limit.limit_val.Type(); + if (limit_type == LimitNodeType::CONSTANT_PERCENTAGE || limit_type == LimitNodeType::EXPRESSION_PERCENTAGE) { + // A percentage limit counts the rows before the offset, so we cannot prune with the offset + row_offset.SetInvalid(); + } } optional_ptr RowGroupPruner::FindLogicalOrder(const LogicalLimit &logical_limit) const { @@ -163,16 +172,19 @@ optional_ptr RowGroupPruner::FindLogicalGet(const LogicalOrder &logi unique_ptr RowGroupPruner::CreateRowGroupReordererOptions(const optional_idx row_limit, const optional_idx row_offset, const BoundOrderByNode &primary_order, const LogicalGet &logical_get, - const StorageIndex &storage_index, LogicalLimit &logical_limit) const { + const StorageIndex &storage_index, LogicalLimit &logical_limit, + const bool has_secondary_order) const { const auto &colref = primary_order.expression->Cast(); const auto column_type = colref.GetReturnType() == LogicalType::VARCHAR ? OrderByColumnType::STRING : OrderByColumnType::NUMERIC; const auto order_type = primary_order.type; const auto null_order = primary_order.null_order; const auto order_by = order_type == OrderType::ASCENDING ? OrderByStatistics::MIN : OrderByStatistics::MAX; - optional_idx combined_limit = row_limit.IsValid() - ? row_limit.GetIndex() + (row_offset.IsValid() ? row_offset.GetIndex() : 0) - : optional_idx(); + // Without a known offset, we cannot tell which rows the limit keeps + optional_idx combined_limit; + if (row_limit.IsValid() && row_offset.IsValid()) { + combined_limit = row_limit.GetIndex() + row_offset.GetIndex(); + } if (row_offset.IsValid() && row_offset.GetIndex() > 0 && logical_get.function.get_partition_stats) { // Try to prune with offset @@ -180,8 +192,9 @@ RowGroupPruner::CreateRowGroupReordererOptions(const optional_idx row_limit, con auto partition_stats = logical_get.function.get_partition_stats(context, input); if (!partition_stats.empty()) { - auto offset_puning_result = RowGroupReorderer::GetOffsetAfterPruning( - order_by, column_type, order_type, null_order, storage_index, row_offset.GetIndex(), partition_stats); + auto offset_puning_result = + RowGroupReorderer::GetOffsetAfterPruning(order_by, column_type, order_type, null_order, storage_index, + row_offset.GetIndex(), partition_stats, has_secondary_order); if (offset_puning_result.pruned_row_group_count > 0 || offset_puning_result.leading_null_group_offset > 0) { // We can prune row groups and/or reduce the offset by consuming definite NULL-only groups if (!logical_limit.unpruned_offset.IsValid()) { diff --git a/src/duckdb/src/optimizer/row_number_rewriter.cpp b/src/duckdb/src/optimizer/row_number_rewriter.cpp index 19313198d..6ae3bca9d 100644 --- a/src/duckdb/src/optimizer/row_number_rewriter.cpp +++ b/src/duckdb/src/optimizer/row_number_rewriter.cpp @@ -15,6 +15,14 @@ bool RowNumberRewriter::CanOptimize(LogicalOperator &op) { return false; } + // If we have window fusion enabled, then we are also filtering on the row number, + // which reduces the number of scanned rows. This is faster than scanning them all + // and discarding most of them. + auto &window = op.Cast(); + if (window.partition_limit.IsValid()) { + return false; + } + auto &expression = op.expressions[0]; if (expression->GetExpressionType() != ExpressionType::WINDOW_ROW_NUMBER) { return false; diff --git a/src/duckdb/src/optimizer/rule/comparison_simplification.cpp b/src/duckdb/src/optimizer/rule/comparison_simplification.cpp index 983cdc3ca..ee85e04f0 100644 --- a/src/duckdb/src/optimizer/rule/comparison_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/comparison_simplification.cpp @@ -77,6 +77,31 @@ static bool DateTimestampComparisonIsInvertible(ClientContext &context, BoundFun return true; } +//! For a constant c that lies between two adjacent values of x and is rounded to one of them, picks the range +//! comparison with the rounded constant that gives the same result: x < 3.4 -> x <= 3, x < 3.5 -> x < 4 +static bool CompareWithRoundedConstant(BoundFunctionExpression &expr, bool column_ref_left, bool rounded_up) { + // c op x behaves like x op c rounded the other way: 3.5 < x -> 4 <= x, like x < 3.4 -> x <= 3 + if (!column_ref_left) { + rounded_up = !rounded_up; + } + ExpressionType comparison_type; + switch (expr.GetExpressionType()) { + case ExpressionType::COMPARE_LESSTHAN: + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + comparison_type = rounded_up ? ExpressionType::COMPARE_LESSTHAN : ExpressionType::COMPARE_LESSTHANOREQUALTO; + break; + case ExpressionType::COMPARE_GREATERTHAN: + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + comparison_type = + rounded_up ? ExpressionType::COMPARE_GREATERTHANOREQUALTO : ExpressionType::COMPARE_GREATERTHAN; + break; + default: + return false; + } + BoundComparisonExpression::SetType(expr, comparison_type); + return true; +} + static bool ConstantCastIsInvertible(ClientContext &context, BoundFunctionExpression &expr, BoundFunctionExpression &cast_expression, const Value &constant_value, Value &cast_constant, const LogicalType &target_type, bool column_ref_left, @@ -88,11 +113,15 @@ static bool ConstantCastIsInvertible(ClientContext &context, BoundFunctionExpres if (cast_type.IsIntegral() && target_type.IsIntegral()) { return true; } - // The constant must round-trip exactly; the column side is checked by the caller. - if (BoundCastExpression::IsLosslessIntegralToFloatingCast(target_type, cast_type) || - (target_type.id() == LogicalTypeId::DECIMAL && cast_type.id() == LogicalTypeId::DECIMAL)) { + if (BoundCastExpression::CastIsOrderPreserving(target_type, cast_type)) { auto roundtrip = cast_constant.TryCastAs(context, cast_type, nullptr, true); - return roundtrip && *roundtrip == constant_value; + if (!roundtrip) { + return false; + } + if (Value::NotDistinctFrom(*roundtrip, constant_value)) { + return true; + } + return CompareWithRoundedConstant(expr, column_ref_left, *roundtrip > constant_value); } if (target_type.id() != LogicalTypeId::DATE || cast_type.id() != LogicalTypeId::TIMESTAMP) { return false; @@ -272,7 +301,7 @@ unique_ptr ComparisonSimplificationRule::Apply(LogicalOperator &op, changes_made); } if (!BoundCastExpression::CastIsInvertible(target_type, cast_expression.GetReturnType()) && - !BoundCastExpression::IsLosslessIntegralToFloatingCast(target_type, cast_expression.GetReturnType())) { + !BoundCastExpression::CastIsOrderPreserving(target_type, cast_expression.GetReturnType())) { return nullptr; } diff --git a/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp b/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp index 906148deb..67e39e84c 100644 --- a/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp @@ -39,15 +39,49 @@ DateTruncSimplificationRule::DateTruncSimplificationRule(ExpressionRewriter &rew root = std::move(op); } -static bool TruncatesYearsTowardsZero(const BoundConstantExpression &date_part) { - DatePartSpecifier part; - if (!TryGetDatePartSpecifier(StringValue::Get(date_part.GetValue()), part)) { - return true; - } +static bool TruncatesYearsTowardsZero(DatePartSpecifier part) { return part == DatePartSpecifier::DECADE || part == DatePartSpecifier::CENTURY || part == DatePartSpecifier::MILLENNIUM; } +static bool TruncatesToDays(DatePartSpecifier part) { + switch (part) { + case DatePartSpecifier::MILLENNIUM: + case DatePartSpecifier::CENTURY: + case DatePartSpecifier::DECADE: + case DatePartSpecifier::YEAR: + case DatePartSpecifier::QUARTER: + case DatePartSpecifier::MONTH: + case DatePartSpecifier::WEEK: + case DatePartSpecifier::YEARWEEK: + case DatePartSpecifier::ISOYEAR: + case DatePartSpecifier::DAY: + case DatePartSpecifier::DOW: + case DatePartSpecifier::ISODOW: + case DatePartSpecifier::DOY: + case DatePartSpecifier::JULIAN_DAY: + return true; + default: + return false; + } +} + +static bool TruncatesInSessionTimeZone(LogicalTypeId type) { + return type == LogicalTypeId::TIMESTAMP_TZ || type == LogicalTypeId::TIMESTAMP_TZ_NS; +} + +static bool TruncatesToSecondOrFiner(DatePartSpecifier part) { + switch (part) { + case DatePartSpecifier::SECOND: + case DatePartSpecifier::EPOCH: + case DatePartSpecifier::MILLISECONDS: + case DatePartSpecifier::MICROSECONDS: + return true; + default: + return false; + } +} + static bool IsAfterFirstYear(const Value &value) { if (value.IsNull()) { return true; @@ -68,6 +102,10 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v auto &right = BoundComparisonExpression::RightMutable(expr); auto &date_part = bindings[2].get().Cast(); + DatePartSpecifier part; + if (date_part.GetValue().IsNull() || !TryGetDatePartSpecifier(StringValue::Get(date_part.GetValue()), part)) { + return nullptr; + } // We must have only a column on the LHS. if (bindings[3].get().GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { return nullptr; @@ -103,9 +141,20 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v return nullptr; } + // Bounds finer than a day lose their time when cast to DATE, so keep the comparison. + if (column_part.GetReturnType().id() == LogicalTypeId::DATE && !TruncatesToDays(part)) { + return nullptr; + } + + // Truncating a time zone aware timestamp to a minute or longer can cross a UTC offset change, so keep the + // comparison. + if (TruncatesInSessionTimeZone(column_part.GetReturnType().id()) && !TruncatesToSecondOrFiner(part)) { + return nullptr; + } + // Truncating to decades, centuries or millennia does not round years before the common era towards the past // (e.g. 150 BC truncates to 100 BC), so the rewrite below is only valid for constants after that - if (TruncatesYearsTowardsZero(date_part) && !IsAfterFirstYear(rhs.GetValue())) { + if (TruncatesYearsTowardsZero(part) && !IsAfterFirstYear(rhs.GetValue())) { return nullptr; } @@ -392,7 +441,7 @@ unique_ptr DateTruncSimplificationRule::CreateTrunc(const BoundConst if (trunc->IsFoldable()) { Value result; if (!ExpressionExecutor::TryEvaluateScalar(rewriter.context, *trunc, result)) { - return trunc; + return nullptr; } return make_uniq(result); @@ -446,7 +495,7 @@ unique_ptr DateTruncSimplificationRule::CreateTruncAdd(const BoundCo if (trunc->IsFoldable()) { Value result; if (!ExpressionExecutor::TryEvaluateScalar(rewriter.context, *trunc, result)) { - return trunc; + return nullptr; } return make_uniq(result); diff --git a/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp b/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp index 12ca6113b..9b45def6d 100644 --- a/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp +++ b/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp @@ -129,7 +129,7 @@ struct ListComprehensionMatch { optional_ptr root; optional_ptr list_filter_expr; optional_ptr inner_apply; - optional_ptr inner_bind; + optional_ptr inner_bind; optional_ptr filter_expr; optional_ptr result_expr; vector> captured_children; diff --git a/src/duckdb/src/optimizer/rule/or_range_merge.cpp b/src/duckdb/src/optimizer/rule/or_range_merge.cpp index e57455512..4b8f1be33 100644 --- a/src/duckdb/src/optimizer/rule/or_range_merge.cpp +++ b/src/duckdb/src/optimizer/rule/or_range_merge.cpp @@ -265,7 +265,8 @@ unique_ptr MakeComparison(ExpressionType type, const Expression &inp } //! The merged range: a BETWEEN when both bounds are present, otherwise a single comparison -unique_ptr MakeRange(const Expression &input, const RangeBound &lower, const RangeBound &upper) { +unique_ptr MakeRange(ClientContext &context, const Expression &input, const RangeBound &lower, + const RangeBound &upper) { auto lower_type = lower.inclusive ? ExpressionType::COMPARE_GREATERTHANOREQUALTO : ExpressionType::COMPARE_GREATERTHAN; auto upper_type = upper.inclusive ? ExpressionType::COMPARE_LESSTHANOREQUALTO : ExpressionType::COMPARE_LESSTHAN; @@ -281,7 +282,7 @@ unique_ptr MakeRange(const Expression &input, const RangeBound &lowe MakeComparison(lower_type, input, lower), MakeComparison(upper_type, input, upper)); } - return BoundBetweenExpression::Create(input.Copy(), make_uniq(lower.value), + return BoundBetweenExpression::Create(context, input.Copy(), make_uniq(lower.value), make_uniq(upper.value), lower.inclusive, upper.inclusive); } @@ -349,7 +350,7 @@ unique_ptr OrRangeMergeRule::Apply(LogicalOperator &op, vector &expr, bool & auto bound_cast = BoundCastExpression::GetBoundCast(cast).Copy(); auto &target_type = cast.GetReturnType(); auto child = std::move(BoundCastExpression::ChildMutable(cast)); - auto safe_cast = - BoundCastExpression::IsDefaultCast(cast) - ? BoundCastExpression::CreateDefault(std::move(child), target_type, std::move(bound_cast), true) - : BoundCastExpression::Create(std::move(child), target_type, std::move(bound_cast), true); + auto safe_cast = BoundCastExpression::Create(std::move(child), target_type, std::move(bound_cast), true); safe_cast->SetAlias(cast.GetAlias()); safe_cast->SetQueryLocation(cast.GetQueryLocation()); expr = std::move(safe_cast); diff --git a/src/duckdb/src/optimizer/self_join_aggregate.cpp b/src/duckdb/src/optimizer/self_join_aggregate.cpp index 1ac3903fd..db7e44a6b 100644 --- a/src/duckdb/src/optimizer/self_join_aggregate.cpp +++ b/src/duckdb/src/optimizer/self_join_aggregate.cpp @@ -20,11 +20,13 @@ // the left side of a RIGHT_SEMI or RIGHT_ANTI one), whose rows only decide whether a match exists -- a MARK join's NULL // included, which depends on whether a NULL occurs, not how often; a DISTINCT, whose targets it reads through // expressions, a DISTINCT ON passing its other columns through by position, which therefore all count as read; and a -// GROUP BY whose aggregates are min, max or DISTINCT ones (`min(x, n)`, the n smallest values, counts duplicates and -// is not one of them). Below such a parent the property passes through projections and filters without volatile -// expressions, cross products and INNER joins: their output, as a set, depends only on their inputs as sets. Anything -// else stops it, a UNION among them: it reads its inputs' columns by position rather than through expressions, so what -// it reads would not be seen. A materialized CTE's definition ignores duplicates when every one of its references does. +// GROUP BY whose aggregates ignore duplicates (LogicalAggregate::IgnoresDuplicates: DISTINCT ones, and the ones that +// depend neither on duplicates nor on input order, min, max, bool_and, bool_or; `min(x, n)`, the n smallest values, +// counts duplicates and is not one of them). Below such a parent the property passes through projections and filters +// without volatile expressions, cross products and INNER joins: their output, as a set, depends only on their inputs as +// sets. Anything else stops it, a UNION among them: it reads its inputs' columns by position rather than through +// expressions, so what it reads would not be seen. A materialized CTE's definition ignores duplicates when every one of +// its references does. // // What must hold of the join, in the plan as bound (the rewrite runs before filter pushdown, which would move the // conditions into the scans; the later optimizers then push the new filter into the scan and order the joins around @@ -89,27 +91,6 @@ bool JoinConditionsVolatile(const LogicalOperator &op) { return false; } -//! A GROUP BY whose result is the same over its input with or without repeated rows -bool AggregateIgnoresDuplicates(const LogicalAggregate &aggregate) { - if (AnyVolatile(aggregate.groups)) { - return false; - } - for (auto &expr : aggregate.expressions) { - if (expr->GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE || expr->IsVolatile()) { - return false; - } - auto &bound = expr->Cast(); - if (bound.IsDistinct()) { - continue; - } - auto &name = bound.Function().GetName().GetIdentifierName(); - if ((name != "min" && name != "max") || bound.GetChildren().size() != 1) { - return false; - } - } - return true; -} - //! The column bindings the plan reads, visited from the root down so that a candidate projection's expressions count //! only when the column they compute is itself read: everything above a candidate reads it through expressions, so //! an unreferenced column of it is dead, and so is whatever only that column referenced (an inlined CTE's identity @@ -334,7 +315,7 @@ class SelfJoinAggregateRewriter { return; } case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: - Walk(op.children[0], AggregateIgnoresDuplicates(op.Cast())); + Walk(op.children[0], op.Cast().IgnoresDuplicates()); return; case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: { // its references are all below its second child, so they are all seen before its definition is diff --git a/src/duckdb/src/optimizer/set_operation_aggregate.cpp b/src/duckdb/src/optimizer/set_operation_aggregate.cpp new file mode 100644 index 000000000..659a107b4 --- /dev/null +++ b/src/duckdb/src/optimizer/set_operation_aggregate.cpp @@ -0,0 +1,474 @@ +// EXCEPT ALL and INTERSECT ALL reach the optimizer as a LogicalSetOperation. Once the filters have been moved around it +// (FilterPullup / FilterPushdown: a filter on the result goes into the left child, what it implies for the other +// child goes there, see PushdownSetOperation and PullupSetOperation), this pass chooses how to run it. +// +// The general plan numbers the rows that are equal in all columns on both sides and joins on the columns and the +// number (LogicalSetOperation::CreateJoin): two windows that partition by every column, and a hash join on every +// column. But a row that occurs n times in l and m times in r occurs max(n - m, 0) times in l EXCEPT ALL r and +// min(n, m) times in l INTERSECT ALL r, so counting the rows of every group per side is enough: +// +// PROJECTION +// UNNEST -- one row per copy +// UNNEST -- one row per block of copies +// FILTER n > m -- INTERSECT ALL: n > 0 AND m > 0 +// AGGREGATE count(in_l) AS n, count(in_r) AS m GROUP BY +// UNION ALL +// PROJECTION , true AS in_l, NULL AS in_r +// PROJECTION , NULL AS in_l, true AS in_r +// +// A group is emitted c = n - m times (INTERSECT ALL: c = min(n, m) times). Its copies are generated in blocks of +// COPY_BLOCK_SIZE rows, so that a group with very many copies never needs one list with an entry per copy: the +// first UNNEST yields a row per block, the second one the rows of the block. The lists come from list_resize of a +// constant list, which like every function used here is part of the core library; a group with a single copy, the +// common case, unnests the constant list itself in both steps. +// +// The aggregate returns one row of a group where the join returns the left rows, so it is only used if rows that +// compare equal are identical: no column is compared under a collation, none is floating point (0.0 and -0.0) or of +// a type whose comparison normalizes (INTERVAL, TIME WITH TIME ZONE), also not nested. Every other EXCEPT ALL / +// INTERSECT ALL becomes the join. +// +// The join is also kept where the left child is estimated to have few distinct rows with many copies each: the few +// groups of the aggregate cannot feed all threads, so the expansion and what follows it would run on one thread. +// Without an estimate of the distinct rows, a left child with enough rows for many copies of each is taken for one. +// And it is kept where the side it can build its hash table on is estimated to be much smaller than the other: its +// filter then prunes the scan of the larger side to the rows that have a match, where the aggregate hashes every row +// of both sides. That is either side of an INTERSECT ALL and the left side of an EXCEPT ALL. +// +// The pass runs before the join order, statistics propagation and compressed materialization, which then see an +// ordinary aggregate or join. +#include "duckdb/optimizer/set_operation_aggregate.hpp" + +#include "duckdb/common/reference_map.hpp" +#include "duckdb/function/builtin_function_lookup.hpp" +#include "duckdb/function/function_binder.hpp" +#include "duckdb/parallel/task_scheduler.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/planner/expression/bound_case_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_function_expression.hpp" +#include "duckdb/planner/expression/bound_unnest_expression.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_set_operation.hpp" +#include "duckdb/planner/operator/logical_unnest.hpp" + +namespace duckdb { + +namespace { + +//! The copies of a group are generated in blocks of this many rows +constexpr int64_t COPY_BLOCK_SIZE = STANDARD_VECTOR_SIZE; + +//! The aggregate plan is not used for fewer groups than this per thread: the scan of the aggregate's result is the +//! source of everything above the set operation, and with few groups it cannot keep the threads busy. This is a +//! number of groups, measured with the default vector size (few groups lose, some thousands per thread do not), and +//! deliberately not STANDARD_VECTOR_SIZE: how the scan of the groups is split among the threads is not a matter of +//! the vector size, and the choice of the plan should not change with it +constexpr idx_t MIN_GROUPS_PER_THREAD = 2048; +//! .. if every group has at least this many rows on average, so that there is work above to be spread +constexpr idx_t MIN_COPIES_PER_GROUP = 128; +//! The join is kept where the side it builds on is estimated to have this many times fewer rows than the side it +//! probes: at a ratio of 4 the two plans take the same time, from 8 on the join is ahead and increasingly so +constexpr idx_t MIN_PROBE_TO_BUILD_RATIO = 8; +//! How deep the estimate of the distinct values of a column follows the plan +constexpr idx_t MAX_DISTINCT_COUNT_DEPTH = 64; +//! Estimates of distinct values are capped here, so that their products and sums cannot overflow: everything above +//! it is many groups +constexpr idx_t MAX_DISTINCT_COUNT = NumericLimits::Maximum(); + +optional_idx MultiplyCounts(optional_idx left, optional_idx right) { + if (!left.IsValid() || !right.IsValid()) { + return optional_idx(); + } + return MinValue(left.GetIndex() * right.GetIndex(), MAX_DISTINCT_COUNT); +} + +//! Estimates how many distinct values the columns of an operator have, if there is anything to tell: a constant has +//! one value, a column what the scan it comes from says, and another expression at most as many as the combinations +//! of the columns it reads. A column is estimated once per operator, so that a column that is read many times in the +//! plan below, as by a chain of projections that each read the one below twice, costs no more than reading the plan +class DistinctCountEstimator { +public: + explicit DistinctCountEstimator(ClientContext &context) : context(context) { + } + + //! An estimate of the number of distinct values of a column that op produces, if there is one + optional_idx ColumnDistinctCount(LogicalOperator &op, const ColumnBinding &binding); + +private: + optional_idx EstimateColumn(LogicalOperator &op, const ColumnBinding &binding); + optional_idx EstimateExpression(LogicalOperator &op, const Expression &expr); + +private: + ClientContext &context; + //! The estimates so far, per operator and column + reference_map_t> estimates; + //! How deep below the set operation the estimate currently is + idx_t depth = 0; +}; + +optional_idx DistinctCountEstimator::ColumnDistinctCount(LogicalOperator &op, const ColumnBinding &binding) { + auto &op_estimates = estimates[op]; + auto entry = op_estimates.find(binding); + if (entry != op_estimates.end()) { + return entry->second; + } + optional_idx result; + if (depth < MAX_DISTINCT_COUNT_DEPTH) { + depth++; + result = EstimateColumn(op, binding); + depth--; + } + // the map can have grown while the column was estimated + estimates[op][binding] = result; + return result; +} + +optional_idx DistinctCountEstimator::EstimateExpression(LogicalOperator &op, const Expression &expr) { + if (expr.IsFoldable()) { + return 1; + } + if (expr.IsVolatile()) { + return optional_idx(); + } + optional_idx result = 1; + bool has_column = false; + ExpressionIterator::VisitExpression(expr, [&](const BoundColumnRefExpression &colref) { + has_column = true; + if (colref.Depth() != 0) { + result = optional_idx(); + } else if (result.IsValid()) { + result = MultiplyCounts(result, ColumnDistinctCount(op, colref.Binding())); + } + }); + if (!has_column) { + return optional_idx(); + } + // few values by type + optional_idx domain; + switch (expr.GetReturnType().id()) { + case LogicalTypeId::BOOLEAN: + domain = 3; + break; + case LogicalTypeId::TINYINT: + case LogicalTypeId::UTINYINT: + domain = 257; + break; + case LogicalTypeId::ENUM: + domain = EnumType::GetSize(expr.GetReturnType()) + 1; + break; + default: + break; + } + if (domain.IsValid() && (!result.IsValid() || result.GetIndex() > domain.GetIndex())) { + return domain; + } + return result; +} + +optional_idx DistinctCountEstimator::EstimateColumn(LogicalOperator &op, const ColumnBinding &binding) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_GET: { + auto &get = op.Cast(); + if (binding.table_index != get.table_index || !get.children.empty()) { + return optional_idx(); + } + auto &column_index = get.GetColumnIndex(binding); + if (column_index.IsVirtualColumn()) { + return optional_idx(); + } + unique_ptr stats; + if (get.bind_data && get.function.statistics_extended) { + TableFunctionGetStatisticsInput input(get.bind_data.get(), column_index); + stats = get.function.statistics_extended(context, input); + } else if (get.bind_data && get.function.statistics) { + stats = get.function.statistics(context, get.bind_data.get(), column_index.GetPrimaryIndex()); + } + if (!stats || stats->GetDistinctCount() == 0) { + return optional_idx(); + } + // one more for NULL + return MinValue(stats->GetDistinctCount(), MAX_DISTINCT_COUNT - 1) + 1; + } + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &projection = op.Cast(); + if (binding.table_index != projection.table_index || binding.column_index >= op.expressions.size()) { + return optional_idx(); + } + return EstimateExpression(*op.children[0], *op.expressions[binding.column_index]); + } + case LogicalOperatorType::LOGICAL_UNION: { + auto &setop = op.Cast(); + if (binding.table_index != setop.table_index) { + return optional_idx(); + } + idx_t result = 0; + for (auto &child : op.children) { + auto child_bindings = child->GetColumnBindings(); + if (binding.column_index >= child_bindings.size()) { + return optional_idx(); + } + auto child_count = ColumnDistinctCount(*child, child_bindings[binding.column_index]); + if (!child_count.IsValid()) { + return optional_idx(); + } + result = MinValue(result + child_count.GetIndex(), MAX_DISTINCT_COUNT); + } + return result; + } + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_LIMIT: + case LogicalOperatorType::LOGICAL_ORDER_BY: + case LogicalOperatorType::LOGICAL_TOP_N: + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + case LogicalOperatorType::LOGICAL_ANY_JOIN: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: { + // the values of a column come from the child that has it (an outer join adds NULL, which is counted) + for (auto &child : op.children) { + for (auto &child_binding : child->GetColumnBindings()) { + if (child_binding == binding) { + return ColumnDistinctCount(*child, binding); + } + } + } + return optional_idx(); + } + default: + return optional_idx(); + } +} + +} // namespace + +SetOperationAggregate::SetOperationAggregate(Optimizer &optimizer, bool use_aggregate) + : optimizer(optimizer), use_aggregate(use_aggregate) { +} + +bool SetOperationAggregate::CanUseAggregate(LogicalSetOperation &setop) { + if (!use_aggregate || !setop.setop_all) { + return false; + } + auto comparisons = setop.GetComparisons(optimizer.context); + D_ASSERT(comparisons.size() == setop.column_count && setop.correlated_column_count <= setop.column_count); + for (idx_t i = 0; i < comparisons.size(); i++) { + auto &comparison = comparisons[i]; + // a column that is compared under a collation is not compared as a plain column + if (comparison.GetLHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + comparison.GetRHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + comparison.GetLHS().GetReturnType() != comparison.GetRHS().GetReturnType()) { + return false; + } + // the correlated columns hold the distinct values of the outer query, which are compared as they are + bool is_correlated = i + setop.correlated_column_count >= setop.column_count; + if (!is_correlated && !comparison.GetLHS().GetReturnType().EqualValuesAreIdentical()) { + return false; + } + } + return !FewGroupsOfManyRows(setop) && !OneSideMuchSmaller(setop); +} + +//! Whether the left child, whose rows the set operation returns, is estimated to have few distinct rows with many +//! copies each. The aggregate plan then expands a few groups into many rows, and since the scan of its few groups +//! is the source of that pipeline, the expansion and everything above it up to the next pipeline breaker run on +//! one thread, where the rows of the join plan come from all threads. Without an estimate of the distinct rows, +//! the child is taken for one group, so that the join is kept where there are enough rows for many copies of it. +bool SetOperationAggregate::FewGroupsOfManyRows(LogicalSetOperation &setop) { + auto &context = optimizer.context; + auto threads = TaskScheduler::GetScheduler(context).NumberOfThreads(); + if (threads <= 1) { + return false; + } + auto &left = *setop.children[0]; + DistinctCountEstimator estimator(context); + optional_idx groups = 1; + for (auto &binding : left.GetColumnBindings()) { + groups = MultiplyCounts(groups, estimator.ColumnDistinctCount(left, binding)); + } + idx_t group_count = groups.IsValid() ? groups.GetIndex() : 1; + auto rows = left.EstimateCardinality(context); + return group_count < threads * MIN_GROUPS_PER_THREAD && group_count * MIN_COPIES_PER_GROUP <= rows; +} + +//! Whether the child the join builds its hash table on is estimated to be much smaller than the one it probes. The +//! join then prunes the scan of the larger child to the rows that have a match in the smaller one, where the +//! aggregate hashes every row of both children. An INTERSECT ALL is a SEMI join that builds on either side, an +//! EXCEPT ALL an ANTI join that builds on the left side only: over a small right side it has to see every left row, +//! and those without a match are its result +bool SetOperationAggregate::OneSideMuchSmaller(LogicalSetOperation &setop) { + auto &context = optimizer.context; + auto build_rows = setop.children[0]->EstimateCardinality(context); + auto probe_rows = setop.children[1]->EstimateCardinality(context); + if (setop.type == LogicalOperatorType::LOGICAL_INTERSECT && probe_rows < build_rows) { + std::swap(build_rows, probe_rows); + } + return build_rows <= probe_rows / MIN_PROBE_TO_BUILD_RATIO; +} + +//! The columns of a child followed by its side markers: in_left is TRUE for the rows of the left child and NULL for +//! the rows of the right one, in_right the reverse +unique_ptr SetOperationAggregate::AddSideMarkers(unique_ptr child, bool is_left) { + child->ResolveOperatorTypes(); + auto bindings = child->GetColumnBindings(); + vector> select_list; + for (idx_t i = 0; i < bindings.size(); i++) { + select_list.push_back(make_uniq(child->types[i], bindings[i])); + } + for (auto set : {is_left, !is_left}) { + select_list.push_back( + make_uniq(set ? Value::BOOLEAN(true) : Value(LogicalType::BOOLEAN))); + } + auto projection = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(select_list)); + projection->AddChild(std::move(child)); + return std::move(projection); +} + +//! The aggregate over the union of the children of an EXCEPT ALL / INTERSECT ALL +unique_ptr SetOperationAggregate::CreateAggregate(LogicalSetOperation &setop) { + auto &context = optimizer.context; + auto &binder = optimizer.binder; + bool is_except = setop.type == LogicalOperatorType::LOGICAL_EXCEPT; + auto types = setop.GetComparisonTypes(context); + auto left = AddSideMarkers(std::move(setop.children[0]), true); + auto right = AddSideMarkers(std::move(setop.children[1]), false); + + auto column_count = types.size(); + auto union_index = binder.GenerateTableIndex(); + auto union_all = make_uniq(union_index, column_count + 2, std::move(left), std::move(right), + LogicalOperatorType::LOGICAL_UNION, true); + + // count(in_left), count(in_right) GROUP BY all columns + vector> counts; + FunctionBinder function_binder(context); + for (idx_t side = 0; side < 2; side++) { + vector> arguments; + arguments.push_back(make_uniq( + LogicalType::BOOLEAN, ColumnBinding(union_index, ProjectionIndex(column_count + side)))); + auto function = GetBuiltinAggregateFunction(context, Identifier("count"), {LogicalType::BOOLEAN}); + counts.push_back(function_binder.BindAggregateFunction(function, std::move(arguments))); + } + auto group_index = binder.GenerateTableIndex(); + auto aggregate_index = binder.GenerateTableIndex(); + auto aggregate = make_uniq(group_index, aggregate_index, std::move(counts)); + aggregate->groupings_index = binder.GenerateTableIndex(); + GroupingSet every_column; + for (idx_t i = 0; i < column_count; i++) { + aggregate->groups.push_back( + make_uniq(types[i], ColumnBinding(union_index, ProjectionIndex(i)))); + every_column.insert(ProjectionIndex(i)); + } + aggregate->grouping_sets.push_back(std::move(every_column)); + aggregate->AddChild(std::move(union_all)); + + auto left_count = [&]() -> unique_ptr { + return make_uniq(LogicalType::BIGINT, + ColumnBinding(aggregate_index, ProjectionIndex(0))); + }; + auto right_count = [&]() -> unique_ptr { + return make_uniq(LogicalType::BIGINT, + ColumnBinding(aggregate_index, ProjectionIndex(1))); + }; + auto bigint = [&](int64_t value) -> unique_ptr { + return make_uniq(Value::BIGINT(value)); + }; + auto call = [&](const char *name, unique_ptr first, + unique_ptr second) -> unique_ptr { + vector> arguments; + arguments.push_back(std::move(first)); + arguments.push_back(std::move(second)); + return BindBuiltinScalarExpression(context, Identifier(name), std::move(arguments)); + }; + + // the groups that remain, and how often each of them is emitted + auto filter = make_uniq(); + unique_ptr copies; + if (is_except) { + filter->expressions.push_back( + BoundComparisonExpression::Create(ExpressionType::COMPARE_GREATERTHAN, left_count(), right_count())); + copies = call("-", left_count(), right_count()); + } else { + filter->expressions.push_back( + BoundComparisonExpression::Create(ExpressionType::COMPARE_GREATERTHAN, left_count(), bigint(0))); + filter->expressions.push_back( + BoundComparisonExpression::Create(ExpressionType::COMPARE_GREATERTHAN, right_count(), bigint(0))); + copies = make_uniq( + BoundComparisonExpression::Create(ExpressionType::COMPARE_LESSTHAN, left_count(), right_count()), + left_count(), right_count()); + } + filter->AddChild(std::move(aggregate)); + + // one row per copy, in two steps so that no list holds more than COPY_BLOCK_SIZE entries per block of copies. + // a group with a single block, or a single copy, unnests a constant list, which costs next to nothing + auto list_of = [&](vector entries) -> unique_ptr { + return make_uniq(Value::LIST(LogicalType::BOOLEAN, std::move(entries))); + }; + auto unnest_of = [&](unique_ptr list) -> unique_ptr { + auto result = make_uniq(LogicalType::BOOLEAN); + result->ChildMutable() = std::move(list); + return std::move(result); + }; + auto compare = [&](ExpressionType type, unique_ptr left, int64_t right) { + return BoundComparisonExpression::Create(type, std::move(left), bigint(right)); + }; + // the blocks: one row per started block of copies, TRUE for the first block and NULL for the others + auto block_count = call("+", call("//", call("-", copies->Copy(), bigint(1)), bigint(COPY_BLOCK_SIZE)), bigint(1)); + auto block_list = make_uniq( + compare(ExpressionType::COMPARE_LESSTHANOREQUALTO, copies->Copy(), COPY_BLOCK_SIZE), + list_of({Value::BOOLEAN(true)}), call("list_resize", list_of({Value::BOOLEAN(true)}), std::move(block_count))); + auto blocks_index = binder.GenerateTableIndex(); + auto blocks = make_uniq(blocks_index); + blocks->expressions.push_back(unnest_of(std::move(block_list))); + blocks->AddChild(std::move(filter)); + + // a block: a list of COPY_BLOCK_SIZE entries, the first block holds the remainder + auto first_block = call("+", call("%", call("-", copies->Copy(), bigint(1)), bigint(COPY_BLOCK_SIZE)), bigint(1)); + auto is_first_block = + make_uniq(LogicalType::BOOLEAN, ColumnBinding(blocks_index, ProjectionIndex(0))); + auto block_size = + make_uniq(std::move(is_first_block), std::move(first_block), bigint(COPY_BLOCK_SIZE)); + auto copy_list = make_uniq(compare(ExpressionType::COMPARE_EQUAL, std::move(copies), 1), + list_of({Value::BOOLEAN(true)}), + call("list_resize", list_of({}), std::move(block_size))); + auto unnest = make_uniq(binder.GenerateTableIndex()); + unnest->expressions.push_back(unnest_of(std::move(copy_list))); + unnest->AddChild(std::move(blocks)); + + // the columns of the set operation, under its table index + vector> select_list; + for (idx_t i = 0; i < column_count; i++) { + select_list.push_back( + make_uniq(types[i], ColumnBinding(group_index, ProjectionIndex(i)))); + } + auto projection = make_uniq(setop.table_index, std::move(select_list)); + projection->AddChild(std::move(unnest)); + return std::move(projection); +} + +unique_ptr SetOperationAggregate::Optimize(unique_ptr op) { + for (auto &child : op->children) { + child = Optimize(std::move(child)); + } + if (op->type != LogicalOperatorType::LOGICAL_EXCEPT && op->type != LogicalOperatorType::LOGICAL_INTERSECT) { + return op; + } + auto &setop = op->Cast(); + unique_ptr result; + if (CanUseAggregate(setop)) { + result = CreateAggregate(setop); + } else { + auto types = setop.GetComparisonTypes(optimizer.context); + result = LogicalSetOperation::CreateJoin(optimizer.binder, types, setop.table_index, setop.type, + setop.setop_all, std::move(setop.children[0]), + std::move(setop.children[1]), setop.correlated_column_count); + } + result->ResolveOperatorTypes(); + return result; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_aggregate.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_aggregate.cpp index b65c3c27c..3ca285804 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_aggregate.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_aggregate.cpp @@ -1,10 +1,23 @@ #include "duckdb/optimizer/statistics_propagator.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/storage/statistics/numeric_stats.hpp" namespace duckdb { unique_ptr StatisticsPropagator::PropagateExpression(BoundAggregateExpression &aggr, unique_ptr &expr_ptr) { + if (aggr.GetFilter()) { + // a filter that is true for every row is no filter + auto &filter = aggr.GetFilterMutable(); + auto filter_stats = PropagateExpression(filter); + if (filter_stats && filter_stats->GetType().id() == LogicalTypeId::BOOLEAN && !filter_stats->CanHaveNull() && + filter_stats->GetStatsType() == StatisticsType::NUMERIC_STATS && NumericStats::HasMinMax(*filter_stats) && + BooleanValue::Get(NumericStats::Min(*filter_stats))) { + filter.reset(); + // the columns that only the filter read can be pruned from the scan + removed_expressions = true; + } + } vector stats; stats.reserve(aggr.GetChildren().size()); for (auto &child : aggr.GetChildrenMutable()) { @@ -18,7 +31,7 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundAggreg if (!aggr.Function().GetCallbacks().HasStatisticsCallback()) { return nullptr; } - AggregateStatisticsInput input(aggr.BindInfo(), stats, node_stats.get()); + AggregateStatisticsInput input(aggr.BindInfoMutable(), stats, node_stats.get()); const idx_t child_count = aggr.GetChildren().size(); auto result = aggr.Function().GetCallbacks().GetStatisticsCallback()(context, aggr, input); removed_expressions |= aggr.GetChildren().size() < child_count; diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_between.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_between.cpp index ba1e9f298..226fe2b62 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_between.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_between.cpp @@ -15,6 +15,14 @@ unique_ptr StatisticsPropagator::PropagateBetween(BoundFunctionE auto input_stats = PropagateExpression(input); auto lower_stats = PropagateExpression(lower_bound); auto upper_stats = PropagateExpression(upper_bound); + if (HasNoValidValue(input_stats.get()) && IsRemovable(*input) && IsRemovable(*lower_bound) && + IsRemovable(*upper_bound)) { + // an input that holds only NULLs: the BETWEEN is NULL for every row + // (a bound that holds only NULLs leaves FALSE or NULL, which is not a constant) + expr_ptr = make_uniq(Value(LogicalType::BOOLEAN)); + removed_expressions = true; + return PropagateExpression(expr_ptr); + } if (!input_stats) { return nullptr; } diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_comparison.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_comparison.cpp index c6583e503..bf14f141e 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_comparison.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_comparison.cpp @@ -2,6 +2,7 @@ #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/expression_barrier.hpp" #include "duckdb/optimizer/expression_rewriter.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/storage/statistics/string_stats.hpp" @@ -90,6 +91,15 @@ static FilterPropagateResult PropagateValueComparison(const Value &lmin, const V } } +bool StatisticsPropagator::HasNoValidValue(optional_ptr stats) { + // statistics that hold neither NULL nor non-NULL values describe an empty input, which is left alone + return stats && stats->CanHaveNull() && !stats->CanHaveNoNull(); +} + +bool StatisticsPropagator::IsRemovable(const Expression &expr) { + return !expr.CanThrow() && !expr.IsVolatile() && !ExpressionBarrier::Contains(expr); +} + FilterPropagateResult StatisticsPropagator::PropagateComparison(const BaseStatistics &lstats, const BaseStatistics &rstats, ExpressionType comparison) { @@ -201,6 +211,15 @@ unique_ptr StatisticsPropagator::PropagateComparison(BoundFuncti if (comparison != expr.GetExpressionType()) { BoundComparisonExpression::SetType(expr, comparison); } + if (comparison != ExpressionType::COMPARE_DISTINCT_FROM && + comparison != ExpressionType::COMPARE_NOT_DISTINCT_FROM && + (HasNoValidValue(left_stats.get()) || HasNoValidValue(right_stats.get())) && IsRemovable(*left) && + IsRemovable(*right)) { + // an operand that holds only NULLs: the comparison is NULL for every row + expr_ptr = make_uniq(Value(LogicalType::BOOLEAN)); + removed_expressions = true; + return PropagateExpression(expr_ptr); + } if (!left_stats || !right_stats) { return nullptr; } diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp index 927958946..973b48a0e 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_function.cpp @@ -2,6 +2,7 @@ #include "duckdb/execution/expression_executor.hpp" #include "duckdb/function/arg_properties.hpp" +#include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" @@ -248,8 +249,10 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundFuncti vector stats; stats.reserve(func.GetChildren().size()); bool has_invalidated_parameter = false; + bool has_all_null_argument = false; for (auto &child : func.GetChildrenMutable()) { auto stat = PropagateExpression(child); + has_all_null_argument = has_all_null_argument || HasNoValidValue(stat.get()); // an invalidated parameter has no statistics until it is rebound at execution if (child->GetExpressionType() == ExpressionType::VALUE_PARAMETER && child->GetReturnType().id() == LogicalTypeId::SQLNULL) { @@ -268,12 +271,22 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundFuncti if (has_invalidated_parameter) { return nullptr; } + if (has_all_null_argument && func.GetReturnType().id() == LogicalTypeId::BOOLEAN && + !BoundCastExpression::IsCast(func) && + func.Function().GetNullHandling() == FunctionNullHandling::DEFAULT_NULL_HANDLING && + !func.Function().HasBindLambdaCallback() && IsRemovable(func)) { + // a predicate with default NULL handling (LIKE, contains, ...) is NULL for every row when an argument holds + // only NULLs + expr_ptr = make_uniq(Value(LogicalType::BOOLEAN)); + removed_expressions = true; + return PropagateExpression(expr_ptr); + } auto constant_stats = PropagateConstantInputs(context, func, stats); if (constant_stats) { return constant_stats; } if (func.Function().HasStatisticsCallback()) { - FunctionStatisticsInput input(func, func.BindInfo().get(), stats, &expr_ptr); + FunctionStatisticsInput input(func, func.BindInfoMutable(), stats, &expr_ptr); return func.Function().GetStatisticsCallback()(context, input); } return PropagateMonotoneBounds(context, func, stats); diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_operator.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_operator.cpp index cb8417a9b..e04e31ceb 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_operator.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_operator.cpp @@ -40,6 +40,20 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundOperat } child_stats.push_back(std::move(stats)); } + if ((expr.GetExpressionType() == ExpressionType::COMPARE_IN || + expr.GetExpressionType() == ExpressionType::COMPARE_NOT_IN) && + !child_stats.empty() && HasNoValidValue(child_stats[0].get())) { + bool removable = true; + for (auto &child : expr.GetChildren()) { + removable = removable && IsRemovable(*child); + } + if (removable) { + // x [NOT] IN (...) is NULL for every row when x holds only NULLs + expr_ptr = make_uniq(Value(LogicalType::BOOLEAN)); + removed_expressions = true; + return PropagateExpression(expr_ptr); + } + } if (!all_have_stats) { return nullptr; } diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp index a7c26f245..cd5f15939 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_get.cpp @@ -164,6 +164,18 @@ static bool IsNullOnlyForNullColumn(Expression &expr) { } } +unique_ptr StatisticsPropagator::GetColumnStatistics(ClientContext &context, LogicalGet &get, + const ColumnIndex &column_index) { + if (get.function.statistics_extended) { + TableFunctionGetStatisticsInput input(get.bind_data.get(), column_index); + return get.function.statistics_extended(context, input); + } + if (get.function.statistics) { + return get.function.statistics(context, get.bind_data.get(), column_index.GetPrimaryIndex()); + } + return nullptr; +} + unique_ptr StatisticsPropagator::PropagateStatistics(LogicalGet &get, unique_ptr &node_ptr) { if (get.function.cardinality) { @@ -177,14 +189,7 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalGet } auto &column_ids = get.GetColumnIds(); for (idx_t i = 0; i < column_ids.size(); i++) { - unique_ptr stats; - if (get.function.statistics_extended) { - TableFunctionGetStatisticsInput input(get.bind_data.get(), column_ids[i]); - stats = get.function.statistics_extended(context, input); - } else { - stats = get.function.statistics(context, get.bind_data.get(), column_ids[i].GetPrimaryIndex()); - } - + auto stats = GetColumnStatistics(context, get, column_ids[i]); if (stats) { ColumnBinding binding(get.table_index, ProjectionIndex(i)); statistics_map.insert(make_pair(binding, std::move(stats))); diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp index fe4fae892..082553e99 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp @@ -121,8 +121,7 @@ static optional_ptr GetFilterColumn(ClientContext &context, co !BoundCastExpression::CastIsInvertibleForEquality(source_type, target_type)) { return nullptr; } - if (!BoundCastExpression::IsDefaultCast(cast) && - CastFunctionSet::Get(context).CanOverrideDefaultCast(source_type, target_type)) { + if (CastFunctionSet::Get(context).CanOverrideDefaultCast(source_type, target_type)) { return nullptr; } column = BoundCastExpression::Child(cast); @@ -151,6 +150,17 @@ void StatisticsPropagator::PropagateStatistics(LogicalComparisonJoin &join, uniq auto &condition = join.conditions[i]; if (!condition.IsComparison()) { PropagateExpression(condition.JoinExpressionReference()); + switch (ClassifyFilter(condition.GetJoinExpression())) { + case FilterPropagateResult::FILTER_ALWAYS_FALSE: + case FilterPropagateResult::FILTER_FALSE_OR_NULL: + // a residual predicate that never passes: none of the join conditions matter + if (HandleJoinNeverMatches(join, node_ptr)) { + return; + } + break; + default: + break; + } continue; } @@ -161,15 +171,26 @@ void StatisticsPropagator::PropagateStatistics(LogicalComparisonJoin &join, uniq condition.SetComparisonType(SimplifyDistinctComparison(condition.GetComparisonType(), stats_left.get(), stats_right.get(), ComparisonContext::JOIN)); } + // a side that holds only NULLs never compares TRUE, whatever the statistics of the other side + const bool is_distinct = condition.GetComparisonType() == ExpressionType::COMPARE_DISTINCT_FROM || + condition.GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM; + const bool all_null = !is_distinct && + (HasNoValidValue(stats_left.get()) || HasNoValidValue(stats_right.get())) && + IsRemovable(condition.GetLHS()) && IsRemovable(condition.GetRHS()); + if (all_null && !(stats_left && stats_right)) { + if (HandleJoinNeverMatches(join, node_ptr)) { + return; + } + } if (stats_left && stats_right) { - if ((condition.GetComparisonType() == ExpressionType::COMPARE_DISTINCT_FROM || - condition.GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM) && - stats_left->CanHaveNull() && stats_right->CanHaveNull()) { + if (is_distinct && stats_left->CanHaveNull() && stats_right->CanHaveNull()) { // null values are equal in this join, and both sides can have null values // nothing to do here continue; } - auto prune_result = PropagateComparison(*stats_left, *stats_right, condition.GetComparisonType()); + auto prune_result = all_null + ? FilterPropagateResult::FILTER_FALSE_OR_NULL + : PropagateComparison(*stats_left, *stats_right, condition.GetComparisonType()); // Add stats to logical_join for perfect hash join condition.SetLeftStats(stats_left->ToUnique()); condition.SetRightStats(stats_right->ToUnique()); @@ -533,9 +554,7 @@ void StatisticsPropagator::CreateFilterFromJoinStats(unique_ptr child->expressions.emplace_back(std::move(filter_expr)); } - // not allowed to let filter pushdown change mark joins to semi joins. - // semi joins are potentially slower AND the conversion can ruin column binding information - FilterPushdown filter_pushdown(optimizer, false); + FilterPushdown filter_pushdown(optimizer); child = filter_pushdown.Rewrite(std::move(child)); PropagateExpression(expr); } diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_window.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_window.cpp index b4a75889d..ab81586bb 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_window.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_window.cpp @@ -54,7 +54,7 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalWind } auto &aggregate = *over_expr.AggregateFunctionMutable(); if (aggregate.GetCallbacks().HasStatisticsCallback()) { - AggregateStatisticsInput input(over_expr.BindInfo(), child_stats, node_stats.get()); + AggregateStatisticsInput input(over_expr.BindInfoMutable(), child_stats, node_stats.get()); const idx_t child_count = agg_children.size(); // The callback takes a BoundAggregateExpression; a window aggregate has none, so // synthesise one over the same function and children. Callbacks may rewrite both diff --git a/src/duckdb/src/optimizer/statistics_propagator.cpp b/src/duckdb/src/optimizer/statistics_propagator.cpp index 27a4cf29a..38e8a9917 100644 --- a/src/duckdb/src/optimizer/statistics_propagator.cpp +++ b/src/duckdb/src/optimizer/statistics_propagator.cpp @@ -181,7 +181,7 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalCopy column_stats[i] = entry->second.get(); } } - CopyToPropagateStatsInput input {context, *op.bind_data, column_stats}; + CopyToPropagateStatsInput input {context, op.bind_data, column_stats}; op.function.copy_to_propagate_statistics(input); return stats; } diff --git a/src/duckdb/src/optimizer/topn_window_elimination.cpp b/src/duckdb/src/optimizer/topn_window_elimination.cpp index eb50d454c..7b39fe4bf 100644 --- a/src/duckdb/src/optimizer/topn_window_elimination.cpp +++ b/src/duckdb/src/optimizer/topn_window_elimination.cpp @@ -544,15 +544,6 @@ TopNWindowElimination::CreateProjectionOperator(unique_ptr op, return unique_ptr(std::move(logical_projection)); } -class ColumnReferenceExtractor : public BaseColumnPruner { -public: - static column_binding_map_t GetReferences(unique_ptr *expression) { - ColumnReferenceExtractor extractor; - extractor.VisitExpression(expression); - return extractor.column_references; - } -}; - optional_idx TopNWindowElimination::CanOptimize(LogicalOperator &op) { const optional_idx cant_optimize; if (op.type != LogicalOperatorType::LOGICAL_FILTER) { @@ -660,6 +651,10 @@ optional_idx TopNWindowElimination::CanOptimize(LogicalOperator &op) { return cant_optimize; } const auto &window = child.get().Cast(); + // Give up if window fusion has already taking this. + if (window.partition_limit.IsValid()) { + return cant_optimize; + } if (window.window_index != filter_col_idx) { return cant_optimize; } @@ -1056,31 +1051,23 @@ bool TopNWindowElimination::CanUseLateMaterialization(const LogicalWindow &windo if (lidxs.size() != 1 || ridxs.size() != 1) { return false; } - auto left_idx = lidxs[0]; - auto right_idx = ridxs[0]; + const column_binding_set_t left_bindings(left_column_bindings.begin(), left_column_bindings.end()); + const column_binding_set_t right_bindings(right_column_bindings.begin(), right_column_bindings.end()); bool all_left_replaceable = true; bool all_right_replaceable = true; - for (idx_t i = 0; i < projections.size(); i++) { - const auto &projection = projections[i]; - if (projection.table_index != left_idx && projection.table_index != right_idx) { + for (const auto &projection : projections) { + const bool is_left = left_bindings.find(projection) != left_bindings.end(); + if (!is_left && right_bindings.find(projection) == right_bindings.end()) { return false; } - if (projection.table_index == left_idx && projection.column_index >= left_column_bindings.size()) { - return false; - } - if (projection.table_index == right_idx && projection.column_index >= right_column_bindings.size()) { - return false; + if (replaceable_bindings.find(projection) != replaceable_bindings.end()) { + continue; } - auto &column_binding = projection.table_index == left_idx - ? left_column_bindings[projection.column_index] - : right_column_bindings[projection.column_index]; - if (replaceable_bindings.find(column_binding) == replaceable_bindings.end()) { - if (column_binding.table_index == left_idx) { - all_left_replaceable = false; - } else { - all_right_replaceable = false; - } + if (is_left) { + all_left_replaceable = false; + } else { + all_right_replaceable = false; } } @@ -1089,25 +1076,10 @@ bool TopNWindowElimination::CanUseLateMaterialization(const LogicalWindow &windo return false; } - TableIndex replace_table_idx = all_right_replaceable ? right_idx : left_idx; - for (idx_t i = 0; i < projections.size(); i++) { - const auto projection_idx = projections[i]; - if (projection_idx.table_index != left_idx && projection_idx.table_index != right_idx) { - return false; - } - if (projection_idx.table_index == left_idx && - projection_idx.column_index >= left_column_bindings.size()) { - return false; - } - if (projection_idx.table_index == right_idx && - projection_idx.column_index >= right_column_bindings.size()) { - return false; - } - auto &column_binding = projection_idx.table_index == left_idx - ? left_column_bindings[projection_idx.column_index] - : right_column_bindings[projection_idx.column_index]; - if (column_binding.table_index == replace_table_idx) { - projections[i] = replaceable_bindings[column_binding]; + const auto &replace_bindings = all_right_replaceable ? right_bindings : left_bindings; + for (auto &projection : projections) { + if (replace_bindings.find(projection) != replace_bindings.end()) { + projection = replaceable_bindings[projection]; } } diff --git a/src/duckdb/src/optimizer/window_fusion.cpp b/src/duckdb/src/optimizer/window_fusion.cpp new file mode 100644 index 000000000..581b388c1 --- /dev/null +++ b/src/duckdb/src/optimizer/window_fusion.cpp @@ -0,0 +1,195 @@ +#include "duckdb/optimizer/window_fusion.hpp" + +#include "duckdb/optimizer/topn_window_elimination.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/database.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_window.hpp" +#include "duckdb/optimizer/remove_unused_columns.hpp" +#include "duckdb/execution/operator/aggregate/physical_streaming_window.hpp" + +namespace duckdb { + +WindowFusion::WindowFusion(ClientContext &client, optional_ptr>> stats) + : client(client), stats(stats) { + D_ASSERT(stats); +} + +optional_idx WindowFusion::CanOptimize(LogicalOperator &op) { + const optional_idx cant_optimize; + if (op.type != LogicalOperatorType::LOGICAL_FILTER) { + return cant_optimize; + } + + const auto &filter = op.Cast(); + if (filter.expressions.size() != 1) { + return cant_optimize; + } + + const auto comparison = filter.expressions[0]->GetExpressionType(); + switch (comparison) { + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + case ExpressionType::COMPARE_LESSTHAN: + case ExpressionType::COMPARE_EQUAL: + break; + default: + return cant_optimize; + } + + auto &filter_comparison = filter.expressions[0]->Cast(); + auto &right = BoundComparisonExpression::Right(filter_comparison); + if (right.GetExpressionType() != ExpressionType::VALUE_CONSTANT) { + return cant_optimize; + } + auto &filter_value = right.Cast(); + if (filter_value.GetValue().type() != LogicalType::BIGINT) { + return cant_optimize; + } + if (filter_value.GetValue().IsNull()) { + return cant_optimize; + } + + const auto bigint_value = filter_value.GetValue().GetValue(); + optional_idx can_optimize(0); + switch (comparison) { + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + if (bigint_value < 1) { + break; + } + can_optimize = UnsafeNumericCast(bigint_value); + break; + case ExpressionType::COMPARE_LESSTHAN: + if (bigint_value < 2) { + break; + } + can_optimize = UnsafeNumericCast(bigint_value - 1); + break; + case ExpressionType::COMPARE_EQUAL: + // TODO: Handle other values + if (bigint_value < 1) { + break; + } + if (bigint_value != 1) { + return cant_optimize; + } + can_optimize = UnsafeNumericCast(bigint_value); + break; + default: + return cant_optimize; + } + + auto &left = BoundComparisonExpression::LeftMutable(filter_comparison); + if (left->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + return cant_optimize; + } + auto column_references = ColumnReferenceExtractor::GetReferences(&left); + + reference child = *filter.children[0]; + while (child.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto &projection = child.get().Cast(); + if (column_references.size() != 1) { + return cant_optimize; + } + + const auto current_column_ref = column_references.begin()->first; + D_ASSERT(current_column_ref.table_index == projection.table_index); + // The filter has to name the window column itself. An expression that only mentions it, such as + // row_number + 10, is a different predicate, and following the inner reference would drop that expression. + auto &proj_expr = *projection.expressions[current_column_ref.column_index]; + if (proj_expr.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + return cant_optimize; + } + column_references = + ColumnReferenceExtractor::GetReferences(&projection.expressions[current_column_ref.column_index]); + + child = *child.get().children[0]; + } + + if (column_references.size() != 1) { + return cant_optimize; + } + const auto filter_col_idx = column_references.begin()->first.table_index; + + if (child.get().type != LogicalOperatorType::LOGICAL_WINDOW) { + return cant_optimize; + } + const auto &window = child.get().Cast(); + if (window.window_index != filter_col_idx) { + return cant_optimize; + } + const auto &first_window_expr = window.expressions[0]->Cast(); + for (auto &partition : first_window_expr.Partitions()) { + if (partition->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return cant_optimize; + } + } + if (window.expressions.size() != 1) { + for (idx_t i = 1; i < window.expressions.size(); ++i) { + if (!window.expressions[i]->Equals(first_window_expr)) { + return cant_optimize; + } + } + } + if (window.expressions[0]->GetExpressionType() != ExpressionType::WINDOW_ROW_NUMBER) { + return cant_optimize; + } + auto &window_expr = window.expressions[0]->Cast(); + + if (!window_expr.ArgOrders().empty()) { + return cant_optimize; + } + + return can_optimize; +} + +unique_ptr WindowFusion::OptimizeInternal(unique_ptr op) { + // We are not changing any bindings, just fusing a particular filter into an existing window. + // So we can just visit children and return the current operator (or its child.) + for (auto &child : op->children) { + child = OptimizeInternal(std::move(child)); + } + + const auto partition_limit = WindowFusion::CanOptimize(*op); + if (!partition_limit.IsValid()) { + return op; + } + + // Remove the Filter + D_ASSERT(op->children.size() == 1); + auto &filter = op->Cast(); + + // Find the child Window + reference child = *filter.children[0]; + while (child.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { + child = *child.get().children[0]; + } + D_ASSERT(child.get().type == LogicalOperatorType::LOGICAL_WINDOW); + auto &window = child.get().Cast(); + auto &wexpr = window.expressions[0]->Cast(); + + // Restrict to implemented cases + if (!PhysicalStreamingWindow::IsStreamingFunction(client, wexpr)) { + return op; + } + + // Add the limit to the child Window + window.partition_limit = partition_limit; + + // Return the Filter itself (to handle BETWEEN and other situations + // where the window operators cannot (completely) apply the filter.) + return op; +} + +unique_ptr WindowFusion::Optimize(unique_ptr op) { + auto &extension_manager = client.db->GetExtensionManager(); + if (!extension_manager.ExtensionIsLoaded("core_functions")) { + return op; + } + + return OptimizeInternal(std::move(op)); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/window_join_pushdown.cpp b/src/duckdb/src/optimizer/window_join_pushdown.cpp index 8bedbd83b..77a740546 100644 --- a/src/duckdb/src/optimizer/window_join_pushdown.cpp +++ b/src/duckdb/src/optimizer/window_join_pushdown.cpp @@ -141,7 +141,7 @@ unique_ptr WindowJoinPushdown::OptimizeInternal(unique_ptrchildren.emplace_back(std::move(join.children[1])); } - auto new_window = make_uniq(window.window_index); + auto new_window = make_uniq(window.window_index, window.partition_limit); new_window->children.emplace_back(std::move(new_join)); for (auto &expr : window.expressions) { new_window->expressions.emplace_back(std::move(expr)); diff --git a/src/duckdb/src/optimizer/window_self_join.cpp b/src/duckdb/src/optimizer/window_self_join.cpp index a60428813..4d3b77077 100644 --- a/src/duckdb/src/optimizer/window_self_join.cpp +++ b/src/duckdb/src/optimizer/window_self_join.cpp @@ -6,6 +6,7 @@ #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cross_product.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" @@ -192,6 +193,13 @@ bool WindowSelfJoinOptimizer::CanOptimize(const BoundWindowExpression &w_expr, } bool WindowSelfJoinOptimizer::CanOptimize(const LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_GET) { + auto &get = op.Cast(); + // the copy binds the function again, which brings back the files a filter pruned + if (!get.function.HasSerializationCallbacks() && !get.extra_info.file_filters.empty()) { + return false; + } + } switch (op.type) { case LogicalOperatorType::LOGICAL_GET: case LogicalOperatorType::LOGICAL_EXPRESSION_GET: diff --git a/src/duckdb/src/parallel/executor.cpp b/src/duckdb/src/parallel/executor.cpp index f2e09af79..3f39e4fc1 100644 --- a/src/duckdb/src/parallel/executor.cpp +++ b/src/duckdb/src/parallel/executor.cpp @@ -63,6 +63,8 @@ struct ScheduleEventData { //! The schedule ResolveExternalInputs validated, reused so the runtime-filter edges the analysis saw are //! exactly the edges that run (nullptr when nothing needed resolution or for reschedules). unique_ptr resolved_schedule; + //! The events without dependencies, which the caller schedules + vector> ready_events; }; static shared_ptr CreatePipelineScheduleEvent(const PipelineScheduleStage &stage, bool initial_schedule) { @@ -124,22 +126,21 @@ void Executor::ScheduleEventsInternal(ScheduleEventData &event_data) { // verify that we have no cyclic dependencies VerifyScheduledEvents(events); - // schedule the pipelines that do not have dependencies + // the events that do not have dependencies start the schedule for (auto &event : events) { if (!event->HasDependencies()) { - event->Schedule(); - if (!event->HasTasks() && !event->IsFinished() && event->AutoFinishWithoutTasks()) { - event->Finish(); - } + event_data.ready_events.push_back(event); } } } -void Executor::ScheduleEvents(const vector> &meta_pipelines, - unique_ptr resolved_schedule) { - ScheduleEventData event_data(meta_pipelines, events, true); - event_data.resolved_schedule = std::move(resolved_schedule); - ScheduleEventsInternal(event_data); +void Executor::ScheduleReadyEvents(const vector> &ready_events) { + for (auto &event : ready_events) { + event->Schedule(); + if (!event->HasTasks() && !event->IsFinished() && event->AutoFinishWithoutTasks()) { + event->Finish(); + } + } } void Executor::VerifyScheduledEvents(const vector> &events) { @@ -205,6 +206,7 @@ void Executor::ReschedulePipelines(const vector> &pipel vector> &events_p) { ScheduleEventData event_data(pipelines_p, events_p, false); ScheduleEventsInternal(event_data); + ScheduleReadyEvents(event_data.ready_events); } bool Executor::NextExecutor() { @@ -257,6 +259,8 @@ void Executor::Initialize(PhysicalOperator &plan) { void Executor::InitializeInternal(PhysicalOperator &plan) { auto &scheduler = TaskScheduler::GetScheduler(context); + vector> to_schedule; + ScheduleEventData event_data(to_schedule, events, true); { lock_guard elock(executor_lock); physical_plan = &plan; @@ -276,11 +280,10 @@ void Executor::InitializeInternal(PhysicalOperator &plan) { root_pipeline->Build(*physical_plan); // Resolve graph-dependent input modes after every pipeline and dependency has been constructed. - vector> to_schedule; root_pipeline->GetMetaPipelines(to_schedule, true, true); // Model the runtime-filter ordering edges under the same condition ScheduleRuntimeFilters uses below: // this is the initial schedule, so only recursive CTEs disable them. - auto resolved_schedule = state.ResolveExternalInputs(to_schedule, recursive_ctes.empty()); + event_data.resolved_schedule = state.ResolveExternalInputs(to_schedule, recursive_ctes.empty()); profiler->Initialize(plan); root_pipeline->Ready(); @@ -301,10 +304,13 @@ void Executor::InitializeInternal(PhysicalOperator &plan) { // collect all pipelines from the root pipelines (recursively) for the progress bar and verify them root_pipeline->GetPipelines(pipelines, true); - // finally, verify and schedule + // finally, verify the pipelines and create the events VerifyPipelines(); - ScheduleEvents(to_schedule, std::move(resolved_schedule)); + ScheduleEventsInternal(event_data); } + // scheduling creates tasks, and the destructor of a task takes executor_lock: a task destroyed because its + // scheduling fails must not find the lock held by this thread + ScheduleReadyEvents(event_data.ready_events); } void Executor::CancelTasks() { diff --git a/src/duckdb/src/parallel/pipeline.cpp b/src/duckdb/src/parallel/pipeline.cpp index 1e53c15d6..3a465ec84 100644 --- a/src/duckdb/src/parallel/pipeline.cpp +++ b/src/duckdb/src/parallel/pipeline.cpp @@ -127,6 +127,18 @@ void Pipeline::GetDetailedProgress(PipelineProgress &progress) { auto state = GetSourceState(); if (state) { progress.source = source->GetProgress(client, *state); + } else if (IsExternalInput()) { + // this pipeline has no source state: its producers push their chunks into it, so it advances with them + progress.source.done = 0; + progress.source.total = 0; + for (auto &producer_ref : external_input_producers) { + auto producer = producer_ref.lock(); + D_ASSERT(producer); + PipelineProgress producer_progress; + producer->GetDetailedProgress(producer_progress); + producer_progress.source.Normalize(1.0); + progress.source.Add(producer_progress.source); + } } else { progress.source.done = 0; progress.source.total = double(source_cardinality); @@ -217,6 +229,16 @@ idx_t Pipeline::GetMaxThreads() { return max_threads; } +PipelineExecutionOrder Pipeline::GetExecutionOrder() const { + if (!sink) { + return PipelineExecutionOrder::ORDERED; + } + if (sink->RequiredPartitionInfo().AnyRequired()) { + return PipelineExecutionOrder::PARTITIONED; + } + return IsOrderDependent() ? PipelineExecutionOrder::ORDERED : PipelineExecutionOrder::UNORDERED; +} + bool Pipeline::IsOrderDependent() const { if (source) { auto source_order = source->SourceOrder(); diff --git a/src/duckdb/src/parallel/pipeline_executor.cpp b/src/duckdb/src/parallel/pipeline_executor.cpp index e61574823..6e944d03c 100644 --- a/src/duckdb/src/parallel/pipeline_executor.cpp +++ b/src/duckdb/src/parallel/pipeline_executor.cpp @@ -71,7 +71,7 @@ PipelineExecutor::PipelineExecutor(ClientContext &context_p, Pipeline &pipeline_ if (current_operator.IsSink() && current_operator.sink_state->state == SinkFinalizeType::NO_OUTPUT_POSSIBLE) { // one of the operators has already figured out no output is possible // we can skip executing the pipeline - FinishProcessing(); + FinishProcessing(NumericCast(i + 1)); } } InitializeChunk(final_chunk); @@ -81,6 +81,7 @@ void PipelineExecutor::Reset() { auto allow_reuse = Settings::Get(context.client); // Reset execution flags + exhausted_source = false; exhausted_pipeline = false; finalized = false; started_flushing = false; @@ -142,7 +143,7 @@ void PipelineExecutor::Reset() { } if (current_operator.IsSink() && current_operator.sink_state->state == SinkFinalizeType::NO_OUTPUT_POSSIBLE) { - FinishProcessing(); + FinishProcessing(NumericCast(i + 1)); } } @@ -333,7 +334,7 @@ PipelineExecuteResult PipelineExecutor::Execute(idx_t max_chunks) { ExecutionBudget chunk_budget(max_chunks); do { - context.client.InterruptCheck(); + context.client.FastInterruptCheck(); switch (pending_batch_advance_state) { case PendingBatchAdvanceState::MINIMUM_UPDATE: if (UpdateMinBatchIndex() == SinkNextBatchType::BLOCKED) { @@ -539,6 +540,7 @@ bool PipelineExecutor::IsFinishedProcessing() const { void PipelineExecutor::FinishProcessing(int32_t operator_idx) { finished_processing_idx = operator_idx < 0 ? NumericLimits::Maximum() : operator_idx; + exhausted_pipeline = true; in_process_operators = stack(); pipeline.PreventBlocking(); @@ -632,7 +634,7 @@ PipelineExecuteResult PipelineExecutor::PushInputChunk(DataChunk &input, Executi } while (true) { - context.client.InterruptCheck(); + context.client.FastInterruptCheck(); auto result = ExecutePushInternal(input, chunk_budget); if (result == OperatorResultType::BLOCKED) { remaining_sink_chunk = true; @@ -757,7 +759,7 @@ OperatorResultType PipelineExecutor::Execute(DataChunk &input, DataChunk &result return OperatorResultType::NEED_MORE_INPUT; } while (true) { - context.client.InterruptCheck(); + context.client.FastInterruptCheck(); // now figure out where to put the chunk // if current_idx is the last possible index (>= operators.size()) we write to the result // otherwise we write to an intermediate chunk @@ -900,7 +902,7 @@ void PipelineExecutor::InitializeChunk(DataChunk &chunk) { } void PipelineExecutor::StartOperator(PhysicalOperator &op) { - context.client.InterruptCheck(); + context.client.FastInterruptCheck(); context.thread.profiler.StartOperator(&op); } diff --git a/src/duckdb/src/parallel/runtime_filter_schedule.cpp b/src/duckdb/src/parallel/runtime_filter_schedule.cpp index 1caa71e1f..19eeba2eb 100644 --- a/src/duckdb/src/parallel/runtime_filter_schedule.cpp +++ b/src/duckdb/src/parallel/runtime_filter_schedule.cpp @@ -3,6 +3,7 @@ #include "duckdb/execution/operator/join/physical_comparison_join.hpp" #include "duckdb/execution/operator/scan/physical_table_scan.hpp" #include "duckdb/parallel/pipeline.hpp" +#include "duckdb/storage/storage_info.hpp" namespace duckdb { @@ -24,7 +25,13 @@ static optional_ptr RuntimeFilterProducer(Pipeline &pipe } static bool IsSmallBuild(const PhysicalOperator &op) { - if (op.estimated_cardinality > DEFAULT_STANDARD_VECTOR_SIZE || op.IsSink()) { + // Membership joins do not expand the probe side. + bool membership_join = false; + if (op.type == PhysicalOperatorType::HASH_JOIN) { + const auto join_type = op.Cast().join_type; + membership_join = join_type == JoinType::MARK || join_type == JoinType::SEMI || join_type == JoinType::ANTI; + } + if (op.estimated_cardinality > DEFAULT_ROW_GROUP_SIZE || (op.IsSink() && !membership_join)) { return false; } for (auto &child : op.children) { diff --git a/src/duckdb/src/parallel/scan_affinity_queue.cpp b/src/duckdb/src/parallel/scan_affinity_queue.cpp new file mode 100644 index 000000000..bfb307c93 --- /dev/null +++ b/src/duckdb/src/parallel/scan_affinity_queue.cpp @@ -0,0 +1,68 @@ +#include "duckdb/parallel/scan_affinity_queue.hpp" + +#include "duckdb/common/numeric_utils.hpp" +#include "duckdb/parallel/scan_read_ahead.hpp" + +namespace duckdb { + +ScanAffinityQueue::Shard::Shard(idx_t probe_index) : probe_index(probe_index) { +} + +ScanAffinityQueue::ScanAffinityQueue(idx_t shard_count) : probe_slots(NextPowerOfTwo(shard_count)) { + D_ASSERT(shard_count > 0); + // Spread shards across power-of-two slots so XOR probing keeps balanced ranges together. + for (idx_t i = 0; i < shard_count; i++) { + const auto probe_index = i * probe_slots.size() / shard_count; + shards.push_back(make_uniq(probe_index)); + probe_slots[probe_index] = shards.back().get(); + } +} + +ScanAffinityQueue::~ScanAffinityQueue() = default; + +void ScanAffinityQueue::Push(idx_t producer_shard, optional_idx affinity, unique_ptr job) { + const auto destination = affinity.IsValid() ? affinity.GetIndex() : producer_shard; + D_ASSERT(destination < shards.size()); + auto &shard = *shards[destination]; + lock_guard guard(shard.lock); + auto &queue = affinity.IsValid() ? shard.affinity : shard.unknown; + queue.assignments.push_back(std::move(job)); + queue.ready.store(queue.assignments.size(), std::memory_order_relaxed); +} + +bool ScanAffinityQueue::TryPop(idx_t local_shard, unique_ptr &job) { + D_ASSERT(local_shard < shards.size()); + const auto probe_index = shards[local_shard]->probe_index; + return TryTakeAssignment(probe_index, ProbeMode::ADVISORY, job) || + TryTakeAssignment(probe_index, ProbeMode::AUTHORITATIVE, job); +} + +bool ScanAffinityQueue::TryTakeAssignment(idx_t probe_index, ProbeMode mode, unique_ptr &job) { + // Prefer cached assignments before considering unknown placement. + for (const auto has_affinity : {true, false}) { + for (idx_t distance = 0; distance < probe_slots.size(); distance++) { + auto slot = probe_slots[probe_index ^ distance]; + if (!slot) { + continue; + } + auto &shard = *slot; + auto &queue = has_affinity ? shard.affinity : shard.unknown; + if (mode == ProbeMode::ADVISORY && !queue.ready.load(std::memory_order_relaxed)) { + continue; + } + { + lock_guard guard(shard.lock); + if (queue.assignments.empty()) { + continue; + } + job = std::move(queue.assignments.front()); + queue.assignments.pop_front(); + queue.ready.store(queue.assignments.size(), std::memory_order_relaxed); + } + return true; + } + } + return false; +} + +} // namespace duckdb diff --git a/src/duckdb/src/parallel/scan_read_ahead.cpp b/src/duckdb/src/parallel/scan_read_ahead.cpp index 7fd4750a2..ce0f45b98 100644 --- a/src/duckdb/src/parallel/scan_read_ahead.cpp +++ b/src/duckdb/src/parallel/scan_read_ahead.cpp @@ -2,15 +2,29 @@ #include "duckdb/parallel/scan_read_ahead.hpp" #include "duckdb/common/file_system.hpp" +#include "duckdb/execution/executor.hpp" #include "duckdb/function/table_function.hpp" #include "duckdb/logging/log_type.hpp" #include "duckdb/logging/logger.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/settings.hpp" +#include "duckdb/parallel/scan_affinity_queue.hpp" #include "duckdb/parallel/task_scheduler.hpp" namespace duckdb { +ReadAheadJobCompletion::ReadAheadJobCompletion(shared_ptr executor_p) + : executor(std::move(executor_p)), pending_io_tasks(0) { +} + +ReadAheadJobCompletion::~ReadAheadJobCompletion() = default; + +void ReadAheadJobCompletion::OwnJob(ScanReadAhead &read_ahead_p, unique_ptr job) { + D_ASSERT(!job->io_completion); + read_ahead = read_ahead_p; + ready_job = std::move(job); +} + void ReadAheadJobCompletion::AddIOTask() { ++pending_io_tasks; } @@ -22,6 +36,10 @@ void ReadAheadJobCompletion::FinishIOTask() { // I/O tasks still outstanding, nothing to wake yet return; } + if (ready_job) { + read_ahead->CompleteJob(std::move(ready_job)); + return; + } // wake the parked scan task, if any const annotated_lock_guard guard {parked_scan.lock}; parked_scan.UnblockTasks(); @@ -65,35 +83,68 @@ void ReadAheadJobCompletion::WaitForIO() { class ReadAheadIOTask : public BaseExecutorTask { public: ReadAheadIOTask(TaskExecutor &executor, unique_ptr task_p, - shared_ptr completion_p, ScanReadAhead &read_ahead_p) - : BaseExecutorTask(executor), task(std::move(task_p)), completion(std::move(completion_p)), - read_ahead(read_ahead_p) { + shared_ptr completion_p) + : BaseExecutorTask(executor), task(std::move(task_p)), completion(std::move(completion_p)) { completion->AddIOTask(); } ~ReadAheadIOTask() override { - // release the task's resources before waking the scan, they may outlive the database otherwise - task.reset(); - // If we are done we decrement the pending - completion->FinishIOTask(); + Finish(); } void ExecuteTask() override { + RunningRead running(completion->read_ahead); try { // Does the actual IO task->Execute(); } catch (std::exception &ex) { - // recording the error through the read-ahead also wakes the threads waiting for progress - read_ahead.PushError(ErrorData(ex)); + executor.PushTaskError(ex); + } catch (...) { + executor.PushTaskError("Unknown exception during read-ahead I/O"); + } + Finish(); + } + + void Cancel() override { + Finish(); + } + +private: + //! Affinity waiters need a scan-progress wake-up before the executor counts this read as complete. + class RunningRead { + public: + explicit RunningRead(optional_ptr read_ahead) : read_ahead(read_ahead) { + if (read_ahead) { + ++read_ahead->running_reads; + } + } + ~RunningRead() { + if (read_ahead && read_ahead->running_reads.fetch_sub(1) == 1) { + // A parked consumer must retry even when the remaining reads have not started. + read_ahead->SignalProgress(false); + } } - // release the task's resources while the executor still counts this task as running + + private: + optional_ptr read_ahead; + }; + + void Finish() { + if (!completion) { + return; + } + // Publish before returning to executor completion accounting, including cancellation. task.reset(); + auto finished = std::move(completion); + finished->FinishIOTask(); + } + + string TaskType() const override { + return "ReadAheadIOTask"; } private: unique_ptr task; shared_ptr completion; - //! Outlives the task, the read-ahead drains its executor before it is destroyed - ScanReadAhead &read_ahead; }; //! Async task that opens one file ahead of decoding @@ -112,6 +163,10 @@ class FileOpenTask : public BaseExecutorTask { cancel_fn(); } + string TaskType() const override { + return "FileOpenTask"; + } + private: std::function open_fn; std::function cancel_fn; @@ -150,13 +205,28 @@ static idx_t GetOpenFileBudget(ClientContext &context) { return FileSystem::GetFileDescriptorShare(file_descriptor_limit); } -ScanReadAhead::ScanReadAhead(ClientContext &context, idx_t read_ahead_depth_p, - unique_ptr memory_governor_p) - : context(context), read_ahead_depth(read_ahead_depth_p), memory_governor(std::move(memory_governor_p)), +idx_t ScanReadAhead::JobWindow(ScanReadAheadPolicy policy, idx_t read_ahead_depth, idx_t scan_concurrency) { + if (policy == ScanReadAheadPolicy::ORDERED) { + return read_ahead_depth; + } + // Pending reads also occupy slots for work that would otherwise be held by scan workers. + const auto depth = MinValue(read_ahead_depth, AFFINITY_WINDOW); + return depth + MinValue(scan_concurrency, AFFINITY_WINDOW - depth); +} + +ScanReadAhead::ScanReadAhead(ClientContext &context, ScanReadAheadPolicy policy, idx_t read_ahead_depth, + unique_ptr memory_governor_p, bool prefetch_enabled_p, + idx_t shard_count, idx_t scan_concurrency) + : context(context), prefetch_enabled(prefetch_enabled_p), + job_window(JobWindow(policy, read_ahead_depth, scan_concurrency)), memory_governor(std::move(memory_governor_p)), open_window(MaxValue(TaskScheduler::GetScheduler(context).NumberOfAsyncThreads() * 2, memory_governor ? 0 : read_ahead_depth)), - open_file_budget(GetOpenFileBudget(context)) { - D_ASSERT(read_ahead_depth_p > 0); + open_file_budget(GetOpenFileBudget(context)), + affinity(policy == ScanReadAheadPolicy::AFFINITY ? make_uniq(shard_count) : nullptr) { + D_ASSERT(read_ahead_depth > 0); + if (affinity && memory_governor) { + memory_governor->UpdateReservation(MINIMUM_AFFINITY_JOB_CHARGE * AFFINITY_WINDOW); + } backlog_budget = memory_governor ? memory_governor->BackpressureBudget() : NumericLimits::Maximum(); executor = make_shared_ptr(context, TaskSchedulerType::ASYNC); } @@ -166,24 +236,239 @@ ScanReadAhead::~ScanReadAhead() { } void ScanReadAhead::CancelAndDrain() { + done = true; executor->CancelAndDrain(); } -unique_ptr ScanReadAhead::Create(ClientContext &context) { - if (TaskScheduler::GetScheduler(context).NumberOfAsyncThreads() == 0) { - // read-ahead schedules its I/O on the async pool, without async threads there is nothing to gain - return nullptr; - } +unique_ptr ScanReadAhead::Create(ClientContext &context, ScanReadAheadPolicy policy, bool prefetch, + idx_t shard_count, idx_t scan_concurrency) { const auto configured_depth = Settings::Get(context); - if (configured_depth == 0) { + prefetch = prefetch && TaskScheduler::GetScheduler(context).NumberOfAsyncThreads() > 0 && configured_depth != 0; + if (!prefetch) { + if (policy == ScanReadAheadPolicy::AFFINITY) { + return make_uniq(context, policy, AFFINITY_WINDOW, nullptr, false, shard_count, + scan_concurrency); + } return nullptr; } if (configured_depth < 0) { // automatic mode, unlimited depth, the backlog is bounded by a temp-memory reservation instead - return make_uniq(context, NumericLimits::Maximum(), - make_uniq(context.GetContext())); + return make_uniq(context, policy, NumericLimits::Maximum(), + make_uniq(context.GetContext()), true, shard_count, + scan_concurrency); + } + return make_uniq(context, policy, NumericCast(configured_depth), nullptr, true, shard_count, + scan_concurrency); +} + +idx_t ScanReadAhead::MinimumJobCharge() const { + if (!affinity) { + return MINIMUM_ORDERED_JOB_CHARGE; + } + // A fixed assignment window bounds metadata when no memory governor is in use. + return memory_governor ? MINIMUM_AFFINITY_JOB_CHARGE : 0; +} + +idx_t ScanReadAhead::ReserveBatch() { + const auto minimum = MinimumJobCharge(); + auto reserved = PRODUCE_BATCH; + const auto previous_bytes = minimum ? pending_budget_charge.fetch_add(reserved * minimum) : 0; + const auto depth = ReservationDepth(previous_bytes); + auto count = active_jobs.load(std::memory_order_relaxed); + while (count < depth) { + const auto slots = MinValue(reserved, depth - count); + if (active_jobs.compare_exchange_weak(count, count + slots, std::memory_order_relaxed)) { + if (minimum) { + pending_budget_charge -= (reserved - slots) * minimum; + } + ++active_producers; + return slots; + } + } + if (minimum) { + pending_budget_charge -= reserved * minimum; + } + return 0; +} + +bool ScanReadAhead::TryProduceBatch(const ProduceJobCallback &produce, idx_t local_shard) { + ThrowIfError(); + if (IsDone()) { + return false; + } + const auto count = ReserveBatch(); + if (!count) { + return false; + } + ProducerReservation reservation(*this, count); + try { + for (idx_t i = 0; i < count; i++) { + ThrowIfError(); + vector> io_tasks; + auto job = produce(io_tasks); + if (!job) { + ThrowIfError(); + SetDone(); + break; + } + job->producer_shard = local_shard; + ScheduleReadyJob(std::move(job), std::move(io_tasks), reservation); + if (pending_budget_charge.load() >= backlog_budget.load()) { + break; + } + } + } catch (std::exception &ex) { + executor->PushTaskError(ex); + SignalProgress(true); + throw; + } catch (...) { + executor->PushTaskError("Unknown exception while producing read-ahead work"); + SignalProgress(true); + throw; + } + return true; +} + +void ScanReadAhead::ScheduleReadyJob(unique_ptr job, vector> io_tasks, + ProducerReservation &reservation) { + const auto minimum = MinimumJobCharge(); + job->budget_charge = memory_governor ? MaxValue(minimum, job->GetMemoryUsage()) : 0; + for (auto &task : io_tasks) { + if (memory_governor) { + job->budget_charge += task->GetIOSize(); + } + } + if (io_tasks.empty()) { + if (job->budget_charge > minimum) { + pending_budget_charge += job->budget_charge - minimum; + } + reservation.Commit(); + try { + UpdateBudget(); + } catch (...) { + RetireJob(job->budget_charge); + throw; + } + CompleteJob(std::move(job)); + return; + } + auto completion = make_shared_ptr(executor); + // Hold publication until all wrappers, submission and producer bookkeeping are finished. + completion->AddIOTask(); + struct PublishGuard { + explicit PublishGuard(ReadAheadJobCompletion &completion) : completion(completion) { + } + ~PublishGuard() { + completion.FinishIOTask(); + } + ReadAheadJobCompletion &completion; + } publish(*completion); + vector> read_tasks; + read_tasks.reserve(io_tasks.size()); + for (auto &task : io_tasks) { + read_tasks.push_back(make_uniq(*executor, std::move(task), completion)); + } + if (job->budget_charge > minimum) { + pending_budget_charge += job->budget_charge - minimum; + } + reservation.Commit(); + completion->OwnJob(*this, std::move(job)); + try { + UpdateBudget(); + DUCKDB_LOG(context, AsyncTaskScheduleLogType, "READ_AHEAD", read_tasks.size()); + executor->ScheduleTasks(std::move(read_tasks)); + } catch (std::exception &ex) { + executor->PushTaskError(ex); + throw; + } catch (...) { + executor->PushTaskError("Unknown exception while scheduling read-ahead I/O"); + throw; + } +} + +void ScanReadAhead::RetireJob(idx_t budget_charge) { + if (budget_charge) { + pending_budget_charge -= budget_charge; + } + ReleaseSlot(); + SignalProgress(true); +} + +void ScanReadAhead::CompleteJob(unique_ptr job) { + const auto budget_charge = job->budget_charge; + if (executor->IsCancelled() || executor->HasError()) { + RetireJob(budget_charge); + return; + } + try { + const auto hint = job->ResolveAffinity(); + if (executor->IsCancelled() || executor->HasError()) { + RetireJob(budget_charge); + return; + } + const auto producer_shard = job->producer_shard; + affinity->Push(producer_shard, hint, std::move(job)); + } catch (std::exception &ex) { + executor->PushTaskError(ex); + RetireJob(budget_charge); + return; + } catch (...) { + executor->PushTaskError("Unknown exception while publishing read-ahead work"); + RetireJob(budget_charge); + return; + } + SignalProgress(false); +} + +bool ScanReadAhead::TryParkForProgress(TableFunctionInput &input, idx_t epoch) { + lock_guard guard(lock); + parked_scans.push_back(*input.interrupt_state); + ++waiting_threads; + // Register before rechecking: a publisher can skip the lock while there are no waiters. + if (ProgressEpoch() != epoch || running_reads.load() == 0) { + parked_scans.pop_back(); + --waiting_threads; + return false; + } + input.async_result = AsyncResultType::BLOCKED; + return true; +} + +ScanReadAheadAcquire ScanReadAhead::AcquireReadyJob(ClientContext &context, TableFunctionInput &input, + const ProduceJobCallback &produce, + unique_ptr &job, idx_t local_shard) { + D_ASSERT(affinity && !job); + while (true) { + const auto epoch = ProgressEpoch(); + TryProduceBatch(produce, local_shard); + ThrowIfError(); + if (affinity->TryPop(local_shard, job)) { + ReleaseSlot(); + WaitForJob(*job); + SignalProgress(false); + return ScanReadAheadAcquire::ACQUIRED; + } + if (IsDone() && !HasActiveProducers() && active_jobs.load() == 0) { + ReleaseMemoryReservation(); + return ScanReadAheadAcquire::EXHAUSTED; + } + context.InterruptCheck(); + if (!IsDone() && active_jobs.load() < ReservationDepth(pending_budget_charge.load())) { + continue; + } + if (input.results_execution_mode == AsyncResultsExecutionMode::TASK_EXECUTOR && input.interrupt_state && + input.interrupt_state->CanCallback() && running_reads.load() > 0) { + if (TryParkForProgress(input, epoch)) { + return ScanReadAheadAcquire::PARKED; + } + continue; + } + // Without an executing read, keep progress independent of the worker pools. + if (TryRunPendingTask()) { + continue; + } + WaitForProgress(context, epoch); } - return make_uniq(context, NumericCast(configured_depth), nullptr); } bool ScanReadAhead::TryProduceJob(const ProduceJobCallback &claim_and_schedule) { @@ -191,7 +476,7 @@ bool ScanReadAhead::TryProduceJob(const ProduceJobCallback &claim_and_schedule) if (IsDone() || !TryReserveSlot()) { return false; } - ProducerReservation reservation(*this); + ProducerReservation reservation(*this, 1); try { vector> io_tasks; auto job = claim_and_schedule(io_tasks); @@ -202,7 +487,7 @@ bool ScanReadAhead::TryProduceJob(const ProduceJobCallback &claim_and_schedule) return false; } PushJob(std::move(job), std::move(io_tasks)); - reservation.committed = true; + reservation.Commit(); } catch (std::exception &ex) { PushError(ErrorData(ex)); throw; @@ -244,21 +529,25 @@ unique_ptr ScanReadAhead::ClaimJob() { void ScanReadAhead::WaitForJob(ScanReadAheadJob &job) { job.SettleIO(); + if (!job.budget_charge) { + ThrowIfError(); + return; + } // the job's I/O has completed, release its budget charge const auto budget = backlog_budget.load(); - const auto previous = pending_io_bytes.fetch_sub(job.io_bytes); - if (previous >= budget && previous - job.io_bytes < budget) { + const auto previous = pending_budget_charge.fetch_sub(job.budget_charge); + if (previous >= budget && previous - job.budget_charge < budget) { // the scan is no longer over budget, a waiting thread can produce SignalProgress(false); } - job.io_bytes = 0; + job.budget_charge = 0; ThrowIfError(); } ScanReadAheadAcquire ScanReadAhead::AcquireJob(ClientContext &context, TableFunctionInput &data_p, const ProduceJobCallback &claim_and_schedule, unique_ptr &job) { - D_ASSERT(!job); + D_ASSERT(!affinity && !job); optional yield_deadline; while (true) { const auto epoch = ProgressEpoch(); @@ -287,7 +576,7 @@ ScanReadAheadAcquire ScanReadAhead::AcquireJob(ClientContext &context, TableFunc yield_deadline = now + std::chrono::microseconds(PRODUCER_YIELD_MICROS); } if (now < *yield_deadline) { - context.InterruptCheck(); + context.FastInterruptCheck(); TaskScheduler::YieldThread(); } else { WaitForProgress(context, epoch); @@ -309,23 +598,31 @@ void ScanReadAhead::SetDone() { done = true; } -idx_t ScanReadAhead::ReservationDepth() const { - // over budget one job stays queued, claimed jobs hold the budget until their task resumes - const bool over_budget = - pending_io_bytes.load() >= backlog_budget.load() || ReadAheadOpenFile::Count() >= open_file_budget; - return over_budget ? 1 : read_ahead_depth; +idx_t ScanReadAhead::ReservationDepth(idx_t pending_bytes) const { + // Keep one job in flight while over budget so a consumer can still make progress. + const bool over_budget = pending_bytes >= backlog_budget.load() || ReadAheadOpenFile::Count() >= open_file_budget; + return over_budget ? 1 : job_window; +} + +void ScanReadAhead::UpdateBudget() { + const auto minimum = MinimumJobCharge(); + if (memory_governor && pending_budget_charge.load() + minimum > backlog_budget.load()) { + lock_guard guard(lock); + memory_governor->UpdateReservation(pending_budget_charge.load() + minimum); + backlog_budget = memory_governor->BackpressureBudget(); + } + DUCKDB_LOG(context, ReadAheadBudgetLogType, pending_budget_charge.load(), backlog_budget.load(), + active_jobs.load()); } bool ScanReadAhead::TryReserveSlot() { // take the minimum job charge up front so concurrent producers cannot all pass the budget check together - const bool over_memory_budget = pending_io_bytes.fetch_add(MINIMUM_JOB_IO_CHARGE) >= backlog_budget.load(); - // queued jobs keep their files open, so the open file budget bounds the queue too - const bool over_budget = over_memory_budget || ReadAheadOpenFile::Count() >= open_file_budget; - const idx_t depth = over_budget ? 1 : read_ahead_depth; + const auto previous_bytes = pending_budget_charge.fetch_add(MINIMUM_ORDERED_JOB_CHARGE); + const auto depth = ReservationDepth(previous_bytes); if (active_jobs.fetch_add(1) >= depth) { --active_jobs; - pending_io_bytes -= MINIMUM_JOB_IO_CHARGE; - if (active_jobs.load() < ReservationDepth()) { + pending_budget_charge -= MINIMUM_ORDERED_JOB_CHARGE; + if (active_jobs.load() < ReservationDepth(pending_budget_charge.load())) { // a concurrent attempt failed on this attempt's charge or slot, let it retry SignalProgress(false); } @@ -342,24 +639,19 @@ void ScanReadAhead::PushJob(unique_ptr job, vector> read_tasks; read_tasks.reserve(io_tasks.size()); for (auto &task : io_tasks) { - job->io_bytes += task->GetIOSize(); - read_tasks.push_back(make_uniq(*executor, std::move(task), completion, *this)); + job->budget_charge += task->GetIOSize(); + read_tasks.push_back(make_uniq(*executor, std::move(task), completion)); } - job->io_bytes = MaxValue(job->io_bytes, MINIMUM_JOB_IO_CHARGE); + job->budget_charge = MaxValue(job->budget_charge, MINIMUM_ORDERED_JOB_CHARGE); // the minimum charge was taken by TryReserveSlot, charge the remainder - pending_io_bytes += job->io_bytes - MINIMUM_JOB_IO_CHARGE; + pending_budget_charge += job->budget_charge - MINIMUM_ORDERED_JOB_CHARGE; // schedule the reads detached on the async pool right away, logged under their own label if (!read_tasks.empty()) { DUCKDB_LOG(context, AsyncTaskScheduleLogType, "READ_AHEAD", read_tasks.size()); } executor->ScheduleTasks(std::move(read_tasks)); + UpdateBudget(); lock_guard guard(lock); - if (memory_governor) { - // Reserve room for the next job before admission checks the budget. - memory_governor->UpdateReservation(pending_io_bytes.load() + MINIMUM_JOB_IO_CHARGE); - backlog_budget = memory_governor->BackpressureBudget(); - } - DUCKDB_LOG(context, ReadAheadBudgetLogType, pending_io_bytes.load(), backlog_budget.load(), active_jobs.load()); // producers push concurrently, so admit jobs to the queue in batch-index order if (job->batch_index < next_batch_index || !pending_jobs.emplace(job->batch_index, std::move(job)).second) { throw InternalException("Read-ahead jobs must have unique batch indexes, assigned densely from 0"); @@ -380,11 +672,12 @@ void ScanReadAhead::PushError(ErrorData error) { } void ScanReadAhead::ScheduleFileOpen(std::function open_fn, std::function cancel_fn) { + D_ASSERT(prefetch_enabled); executor->ScheduleTask(make_uniq(*executor, std::move(open_fn), std::move(cancel_fn))); } bool ScanReadAhead::CanScheduleOpen(idx_t files_ahead) const { - return files_ahead < open_window && ReadAheadOpenFile::Count() < open_file_budget; + return prefetch_enabled && files_ahead < open_window && ReadAheadOpenFile::Count() < open_file_budget; } bool ScanReadAhead::TryRunPendingTask() { @@ -427,15 +720,44 @@ void ScanReadAhead::SignalProgress(bool wake_all) { if (waiting_threads.load() == 0) { return; } + optional wake_one; + vector wake_many; { - // a waiter that saw the old epoch is blocked in the wait once the lock is free lock_guard guard(lock); + wake_all |= IsDone() && !HasActiveProducers() && active_jobs.load() == 0; + if (wake_all) { + wake_many.swap(parked_scans); + waiting_threads -= wake_many.size(); + } else if (!parked_scans.empty()) { + wake_one = std::move(parked_scans.back()); + parked_scans.pop_back(); + --waiting_threads; + } } WakeWaiters(wake_all); + if (wake_one) { + ResumeScan(*wake_one); + } + for (auto &interrupt_state : wake_many) { + ResumeScan(interrupt_state); + } +} + +void ScanReadAhead::ResumeScan(const InterruptState &interrupt_state) { + try { + interrupt_state.Callback(); + } catch (std::exception &ex) { + executor->PushTaskError(ex); + Executor::Get(context).PushTaskError(ex); + } catch (...) { + const auto message = "Unknown exception while resuming a scan"; + executor->PushTaskError(message); + Executor::Get(context).PushTaskError(message); + } } void ScanReadAhead::WaitForProgress(ClientContext &context, idx_t epoch) { - context.BlockingInterruptCheck(); + context.InterruptCheck(); { unique_lock guard(lock); ++waiting_threads; @@ -443,7 +765,7 @@ void ScanReadAhead::WaitForProgress(ClientContext &context, idx_t epoch) { progress.wait_for(guard, std::chrono::milliseconds(10), [&]() { return progress_epoch.load() != epoch; }); --waiting_threads; } - context.BlockingInterruptCheck(); + context.InterruptCheck(); } idx_t ScanReadAhead::ProgressEpoch() const { diff --git a/src/duckdb/src/parallel/sharded_counter.cpp b/src/duckdb/src/parallel/sharded_counter.cpp new file mode 100644 index 000000000..dc8bce186 --- /dev/null +++ b/src/duckdb/src/parallel/sharded_counter.cpp @@ -0,0 +1,26 @@ +#include "duckdb/parallel/sharded_counter.hpp" + +#include "duckdb/parallel/task_scheduler.hpp" + +namespace duckdb { + +void ShardedCounter::Add(idx_t count) { + const auto shard = (TaskScheduler::GetEstimatedCPUId() / CPUS_PER_SHARD) % SHARD_COUNT; + shards[shard].fetch_add(count, std::memory_order_relaxed); +} + +idx_t ShardedCounter::GetTotal() const { + idx_t total = 0; + for (const auto &shard : shards) { + total += shard.load(std::memory_order_relaxed); + } + return total; +} + +void ShardedCounter::Reset() { + for (auto &shard : shards) { + shard.store(0, std::memory_order_relaxed); + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/parallel/task_executor.cpp b/src/duckdb/src/parallel/task_executor.cpp index 152d7c527..a45d5724c 100644 --- a/src/duckdb/src/parallel/task_executor.cpp +++ b/src/duckdb/src/parallel/task_executor.cpp @@ -23,17 +23,26 @@ class TaskExecutorTask : public Task { return RunGuarded([&]() { task->Cancel(); }, "Unknown exception while cancelling a task"); } TaskExecutionResult result; + // A failed task-start notification must retire work before the guard publishes completion. + bool task_body_started = false; try { TaskNotifier task_notifier {executor.context}; + task_body_started = true; // PROCESS_ALL must run to completion, so loop the steps; PROCESS_PARTIAL does one and yields do { result = task->ExecuteTaskStep(); } while (result == TaskExecutionResult::TASK_NOT_FINISHED && mode == TaskExecutionMode::PROCESS_ALL); } catch (std::exception &ex) { executor.PushTaskError(ex); + if (!task_body_started) { + Retire(); + } return TaskExecutionResult::TASK_ERROR; } catch (...) { // LCOV_EXCL_START executor.PushTaskError("Unknown exception during task execution"); + if (!task_body_started) { + Retire(); + } return TaskExecutionResult::TASK_ERROR; } // LCOV_EXCL_STOP if (result == TaskExecutionResult::TASK_NOT_FINISHED) { @@ -57,12 +66,12 @@ class TaskExecutorTask : public Task { return task->TaskType(); } - //! Retire a task that never made it into the queue, without touching the executor's accounting + //! Retire outstanding work without touching the executor's accounting void Retire() noexcept { try { RunGuarded([&]() { task->Cancel(); }, "Unknown exception while cancelling a task"); } catch (...) { - // Preserve the submission exception if reporting a cancellation error fails. + // Preserve the original exception if reporting a cancellation error fails. } } diff --git a/src/duckdb/src/parallel/task_scheduler.cpp b/src/duckdb/src/parallel/task_scheduler.cpp index 358b9f826..d4c6a0712 100644 --- a/src/duckdb/src/parallel/task_scheduler.cpp +++ b/src/duckdb/src/parallel/task_scheduler.cpp @@ -5,6 +5,7 @@ #include "duckdb/main/client_context.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/settings.hpp" +#include "duckdb/main/user_settings.hpp" #include "duckdb/parallel/task_scheduler_pool.hpp" #include "duckdb/parallel/task_scheduler_queue.hpp" #include "duckdb/storage/block_allocator.hpp" @@ -207,11 +208,15 @@ void TaskScheduler::ExecuteForever(atomic *marker, const TaskSchedulerType const auto &block_allocator = BlockAllocator::Get(db); const auto &config = DBConfig::GetConfig(db); auto &pool = GetPool(pool_type); + // this thread allocates blocks and reads settings while the heap may be exhausted: its block cache and its + // settings cache live here, so neither creates a thread_local whose destructor registration glibc cannot fail to + // allocate without ending the process. Creating them allocates, so that happens in the retry loop below + BlockAllocatorWorkerState block_state; + WorkerSettingsCache settings_cache; // Only a thread that ran a task since its last flush has allocations to flush, both blocks and the jemalloc cache // of the allocator, so other threads skip the flush and leave the trim of the system heap to the threads that ran - // tasks. Reading the settings would be the first use of their thread_local cache in a thread that never ran one, - // and glibc ends the process when it cannot allocate the registration of a thread_local destructor + // tasks bool flush_pending = false; bool ran_task = false; @@ -223,6 +228,12 @@ void TaskScheduler::ExecuteForever(atomic *marker, const TaskSchedulerType // MAX_TASK_RETRIES times while (true) { try { + if (!block_state.IsInitialized()) { + block_state.Initialize(block_allocator); + } + if (!settings_cache.IsInitialized()) { + settings_cache.Initialize(); + } if (!consumer) { consumer = make_uniq(queues); } diff --git a/src/duckdb/src/parser/expression/type_expression.cpp b/src/duckdb/src/parser/expression/type_expression.cpp index 084812896..6bd7c33a2 100644 --- a/src/duckdb/src/parser/expression/type_expression.cpp +++ b/src/duckdb/src/parser/expression/type_expression.cpp @@ -238,6 +238,8 @@ const char *BuiltinTypeName(LogicalTypeId id) { return "VARIANT"; case LogicalTypeId::GEOMETRY: return "GEOMETRY"; + case LogicalTypeId::GEOGRAPHY: + return "GEOGRAPHY"; case LogicalTypeId::DECIMAL: return "DECIMAL"; case LogicalTypeId::ENUM: @@ -303,6 +305,7 @@ unique_ptr TypeExpression::FromLogicalType(const LogicalType &ty break; } case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: if (GeoType::HasCRS(type)) { children.push_back(LiteralChild(ConstantExpression::String(GeoType::GetCRS(type).GetDefinition()))); } diff --git a/src/duckdb/src/parser/expression/value_expression.cpp b/src/duckdb/src/parser/expression/value_expression.cpp index 49cb3a0d3..9ab1a5bca 100644 --- a/src/duckdb/src/parser/expression/value_expression.cpp +++ b/src/duckdb/src/parser/expression/value_expression.cpp @@ -153,14 +153,16 @@ static unique_ptr IntervalExpression(const interval_t &value) static unique_ptr GeometryExpression(const Value &value) { auto &type = value.type(); + const bool geography = type.id() == LogicalTypeId::GEOGRAPHY; unique_ptr result; if (value.IsNull()) { auto geometry = GeoType::HasCRS(type) ? Value("GEOMETRYCOLLECTION EMPTY") : Value(); - result = CastTo(LogicalType::GEOMETRY(), ConstantExpression::FromValue(geometry)); + result = CastTo(geography ? LogicalType::GEOGRAPHY() : LogicalType::GEOMETRY(), + ConstantExpression::FromValue(geometry)); } else { vector> arguments; arguments.push_back(ConstantExpression::FromValue(Value::BLOB_RAW(StringValue::Get(value)))); - result = ValueFunction("st_geomfromwkb", std::move(arguments)); + result = ValueFunction(geography ? "st_geogfromwkb" : "st_geomfromwkb", std::move(arguments)); } if (!GeoType::HasCRS(type)) { return result; @@ -201,14 +203,16 @@ static bool HasUnsupportedVariantKeys(const VariantNode &node) { bool ConstantExpression::RequiresTypeWitness(const LogicalType &type) { return TypeVisitor::Contains(type, [&](const LogicalType &child) { return child.IsAggregateState() || child.id() == LogicalTypeId::TYPE || - (child.id() == LogicalTypeId::GEOMETRY && GeoType::HasCRS(child)) || + ((child.id() == LogicalTypeId::GEOMETRY || child.id() == LogicalTypeId::GEOGRAPHY) && + GeoType::HasCRS(child)) || (type.id() != LogicalTypeId::VARCHAR && child.id() == LogicalTypeId::VARCHAR && !StringType::GetCollation(child).empty()); }); } static unique_ptr NestedValueExpression(const LogicalType &type, optional_ptr value) { - if (type.IsAggregateState() || type.id() == LogicalTypeId::GEOMETRY || type.id() == LogicalTypeId::TYPE || + if (type.IsAggregateState() || type.id() == LogicalTypeId::GEOMETRY || type.id() == LogicalTypeId::GEOGRAPHY || + type.id() == LogicalTypeId::TYPE || (type.id() != LogicalTypeId::TUPLE && TypeExpression::CanRepresent(type) && !ConstantExpression::RequiresTypeWitness(type))) { return ConstantExpression::FromValue(value ? value->WithType(type) : Value(type)); @@ -315,7 +319,7 @@ unique_ptr ConstantExpression::FromValue(const Value &value) { arguments.push_back(FromValue(Value(TypeValue::GetType(value)))); return ValueFunction("get_type", std::move(arguments)); } - if (type.id() == LogicalTypeId::GEOMETRY) { + if (type.id() == LogicalTypeId::GEOMETRY || type.id() == LogicalTypeId::GEOGRAPHY) { auto result = GeometryExpression(value); return type.HasAlias() ? CastTo(type, std::move(result)) : std::move(result); } diff --git a/src/duckdb/src/parser/parsed_data/create_collation_info.cpp b/src/duckdb/src/parser/parsed_data/create_collation_info.cpp deleted file mode 100644 index 8c7e3f94f..000000000 --- a/src/duckdb/src/parser/parsed_data/create_collation_info.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "duckdb/parser/parsed_data/create_collation_info.hpp" - -namespace duckdb { - -CreateCollationInfo::CreateCollationInfo(Identifier name_p, ScalarFunction function_p, bool combinable_p, - bool not_required_for_equality_p) - : CreateInfo(CatalogType::COLLATION_ENTRY), function(std::move(function_p)), combinable(combinable_p), - not_required_for_equality(not_required_for_equality_p) { - this->SetCollationName(std::move(name_p)); - internal = true; -} - -unique_ptr CreateCollationInfo::Copy() const { - auto result = make_uniq(GetCollationName(), function, combinable, not_required_for_equality); - CopyProperties(*result); - return std::move(result); -} - -} // namespace duckdb diff --git a/src/duckdb/src/parser/parser.cpp b/src/duckdb/src/parser/parser.cpp index 20a5afc49..8583c8733 100644 --- a/src/duckdb/src/parser/parser.cpp +++ b/src/duckdb/src/parser/parser.cpp @@ -3,7 +3,6 @@ #include "duckdb/parser/peg/keyword_helper/duckdb_keyword_helper.hpp" #include "duckdb/main/extension_callback_manager.hpp" -#include "duckdb/parser/group_by_node.hpp" #include "duckdb/parser/parsed_data/create_table_info.hpp" #include "duckdb/parser/parser_extension.hpp" #include "duckdb/parser/token_iterator.hpp" @@ -11,9 +10,6 @@ #include "duckdb/parser/statement/create_statement.hpp" #include "duckdb/parser/statement/extension_statement.hpp" #include "duckdb/parser/statement/select_statement.hpp" -#include "duckdb/parser/statement/update_statement.hpp" -#include "duckdb/parser/query_node/update_query_node.hpp" -#include "duckdb/parser/tableref/expressionlistref.hpp" #include "duckdb/parser/peg/matcher.hpp" #include "duckdb/parser/peg/parser_packrat.hpp" #include "duckdb/parser/peg/transformer/peg_transformer.hpp" @@ -756,22 +752,6 @@ unique_ptr Parser::ParseSingleExpression(const string &express return std::move(expressions[0]); } -GroupByNode Parser::ParseGroupByList(const string &group_by) { - // construct a mock SELECT query with our group_by expressions - string mock_query = StringUtil::Format("SELECT 42 GROUP BY %s", group_by); - // parse the query - Parser parser(options); - parser.ParseQuery(mock_query); - // check the result - if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::SELECT_STATEMENT) { - throw ParserException("Expected a single SELECT statement"); - } - auto &select = parser.statements[0]->Cast(); - D_ASSERT(select.node->type == QueryNodeType::SELECT_NODE); - auto &select_node = select.node->Cast(); - return std::move(select_node.groups); -} - vector Parser::ParseOrderList(const string &select_list) { // construct a mock query string mock_query = "SELECT * FROM tbl ORDER BY " + select_list; @@ -793,44 +773,6 @@ vector Parser::ParseOrderList(const string &select_list) { return std::move(order.orders); } -void Parser::ParseUpdateList(const string &update_list, vector &update_columns, - vector> &expressions) { - // construct a mock query - string mock_query = "UPDATE tbl SET " + update_list; - // parse the query - Parser parser(options); - parser.ParseQuery(mock_query); - // check the statements - if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::UPDATE_STATEMENT) { - throw ParserException("Expected a single UPDATE statement"); - } - auto &update = parser.statements[0]->Cast(); - update_columns = update.node->set_info->columns; - expressions = std::move(update.node->set_info->expressions); -} - -vector>> Parser::ParseValuesList(const string &value_list) { - // construct a mock query - string mock_query = "VALUES " + value_list; - // parse the query - Parser parser(options); - parser.ParseQuery(mock_query); - // check the statements - if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::SELECT_STATEMENT) { - throw ParserException("Expected a single SELECT statement"); - } - auto &select = parser.statements[0]->Cast(); - if (select.node->type != QueryNodeType::SELECT_NODE) { - throw ParserException("Expected a single SELECT node"); - } - auto &select_node = select.node->Cast(); - if (!select_node.from_table || select_node.from_table->type != TableReferenceType::EXPRESSION_LIST) { - throw ParserException("Expected a single VALUES statement"); - } - auto &values_list = select_node.from_table->Cast(); - return std::move(values_list.values); -} - ColumnList Parser::ParseColumnList(const string &column_list) { string mock_query = "CREATE TABLE tbl (" + column_list + ")"; Parser parser(options); diff --git a/src/duckdb/src/parser/peg/compiled_grammar.cpp b/src/duckdb/src/parser/peg/compiled_grammar.cpp index 65301052a..015cffc79 100644 --- a/src/duckdb/src/parser/peg/compiled_grammar.cpp +++ b/src/duckdb/src/parser/peg/compiled_grammar.cpp @@ -123,6 +123,7 @@ terminal_rule_overrides_t ParsedGrammar::BuildTerminalRuleOverrides(const PEGKey AddTerminalRuleOverride(overrides, "CopyOptionName", make_uniq(SuggestionState::SUGGEST_VARIABLE, keyword_helper)); AddTerminalRuleOverride(overrides, "NumberLiteral", make_uniq()); + AddTerminalRuleOverride(overrides, "DottedName", make_uniq()); AddTerminalRuleOverride(overrides, "StringLiteral", make_uniq()); AddTerminalRuleOverride(overrides, "OperatorLiteral", make_uniq()); AddTerminalRuleOverride(overrides, "AnyOperatorLiteral", diff --git a/src/duckdb/src/parser/peg/keyword_helper/grammar_literal_table.cpp b/src/duckdb/src/parser/peg/keyword_helper/grammar_literal_table.cpp index c22c12a12..95c1ccba9 100644 --- a/src/duckdb/src/parser/peg/keyword_helper/grammar_literal_table.cpp +++ b/src/duckdb/src/parser/peg/keyword_helper/grammar_literal_table.cpp @@ -33,6 +33,44 @@ GrammarLiteralTable::GrammarLiteralTable(const ParsedGrammar &grammar, for (auto &entry : keywords) { Register(entry.first, entry.second.CategoryFlags()); } + Index(); +} + +void GrammarLiteralTable::Index() { + texts.clear(); + infos.clear(); + idx_t slot_count = 16; + while (slot_count < literals.size() * 2) { + slot_count *= 2; + } + slots.assign(slot_count, Slot()); + slot_mask = static_cast(slot_count - 1); + for (auto &entry : literals) { + texts.push_back(entry.first); + infos.push_back(entry.second); + auto hash = static_cast(StringUtil::CIHash(entry.first)); + auto index = hash & slot_mask; + while (slots[index].entry) { + index = (index + 1) & slot_mask; + } + slots[index].hash = hash; + slots[index].entry = static_cast(texts.size()); + } + for (auto &entry : literals) { + auto &text = entry.first; + auto first = static_cast(text[0]); + first_bytes[first] = true; + first_bytes[static_cast(StringUtil::CharacterToLower(static_cast(first)))] = true; + first_bytes[static_cast(StringUtil::CharacterToUpper(static_cast(first)))] = true; + if (text.size() > 1) { + prefix_lengths[PrefixIndex(text[0], text[1])] |= 1U << LengthBit(text.size()); + } + if (text.size() == 1) { + single_byte[first] = entry.second; + single_byte[static_cast(StringUtil::CharacterToLower(static_cast(first)))] = entry.second; + single_byte[static_cast(StringUtil::CharacterToUpper(static_cast(first)))] = entry.second; + } + } } void GrammarLiteralTable::Register(const string &text, keyword_categories_t categories) { diff --git a/src/duckdb/src/parser/peg/matcher.cpp b/src/duckdb/src/parser/peg/matcher.cpp index 9d49dc224..19f6f5615 100644 --- a/src/duckdb/src/parser/peg/matcher.cpp +++ b/src/duckdb/src/parser/peg/matcher.cpp @@ -80,6 +80,11 @@ void Matcher::Print() const { Printer::Print(ToString()); } +void ParseResult::ThrowCastError(ParseResultType target) const { + throw InternalException("Failed to cast parse result of type %s to type %s for rule %s", + ParseResultToString(target), ParseResultToString(type), Name()); +} + void MatchState::AddSuggestion(MatcherSuggestion suggestion) { suggestion.label = context.active_label; context.suggestions.push_back(std::move(suggestion)); @@ -123,8 +128,8 @@ static bool CanGroupList(const ListMatcher &list) { } static bool SameFirstPredicate(const MatcherFirstSet &left, const MatcherFirstSet &right) { - return left.computed && right.computed && left.any == right.any && left.nullable == right.nullable && - left.class_mask == right.class_mask && left.table == right.table && left.literals == right.literals; + return left.computed && right.computed && left.nullable == right.nullable && left.table == right.table && + left.Equals(right); } void MatcherAllocator::InitializeListChains() { @@ -199,6 +204,8 @@ void MatcherAllocator::InitializeListChains() { } } } + chain->tail_first_set.Finalize(); + chain->prefix_first_set.Finalize(); // Publish the owner before installing borrowed pointers: vector growth can throw. auto chain_ptr = chain.get(); list_chains.push_back(std::move(chain)); @@ -210,7 +217,8 @@ void MatcherAllocator::InitializeListChains() { } } -ParseResultAllocator::ParseResultAllocator() : arena(Allocator::DefaultAllocator()), pending_destructors(arena) { +ParseResultAllocator::ParseResultAllocator() + : arena(Allocator::DefaultAllocator(), PARSER_ARENA_INITIAL_CAPACITY), pending_destructors(arena) { } ParseResultAllocator::~ParseResultAllocator() = default; diff --git a/src/duckdb/src/parser/peg/matcher_factory.cpp b/src/duckdb/src/parser/peg/matcher_factory.cpp index eba2aa15c..6e691a813 100644 --- a/src/duckdb/src/parser/peg/matcher_factory.cpp +++ b/src/duckdb/src/parser/peg/matcher_factory.cpp @@ -236,6 +236,7 @@ Matcher &MatcherFactory::CreateRootMatcher(const string &root_rule) { AddPackratMemoizedRule("CatalogQualification"); AddPackratMemoizedRule("SchemaQualification"); AddPackratMemoizedRule("ReservedSchemaQualification"); + AddPackratMemoizedRule("SelectParens"); //===--------------------------------------------------------------------===// // END GENERATED PACKRAT MEMOIZED RULES //===--------------------------------------------------------------------===// @@ -308,14 +309,14 @@ unique_ptr MatcherFactory::CreateKeyword(const string &keyword, } template -static unique_ptr MakeStructural(ARGS &&... args) { +static unique_ptr MakeStructural(ARGS &&...args) { auto result = make_uniq(std::forward(args)...); result->SetStructural(); return result; } template -static unique_ptr MakeChoice(ARGS &&... args) { +static unique_ptr MakeChoice(ARGS &&...args) { auto result = MakeStructural(std::forward(args)...); // This helper creates only the built-in selectors below, not factory overrides. result->SetSelectionStatePreserving(); diff --git a/src/duckdb/src/parser/peg/matcher_first_set.cpp b/src/duckdb/src/parser/peg/matcher_first_set.cpp index e11efc38b..42a2c7c53 100644 --- a/src/duckdb/src/parser/peg/matcher_first_set.cpp +++ b/src/duckdb/src/parser/peg/matcher_first_set.cpp @@ -7,7 +7,7 @@ namespace duckdb { //===--------------------------------------------------------------------===// // FIRST sets //===--------------------------------------------------------------------===// -bool MatcherFirstSet::Merge(const MatcherFirstSet &other) { +bool MatcherTokenSet::MergeTokens(const MatcherTokenSet &other) { bool changed = false; if (other.any && !any) { any = changed = true; @@ -29,7 +29,7 @@ bool MatcherFirstSet::Merge(const MatcherFirstSet &other) { return changed; } -void MatcherFirstSet::AddLiteral(idx_t literal_id) { +void MatcherTokenSet::AddLiteral(idx_t literal_id) { auto word = literal_id / 64; if (word >= literals.size()) { literals.resize(word + 1, 0); @@ -37,6 +37,83 @@ void MatcherFirstSet::AddLiteral(idx_t literal_id) { literals[word] |= uint64_t(1) << (literal_id % 64); } +bool MatcherTokenSet::IsEmpty() const { + if (any || class_mask) { + return false; + } + for (auto word : literals) { + if (word) { + return false; + } + } + return true; +} + +bool MatcherTokenSet::Equals(const MatcherTokenSet &other) const { + if (any != other.any || class_mask != other.class_mask) { + return false; + } + auto words = MaxValue(literals.size(), other.literals.size()); + for (idx_t i = 0; i < words; i++) { + auto left = i < literals.size() ? literals[i] : 0; + auto right = i < other.literals.size() ? other.literals[i] : 0; + if (left != right) { + return false; + } + } + return true; +} + +void MatcherFirstSet::Finalize() { + computed = true; + if (one.any || second.any) { + first_suffices = true; + return; + } + // ONE covers FIRST: a token that passes the FIRST check can always be a one-token match + if ((one.class_mask & class_mask) != class_mask) { + first_suffices = false; + return; + } + for (idx_t i = 0; i < literals.size(); i++) { + auto one_word = i < one.literals.size() ? one.literals[i] : 0; + if ((one_word & literals[i]) != literals[i]) { + first_suffices = false; + return; + } + } + first_suffices = true; +} + +bool MatcherFirstSet::MightMatchSecond(MatchState &state) const { + auto &iterator = state.token_iterator; + auto token = iterator.Current(); + D_ASSERT(token); + if (one.Contains(*token, [&]() { return iterator.CurrentLiteralInfo(*table); })) { + return true; + } + auto next = iterator.Peek(1); + // the autocomplete cursor can stand for any token + if (next && next->type == TokenType::END_OF_INPUT_AUTOCOMPLETE) { + return true; + } + if (next && second.Contains(*next, [&]() { return iterator.PeekLiteralInfo(*table, 1); })) { + return true; + } + // the matcher would have consumed the current token before failing: keep the error position + if (iterator.Position() + 1 > state.context.max_token_index) { + state.context.max_token_index = iterator.Position() + 1; + } + return false; +} + +bool MatcherFirstSet::Merge(const MatcherFirstSet &other) { + bool changed = MergeTokens(other); + changed |= one.MergeTokens(other.one); + changed |= second.MergeTokens(other.second); + return changed; +} + //! Calls fun(child) for every child of a built-in composite matcher template static void ForEachChild(Matcher &matcher, FUN &&fun) { @@ -72,24 +149,42 @@ static bool IsComposite(const Matcher &matcher) { type == MatcherType::REPEAT; } -//! Recomputes the FIRST set of a composite matcher from its children, returns whether anything changed +//! Recomputes the lookahead sets of a composite matcher from its children, returns whether anything changed. +//! ONE holds the first tokens of one-token matches and SECOND the second tokens of longer matches. static bool UpdateFirstSet(Matcher &matcher) { auto &first = matcher.first_set; bool changed = false; bool nullable; switch (matcher.Type()) { - case MatcherType::LIST: + case MatcherType::LIST: { + auto &children = matcher.Cast().matchers; // the first non-nullable element ends the FIRST set of a sequence nullable = true; - for (auto &child : matcher.Cast().matchers) { - auto &child_first = child.get().first_set; - changed |= first.Merge(child_first); - if (!child_first.nullable) { - nullable = false; - break; + for (idx_t i = 0; i < children.size() && nullable; i++) { + auto &child_first = children[i].get().first_set; + changed |= first.MergeTokens(child_first); + // the element can be followed by the FIRST set of the rest of the sequence + MatcherTokenSet suffix_first; + bool suffix_nullable = true; + for (idx_t j = i + 1; j < children.size(); j++) { + auto &suffix_child = children[j].get().first_set; + suffix_first.MergeTokens(suffix_child); + if (!suffix_child.nullable) { + suffix_nullable = false; + break; + } } + if (suffix_nullable) { + changed |= first.one.MergeTokens(child_first.one); + } + changed |= first.second.MergeTokens(child_first.second); + if (!child_first.one.IsEmpty()) { + changed |= first.second.MergeTokens(suffix_first); + } + nullable = child_first.nullable; } break; + } case MatcherType::CHOICE: nullable = false; for (auto &child : matcher.Cast().matchers) { @@ -105,6 +200,10 @@ static bool UpdateFirstSet(Matcher &matcher) { case MatcherType::REPEAT: { auto &child_first = matcher.Cast().GetChildMatcher().first_set; changed |= first.Merge(child_first); + // a one-token element can be followed by the next repetition + if (!child_first.one.IsEmpty()) { + changed |= first.second.MergeTokens(child_first); + } nullable = child_first.nullable; break; } @@ -158,10 +257,13 @@ void ComputeFirstSets(Matcher &root, const GrammarLiteralTable &table) { if (IsComposite(matcher)) { composites.push_back(matcher); } else if (matcher.IsAtomic()) { + // matchers that only describe FIRST may consume any number of tokens + first.one.any = true; + first.second.any = true; static_cast(matcher).InitializeFirstSet(first, table); } else { // custom and derived matchers: no information - first.any = true; + first.SetAny(); } } // composite matchers: least fixed point, the grammar is recursive @@ -174,23 +276,8 @@ void ComputeFirstSets(Matcher &root, const GrammarLiteralTable &table) { } } for (auto &entry : matchers) { - entry.get().first_set.computed = true; - } -} - -bool MatcherFirstSet::MightMatch(MatchState &state) const { - if (!computed || any || nullable) { - return true; - } - auto token = state.token_iterator.Current(); - if (!token) { - return false; - } - if (token->token_class & class_mask) { - return true; + entry.get().first_set.Finalize(); } - auto literal_id = state.token_iterator.CurrentLiteralInfo(*table).LiteralId(); - return literal_id && HasLiteral(literal_id); } } // namespace duckdb diff --git a/src/duckdb/src/parser/peg/matcher_stack.cpp b/src/duckdb/src/parser/peg/matcher_stack.cpp index fe246ff16..7d10fc9fc 100644 --- a/src/duckdb/src/parser/peg/matcher_stack.cpp +++ b/src/duckdb/src/parser/peg/matcher_stack.cpp @@ -454,6 +454,9 @@ class ListMatchFrame final : public MatchStackFrame { if (!SuppressSuggestions(matcher.get())) { return; } + if (list_state.context.suggestions.size() <= saved_suggestion_size) { + return; + } list_state.context.suggestions.erase(list_state.context.suggestions.begin() + NumericCast(saved_suggestion_size), list_state.context.suggestions.end()); diff --git a/src/duckdb/src/parser/peg/peg_rule_id.cpp b/src/duckdb/src/parser/peg/peg_rule_id.cpp index 7707a8543..84dc99b9c 100644 --- a/src/duckdb/src/parser/peg/peg_rule_id.cpp +++ b/src/duckdb/src/parser/peg/peg_rule_id.cpp @@ -437,6 +437,7 @@ static const char *const PEG_RULE_NAMES[] = { "DescribeStatement", "ShowExternalResources", "ShowExternalResourcesType", + "ShowExternalResourceTypes", "ShowDeprecatedSelect", "DescribeSelect", "ShowAllTables", @@ -809,6 +810,9 @@ static const char *const PEG_RULE_NAMES[] = { "RegisterExternalResourceStmt", "DestroyExternalResourceStmt", "ExternalResourceKeyword", + "ExternalResourceType", + "ExternalResourceTypeName", + "BareName", "ExternalResourceCreationOptions", "AttachToExternalResource", "ConnectToExternalResource", @@ -858,7 +862,7 @@ static const char *const PEG_RULE_NAMES[] = { "CreateExtensionRepositoryFromHostStmt", "DropExtensionRepositoryStmt", "ExtensionRepositoryName", - "ExtensionRepositoryHostName", + "DottedName", "TableMatchRecognizeClause", "MatchRecognizeBody", "MatchRecognizeClause", diff --git a/src/duckdb/src/parser/peg/tokenizer/base_tokenizer.cpp b/src/duckdb/src/parser/peg/tokenizer/base_tokenizer.cpp index b867d290f..4c501814f 100644 --- a/src/duckdb/src/parser/peg/tokenizer/base_tokenizer.cpp +++ b/src/duckdb/src/parser/peg/tokenizer/base_tokenizer.cpp @@ -1,6 +1,7 @@ #include "duckdb/common/string_util.hpp" #include "duckdb/parser/peg/tokenizer/tokenizer.hpp" #include "duckdb/parser/peg/keyword_helper.hpp" +#include "duckdb/parser/peg/matcher/number_literal_matcher.hpp" #include "duckdb/parser/peg/matcher/operator_matcher.hpp" namespace duckdb { @@ -8,13 +9,15 @@ namespace duckdb { uint8_t ComputeMatcherTokenClass(TokenType type, const string &text) { switch (type) { case TokenType::KEYWORD: - case TokenType::IDENTIFIER: return MatcherTokenClass::WORD; + case TokenType::IDENTIFIER: + return MatcherTokenClass::WORD | MatcherTokenClass::IDENTIFIER; case TokenType::STRING_LITERAL: // string literals are also accepted in identifier positions (e.g. table and file names) return MatcherTokenClass::STRING | MatcherTokenClass::WORD; case TokenType::NUMBER_LITERAL: - return MatcherTokenClass::NUMBER; + // malformed literals such as 1.2.3 match nothing + return NumberLiteralMatcher::IsNumberLiteral(text) ? MatcherTokenClass::NUMBER : 0; case TokenType::OPERATOR: if (!text.empty() && !Tokenizer::CharacterIsOperator(text[0])) { return 0; @@ -29,6 +32,11 @@ uint8_t ComputeMatcherTokenClass(TokenType type, const string &text) { } } +void MatcherToken::RefreshLiteralInfo(const GrammarLiteralTable &table) { + literal_info = table.Lookup(text); + literal_table_id = table.CacheId(); +} + TokenizerBehavior::TokenizerBehavior(const string &sql) : sql(sql) { } @@ -140,8 +148,8 @@ bool Tokenizer::CharacterIsControlFlow(char c) { } } -bool Tokenizer::CharacterIsKeyword(char c) { - if (IsSingleByteOperator(c)) { +static bool CharacterIsKeywordSlow(char c) { + if (Tokenizer::IsSingleByteOperator(c)) { return false; } if (StringUtil::CharacterIsOperator(c)) { @@ -150,12 +158,35 @@ bool Tokenizer::CharacterIsKeyword(char c) { if (StringUtil::CharacterIsSpace(c)) { return false; } - if (CharacterIsControlFlow(c)) { + if (Tokenizer::CharacterIsControlFlow(c)) { return false; } return true; } +//! Byte classification table for the hot word scan +struct TokenizerCharacterTable { + TokenizerCharacterTable() { + for (idx_t i = 0; i < 256; i++) { + auto c = static_cast(i); + is_keyword[i] = CharacterIsKeywordSlow(c); + // '$' is valid as a non-initial identifier character in PostgreSQL + is_word[i] = is_keyword[i] || c == '$'; + } + } + bool is_keyword[256]; + bool is_word[256]; +}; + +static const TokenizerCharacterTable &CharacterTable() { + static const TokenizerCharacterTable table; + return table; +} + +bool Tokenizer::CharacterIsKeyword(char c) { + return CharacterTable().is_keyword[static_cast(c)]; +} + bool Tokenizer::CharacterIsOperator(char c) { switch (c) { case '+': @@ -214,21 +245,16 @@ void TokenizerBehavior::PushToken(idx_t start, idx_t end, TokenType type, bool u if (start >= end) { return; } - string last_token = sql.substr(start, end - start); - tokens.emplace_back(std::move(last_token), start, type, unterminated); - if (tokens.size() < 2) { - return; - } - auto &previous_token = tokens[tokens.size() - 2]; - auto previous_token_end = previous_token.offset + previous_token.length; - if (has_block_comment && last_block_comment_position >= previous_token_end && last_block_comment_position < start) { - tokens.back().preceded_by_block_comment = true; - } - for (idx_t pos = previous_token_end; pos < start; pos++) { - if (StringUtil::CharacterIsNewline(sql[pos])) { - tokens.back().preceded_by_newline = true; - break; - } + EmplaceToken(start, end, type, unterminated); +} + +void TokenizerBehavior::PushWordToken(idx_t start, idx_t end, TokenType type, const GrammarLiteralTable &table, + LiteralInfo info) { + // PushToken is the behavior's own and may decline the token + auto count = tokens.size(); + PushToken(start, end, type); + if (tokens.size() > count) { + tokens.back().SetLiteralInfo(table, info); } } @@ -268,16 +294,24 @@ bool Tokenizer::IsUnterminatedState(TokenizeState state) { bool Tokenizer::TokenizeInput(TokenizerBehavior &behavior) const { auto &sql = behavior.sql; auto &tokens = behavior.tokens; + auto first_token = tokens.size(); + bool autocomplete = false; if (TokenizeInputInternal(behavior)) { auto terminator = behavior.GetTerminator(); tokens.emplace_back("", sql.size(), terminator); - if (terminator == TokenType::END_OF_INPUT_AUTOCOMPLETE) { - return true; - } + autocomplete = terminator == TokenType::END_OF_INPUT_AUTOCOMPLETE; } else { tokens.emplace_back("", sql.size(), TokenType::END_OF_INPUT); } - return false; + // look every token up once here instead of lazily inside the matcher loop + auto &table = keyword_helper.GetLiteralTable(); + for (idx_t i = first_token; i < tokens.size(); i++) { + auto &token = tokens[i]; + if (!token.HasLiteralInfo(table)) { + token.SetLiteralInfo(table, table.Lookup(token.text)); + } + } + return autocomplete; } void Tokenizer::PushOperatorToken(TokenizerBehavior &behavior, idx_t start, idx_t end) const { @@ -308,6 +342,13 @@ void Tokenizer::PushOperatorToken(TokenizerBehavior &behavior, idx_t start, idx_ } } +//! Classify a word once: its literal info decides between keyword and identifier and is kept on the token +void Tokenizer::PushWordToken(TokenizerBehavior &behavior, idx_t start, idx_t end) const { + auto &table = keyword_helper.GetLiteralTable(); + auto info = table.Lookup(behavior.sql.data() + start, end - start); + behavior.PushWordToken(start, end, info.IsKeyword() ? TokenType::KEYWORD : TokenType::IDENTIFIER, table, info); +} + //! Skip an ordinary run, leaving its first special byte (or the final input byte) to the state machine. static idx_t SkipTokenizerBytes(const string &sql, idx_t pos, char first, char second) { D_ASSERT(pos < sql.size()); @@ -335,6 +376,73 @@ static idx_t SkipTokenizerBytes(const string &sql, idx_t pos, char first, char s return pos; } +void Tokenizer::TokenizeWord(TokenizerBehavior &behavior, const bool *is_word, idx_t &i, idx_t &last_pos, + TokenizeState &state) const { + auto &sql = behavior.sql; + // scan the whole word at once; PushWordToken classifies it as a keyword or an identifier + idx_t end = i + 1; + while (end < sql.size() && is_word[static_cast(sql[end])]) { + end++; + } + if (end == sql.size()) { + state = TokenizeState::KEYWORD; + last_pos = i; + i = end - 1; + return; + } + PushWordToken(behavior, i, end); + last_pos = end; + i = end - 1; +} + +const Tokenizer::ByteTables &Tokenizer::GetByteTables() const { + byte_tables_once.Call([&]() { + for (idx_t byte = 0; byte < 256; byte++) { + auto c = static_cast(byte); + StandardByteClass byte_class; + if (c == '\'') { + byte_class = StandardByteClass::STRING_QUOTE; + } else if (IsQuotedIdentifierDelimiter(c)) { + byte_class = StandardByteClass::QUOTED_IDENTIFIER; + } else if (c == ';') { + byte_class = StandardByteClass::SEMICOLON; + } else if (c == '$') { + byte_class = StandardByteClass::DOLLAR; + } else if (c == '-') { + byte_class = StandardByteClass::MINUS; + } else if (c == '/') { + byte_class = StandardByteClass::SLASH; + } else if (StringUtil::CharacterIsSpace(c)) { + byte_class = StandardByteClass::SPACE; + } else if (c == ':') { + byte_class = StandardByteClass::COLON; + } else if (IsSingleByteOperator(c)) { + byte_class = StandardByteClass::SINGLE_BYTE_OPERATOR; + } else if (CharacterIsInitialNumber(c)) { + byte_class = StandardByteClass::NUMBER; + } else if (CharacterIsSpecialStringCharacter(c)) { + byte_class = StandardByteClass::SPECIAL_STRING_PREFIX; + } else if (StringUtil::CharacterIsOperator(c)) { + byte_class = StandardByteClass::OPERATOR; + } else { + byte_class = StandardByteClass::WORD; + } + byte_tables.standard_classes[byte] = byte_class; + byte_tables.operator_token_classes[byte] = ComputeMatcherTokenClass(TokenType::OPERATOR, string(1, c)); + } + }); + return byte_tables; +} + +void Tokenizer::PushSingleByteOperator(TokenizerBehavior &behavior, const ByteTables &byte_tables, + const GrammarLiteralTable &table, idx_t byte_position, idx_t offset) const { + auto data = behavior.sql.data() + byte_position; + behavior.tokens.emplace_back( + data, 1, offset, TokenType::OPERATOR, + PrecomputedTokenClass(byte_tables.operator_token_classes[static_cast(*data)])); + behavior.tokens.back().SetLiteralInfo(table, table.Lookup(data, 1)); +} + bool Tokenizer::TokenizeInputInternal(TokenizerBehavior &behavior) const { auto &sql = behavior.sql; auto &tokens = behavior.tokens; @@ -345,29 +453,31 @@ bool Tokenizer::TokenizeInputInternal(TokenizerBehavior &behavior) const { string dollar_quote_marker; idx_t dollar_marker_start = 0; idx_t multi_line_comment_depth = 0; + auto &byte_tables = GetByteTables(); + auto &classes = byte_tables.standard_classes; + const bool *is_word = CharacterTable().is_word; + auto &table = keyword_helper.GetLiteralTable(); for (idx_t i = 0; i < sql.size(); i++) { auto c = sql[i]; switch (state) { case TokenizeState::STANDARD: - if (c == '\'') { + switch (classes[static_cast(c)]) { + case StandardByteClass::STRING_QUOTE: state = TokenizeState::STRING_LITERAL; last_pos = i; escape_string = false; break; - } - if (IsQuotedIdentifierDelimiter(c)) { + case StandardByteClass::QUOTED_IDENTIFIER: state = TokenizeState::QUOTED_IDENTIFIER; quoted_identifier_delimiter = c; last_pos = i; break; - } - if (c == ';') { + case StandardByteClass::SEMICOLON: // end of statement behavior.OnStatementEnd(i); last_pos = i + 1; break; - } - if (c == '$') { + case StandardByteClass::DOLLAR: { // Dollar-quoted string statement if (i + 1 >= sql.size()) { // We need more than a single dollar @@ -406,55 +516,68 @@ bool Tokenizer::TokenizeInputInternal(TokenizerBehavior &behavior) const { } break; } - if (c == '-' && i + 1 < sql.size() && sql[i + 1] == '-') { - i++; - state = TokenizeState::SINGLE_LINE_COMMENT; + case StandardByteClass::MINUS: + if (i + 1 < sql.size() && sql[i + 1] == '-') { + i++; + state = TokenizeState::SINGLE_LINE_COMMENT; + break; + } + state = TokenizeState::OPERATOR; + last_pos = i; break; - } - if (c == '/' && i + 1 < sql.size() && sql[i + 1] == '*') { - i++; - state = TokenizeState::MULTI_LINE_COMMENT; - multi_line_comment_depth = 1; + case StandardByteClass::SLASH: + if (i + 1 < sql.size() && sql[i + 1] == '*') { + i++; + state = TokenizeState::MULTI_LINE_COMMENT; + multi_line_comment_depth = 1; + break; + } + state = TokenizeState::OPERATOR; + last_pos = i; break; - } - if (StringUtil::CharacterIsSpace(c)) { - // space character - skip + case StandardByteClass::SPACE: + // skip the whole run of space characters + while (i + 1 < sql.size() && classes[static_cast(sql[i + 1])] == StandardByteClass::SPACE) { + i++; + } last_pos = i + 1; break; - } - idx_t token_length; - if (IsCompoundColonToken(sql, i, token_length)) { - if (i + token_length < sql.size() && CharacterIsOperator(sql[i + token_length])) { - state = TokenizeState::OPERATOR; - last_pos = i; + case StandardByteClass::COLON: { + idx_t token_length; + if (IsCompoundColonToken(sql, i, token_length)) { + if (i + token_length < sql.size() && CharacterIsOperator(sql[i + token_length])) { + state = TokenizeState::OPERATOR; + last_pos = i; + break; + } + // Push the compound colon token + tokens.emplace_back(sql.substr(i, token_length), last_pos, TokenType::OPERATOR); + i += token_length - 1; + last_pos = i + 1; break; } - // Push the compound colon token - tokens.emplace_back(sql.substr(i, token_length), last_pos, TokenType::OPERATOR); - i += token_length - 1; + PushSingleByteOperator(behavior, byte_tables, table, i, last_pos); last_pos = i + 1; break; } - if (IsSingleByteOperator(c)) { + case StandardByteClass::SINGLE_BYTE_OPERATOR: // single-byte operator - directly push the token - tokens.emplace_back(string(1, c), last_pos, TokenType::OPERATOR); + PushSingleByteOperator(behavior, byte_tables, table, i, last_pos); last_pos = i + 1; break; - } - // '.' starts a number only as a leading decimal (.5); otherwise it is the qualifier (t.a, t.*) - if (CharacterIsInitialNumber(c) && - (c != '.' || (i + 1 < sql.size() && StringUtil::CharacterIsDigit(sql[i + 1])))) { + case StandardByteClass::NUMBER: + // '.' starts a number only as a leading decimal (.5); otherwise it is the qualifier (t.a, t.*) + if (c == '.' && (i + 1 >= sql.size() || !StringUtil::CharacterIsDigit(sql[i + 1]))) { + // emit '.' as its own token, tokenize what follows independently + tokens.emplace_back(string(1, c), last_pos, TokenType::OPERATOR); + last_pos = i + 1; + break; + } + // parse a numeric literal state = TokenizeState::NUMERIC; last_pos = i; break; - } - if (c == '.') { - // emit '.' as it's own token, tokenize what follows independently - tokens.emplace_back(string(1, c), last_pos, TokenType::OPERATOR); - last_pos = i + 1; - break; - } - if (CharacterIsSpecialStringCharacter(c)) { + case StandardByteClass::SPECIAL_STRING_PREFIX: // Look ahead to see if a quote follows if (i + 1 < sql.size() && sql[i + 1] == '\'') { state = TokenizeState::STRING_LITERAL; @@ -465,14 +588,16 @@ bool Tokenizer::TokenizeInputInternal(TokenizerBehavior &behavior) const { i++; break; } - } - if (StringUtil::CharacterIsOperator(c)) { + TokenizeWord(behavior, is_word, i, last_pos, state); + break; + case StandardByteClass::OPERATOR: state = TokenizeState::OPERATOR; last_pos = i; break; + case StandardByteClass::WORD: + TokenizeWord(behavior, is_word, i, last_pos, state); + break; } - state = TokenizeState::KEYWORD; - last_pos = i; break; case TokenizeState::NUMERIC: // Check for "always allowed" numeric characters @@ -547,9 +672,7 @@ bool Tokenizer::TokenizeInputInternal(TokenizerBehavior &behavior) const { // '$' is valid as a non-initial identifier character in PostgreSQL if (c != '$' && !CharacterIsKeyword(c)) { // not a keyword - return to standard state - auto word = sql.substr(last_pos, i - last_pos); - auto token_type = keyword_helper.IsKeyword(word) ? TokenType::KEYWORD : TokenType::IDENTIFIER; - behavior.PushToken(last_pos, i, token_type); + PushWordToken(behavior, last_pos, i); state = TokenizeState::STANDARD; last_pos = i; i--; diff --git a/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp b/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp index 5904c5e78..9e6f002ee 100644 --- a/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp +++ b/src/duckdb/src/parser/peg/tokenizer/parser_tokenizer.cpp @@ -25,6 +25,13 @@ void ParserTokenizerBehavior::PushToken(idx_t start, idx_t end, TokenType type, TokenizerBehavior::PushToken(start, end, type, unterminated); } +void ParserTokenizerBehavior::PushWordToken(idx_t start, idx_t end, TokenType type, const GrammarLiteralTable &table, + LiteralInfo info) { + // a word is neither a comment nor a quoted identifier, so none of the PushToken checks apply + D_ASSERT(start < end && (type == TokenType::KEYWORD || type == TokenType::IDENTIFIER)); + EmplaceToken(start, end, type).SetLiteralInfo(table, info); +} + void ParserTokenizerBehavior::OnStatementEnd(idx_t pos) { // Always emit ';' as a TERMINATOR token so the grammar can consume it. // Statement boundaries are determined by the PEG grammar (Program rule), not the tokenizer. 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 214fb8cc4..83cb3a979 100644 --- a/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp +++ b/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp @@ -59,8 +59,8 @@ unique_ptr PEGTransformerFactory::TransformTopLevelStatement(Token ParseResultAllocator parse_result_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()); - ArenaAllocator packrat_allocator(Allocator::DefaultAllocator()); + 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); @@ -95,7 +95,7 @@ unique_ptr PEGTransformerFactory::TransformTopLevelStatement(Token } } - ArenaAllocator transformer_allocator(Allocator::DefaultAllocator()); + ArenaAllocator transformer_allocator(Allocator::DefaultAllocator(), PARSER_ARENA_INITIAL_CAPACITY); PEGTransformer transformer(transformer_allocator, token_iterator, options, grammar); return ExtractAndTransformStatement(transformer, token_iterator, stmt_opt.GetResult(), terminator_offset); diff --git a/src/duckdb/src/parser/peg/transformer/transform_external_resource.cpp b/src/duckdb/src/parser/peg/transformer/transform_external_resource.cpp index 002528b69..9fd081c84 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_external_resource.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_external_resource.cpp @@ -17,11 +17,19 @@ static void ApplyOptions(const optional> &options, Ext PEGTransformerFactory::CollectGenericOptions(*options, stmt.options, "EXTERNAL RESOURCE"); } +//! A resource type spelled without quotes, as a dotted name (aws.s3tables.bucket) or a plain word, is folded to +//! lowercase: types are registered in lowercase and looked up by their exact name. A type in single quotes is taken as +//! written, for one with other characters in it ('aws:cloudformation:quack-on-ec2', 'quack@local') or in another case. +string PEGTransformerFactory::TransformExternalResourceTypeName(PEGTransformer &transformer, + const Identifier &bare_name) { + return StringUtil::Lower(bare_name.GetIdentifierName()); +} + unique_ptr PEGTransformerFactory::TransformCreateExternalResourceStmt( - PEGTransformer &transformer, const string &string_literal, const optional &attach_alias, + PEGTransformer &transformer, const string &external_resource_type, const optional &attach_alias, const optional> &external_resource_creation_options) { auto result = make_uniq(ExternalResourceOperation::CREATE); - result->type = string_literal; + result->type = external_resource_type; if (attach_alias) { result->name = Identifier(*attach_alias); } @@ -29,12 +37,11 @@ unique_ptr PEGTransformerFactory::TransformCreateExternalResourceS return std::move(result); } -unique_ptr -PEGTransformerFactory::TransformRegisterExternalResourceStmt(PEGTransformer &transformer, const string &string_literal, - const optional &attach_alias, - unique_ptr expression) { +unique_ptr PEGTransformerFactory::TransformRegisterExternalResourceStmt( + PEGTransformer &transformer, const string &external_resource_type, const optional &attach_alias, + unique_ptr expression) { auto result = make_uniq(ExternalResourceOperation::REGISTER); - result->type = string_literal; + result->type = external_resource_type; if (attach_alias) { result->name = Identifier(*attach_alias); } @@ -62,13 +69,13 @@ static void AddNamedArgument(vector &children, const string &n unique_ptr PEGTransformerFactory::TransformShowExternalResources(PEGTransformer &transformer, const ShowType &show_rule, const bool &has_result, - optional show_external_resources_type) { + optional show_external_resources_type) { vector children; if (has_result) { AddNamedArgument(children, "discover", ConstantExpression::Boolean(true)); } if (show_external_resources_type) { - auto type = ConstantExpression::String(show_external_resources_type->GetIdentifierName()); + auto type = ConstantExpression::String(*show_external_resources_type); AddNamedArgument(children, "type", std::move(type)); } auto table_function = make_uniq(); @@ -80,4 +87,17 @@ PEGTransformerFactory::TransformShowExternalResources(PEGTransformer &transforme return std::move(select_node); } +// SHOW EXTERNAL RESOURCE TYPES -> SELECT * FROM duckdb_external_resource_types() +unique_ptr PEGTransformerFactory::TransformShowExternalResourceTypes(PEGTransformer &transformer, + const ShowType &show_rule) { + auto table_function = make_uniq(); + table_function->function = + make_uniq("duckdb_external_resource_types", vector()); + + auto select_node = make_uniq(); + select_node->select_list.push_back(make_uniq()); + select_node->from_table = std::move(table_function); + return std::move(select_node); +} + } // namespace duckdb diff --git a/src/duckdb/src/parser/peg/transformer/transform_external_resource_source.cpp b/src/duckdb/src/parser/peg/transformer/transform_external_resource_source.cpp index a42b643a9..b264ab50c 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_external_resource_source.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_external_resource_source.cpp @@ -10,12 +10,12 @@ namespace duckdb { // Both statements produce a normal ATTACH/CONNECT carrying an ExternalResourceOptions. `NEW TEMPORARY` // provisions a resource the statement owns; a bare `` borrows a registered one. -//! NEW TEMPORARY EXTERNAL RESOURCE '' [(create opts)] — provision a fresh resource. +//! NEW TEMPORARY EXTERNAL RESOURCE [(create opts)] — provision a fresh resource. unique_ptr PEGTransformerFactory::TransformExternalResourceCreateClause( - PEGTransformer &transformer, const string &string_literal, + PEGTransformer &transformer, const string &external_resource_type, const optional> &external_resource_creation_options) { auto result = make_uniq(); - result->provider = string_literal; + result->provider = external_resource_type; if (external_resource_creation_options) { CollectGenericOptions(*external_resource_creation_options, result->parsed_params, "EXTERNAL RESOURCE"); } diff --git a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp index 936dc01ae..f6d34a8c4 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp @@ -2313,7 +2313,23 @@ static const TransformChildPlan FRAME_CHILDREN_160[] = {{PEGRuleId::ShowExternal {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_173 = {FRAME_CHILDREN_160, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_161[] = {{PEGRuleId::SelectStatementInternal, +static const TransformChildPlan FRAME_CHILDREN_161[] = {{PEGRuleId::ExternalResourceType, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_174 = {FRAME_CHILDREN_161, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_162[] = {{PEGRuleId::ShowRule, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_175 = {FRAME_CHILDREN_162, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_163[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 1, 1, @@ -2327,8 +2343,8 @@ static const TransformChildPlan FRAME_CHILDREN_161[] = {{PEGRuleId::SelectStatem false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_174 = {FRAME_CHILDREN_161, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_162[] = {{PEGRuleId::SelectStatementInternal, +static const TransformFramePlan FRAME_PLAN_176 = {FRAME_CHILDREN_163, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_164[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 1, 1, @@ -2342,16 +2358,16 @@ static const TransformChildPlan FRAME_CHILDREN_162[] = {{PEGRuleId::SelectStatem false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_175 = {FRAME_CHILDREN_162, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_163[] = {{PEGRuleId::ShowOrDescribe, +static const TransformFramePlan FRAME_PLAN_177 = {FRAME_CHILDREN_164, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_165[] = {{PEGRuleId::ShowOrDescribe, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_176 = {FRAME_CHILDREN_163, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_164[] = {{PEGRuleId::QualifiedName, +static const TransformFramePlan FRAME_PLAN_178 = {FRAME_CHILDREN_165, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_166[] = {{PEGRuleId::QualifiedName, TransformChildKind::REQUIRED, 3, 1, @@ -2365,8 +2381,8 @@ static const TransformChildPlan FRAME_CHILDREN_164[] = {{PEGRuleId::QualifiedNam false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_177 = {FRAME_CHILDREN_164, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_165[] = {{PEGRuleId::ShowTarget, +static const TransformFramePlan FRAME_PLAN_179 = {FRAME_CHILDREN_166, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_167[] = {{PEGRuleId::ShowTarget, TransformChildKind::OPTIONAL, 1, 1, @@ -2380,8 +2396,8 @@ static const TransformChildPlan FRAME_CHILDREN_165[] = {{PEGRuleId::ShowTarget, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_178 = {FRAME_CHILDREN_165, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_166[] = {{PEGRuleId::DescribeTarget, +static const TransformFramePlan FRAME_PLAN_180 = {FRAME_CHILDREN_167, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_168[] = {{PEGRuleId::DescribeTarget, TransformChildKind::OPTIONAL, 1, 1, @@ -2395,42 +2411,42 @@ static const TransformChildPlan FRAME_CHILDREN_166[] = {{PEGRuleId::DescribeTarg false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_179 = {FRAME_CHILDREN_166, 2, 2, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_181 = {FRAME_CHILDREN_168, 2, 2, false, 0, {}}; static const char *const FRAME_NAMES_7[] = {"ShowSpecialForm"}; -static const TransformFramePlan FRAME_PLAN_180 = {nullptr, 0, 1, false, 0, {0, 0, false, true, 1, FRAME_NAMES_7}}; -static const TransformChildPlan FRAME_CHILDREN_167[] = {{PEGRuleId::QualifiedTableName, +static const TransformFramePlan FRAME_PLAN_182 = {nullptr, 0, 1, false, 0, {0, 0, false, true, 1, FRAME_NAMES_7}}; +static const TransformChildPlan FRAME_CHILDREN_169[] = {{PEGRuleId::QualifiedTableName, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_181 = {FRAME_CHILDREN_167, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_168[] = {{PEGRuleId::BaseTableName, +static const TransformFramePlan FRAME_PLAN_183 = {FRAME_CHILDREN_169, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_170[] = {{PEGRuleId::BaseTableName, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_182 = {FRAME_CHILDREN_168, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_169[] = {{PEGRuleId::SummarizeRule, +static const TransformFramePlan FRAME_PLAN_184 = {FRAME_CHILDREN_170, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_171[] = {{PEGRuleId::SummarizeRule, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_183 = {FRAME_CHILDREN_169, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_170[] = {{PEGRuleId::IfExists, +static const TransformFramePlan FRAME_PLAN_185 = {FRAME_CHILDREN_171, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_172[] = {{PEGRuleId::IfExists, TransformChildKind::OPTIONAL, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_184 = {FRAME_CHILDREN_170, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_171[] = {{PEGRuleId::DropBehavior, +static const TransformFramePlan FRAME_PLAN_186 = {FRAME_CHILDREN_172, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_173[] = {{PEGRuleId::DropBehavior, TransformChildKind::OPTIONAL, 2, 1, @@ -2444,8 +2460,8 @@ static const TransformChildPlan FRAME_CHILDREN_171[] = {{PEGRuleId::DropBehavior false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_185 = {FRAME_CHILDREN_171, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_172[] = {{PEGRuleId::DropBehavior, +static const TransformFramePlan FRAME_PLAN_187 = {FRAME_CHILDREN_173, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_174[] = {{PEGRuleId::DropBehavior, TransformChildKind::OPTIONAL, 2, 1, @@ -2459,8 +2475,8 @@ static const TransformChildPlan FRAME_CHILDREN_172[] = {{PEGRuleId::DropBehavior false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_186 = {FRAME_CHILDREN_172, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_173[] = {{PEGRuleId::DropFunctionSignature, +static const TransformFramePlan FRAME_PLAN_188 = {FRAME_CHILDREN_174, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_175[] = {{PEGRuleId::DropFunctionSignature, TransformChildKind::REQUIRED, 3, 3, @@ -2488,8 +2504,8 @@ static const TransformChildPlan FRAME_CHILDREN_173[] = {{PEGRuleId::DropFunction false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_187 = {FRAME_CHILDREN_173, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_174[] = {{PEGRuleId::DropFunctionSignature, +static const TransformFramePlan FRAME_PLAN_189 = {FRAME_CHILDREN_175, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_176[] = {{PEGRuleId::DropFunctionSignature, TransformChildKind::REQUIRED, 3, 3, @@ -2517,8 +2533,8 @@ static const TransformChildPlan FRAME_CHILDREN_174[] = {{PEGRuleId::DropFunction false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_188 = {FRAME_CHILDREN_174, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_175[] = {{PEGRuleId::BaseTableName, +static const TransformFramePlan FRAME_PLAN_190 = {FRAME_CHILDREN_176, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_177[] = {{PEGRuleId::BaseTableName, TransformChildKind::REQUIRED, 4, 2, @@ -2539,8 +2555,8 @@ static const TransformChildPlan FRAME_CHILDREN_175[] = {{PEGRuleId::BaseTableNam false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_189 = {FRAME_CHILDREN_175, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_176[] = {{PEGRuleId::BaseTableName, +static const TransformFramePlan FRAME_PLAN_191 = {FRAME_CHILDREN_177, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_178[] = {{PEGRuleId::BaseTableName, TransformChildKind::LIST, 2, 2, @@ -2561,8 +2577,8 @@ static const TransformChildPlan FRAME_CHILDREN_176[] = {{PEGRuleId::BaseTableNam false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_190 = {FRAME_CHILDREN_176, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_177[] = {{PEGRuleId::QualifiedTableFunction, +static const TransformFramePlan FRAME_PLAN_192 = {FRAME_CHILDREN_178, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_179[] = {{PEGRuleId::QualifiedTableFunction, TransformChildKind::LIST, 2, 2, @@ -2583,8 +2599,8 @@ static const TransformChildPlan FRAME_CHILDREN_177[] = {{PEGRuleId::QualifiedTab false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_191 = {FRAME_CHILDREN_177, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_178[] = {{PEGRuleId::FunctionIdentifier, +static const TransformFramePlan FRAME_PLAN_193 = {FRAME_CHILDREN_179, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_180[] = {{PEGRuleId::FunctionIdentifier, TransformChildKind::LIST, 2, 2, @@ -2605,16 +2621,16 @@ static const TransformChildPlan FRAME_CHILDREN_178[] = {{PEGRuleId::FunctionIden false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_192 = {FRAME_CHILDREN_178, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_179[] = {{PEGRuleId::DropSignatureType, +static const TransformFramePlan FRAME_PLAN_194 = {FRAME_CHILDREN_180, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_181[] = {{PEGRuleId::DropSignatureType, TransformChildKind::OPTIONAL_LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_193 = {FRAME_CHILDREN_179, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_180[] = {{PEGRuleId::QualifiedName, +static const TransformFramePlan FRAME_PLAN_195 = {FRAME_CHILDREN_181, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_182[] = {{PEGRuleId::QualifiedName, TransformChildKind::LIST, 2, 1, @@ -2628,8 +2644,8 @@ static const TransformChildPlan FRAME_CHILDREN_180[] = {{PEGRuleId::QualifiedNam false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_194 = {FRAME_CHILDREN_180, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_181[] = {{PEGRuleId::QualifiedIndexName, +static const TransformFramePlan FRAME_PLAN_196 = {FRAME_CHILDREN_182, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_183[] = {{PEGRuleId::QualifiedIndexName, TransformChildKind::LIST, 2, 1, @@ -2643,8 +2659,8 @@ static const TransformChildPlan FRAME_CHILDREN_181[] = {{PEGRuleId::QualifiedInd false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_195 = {FRAME_CHILDREN_181, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_182[] = {{PEGRuleId::QualifiedSequenceName, +static const TransformFramePlan FRAME_PLAN_197 = {FRAME_CHILDREN_183, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_184[] = {{PEGRuleId::QualifiedSequenceName, TransformChildKind::LIST, 2, 1, @@ -2658,8 +2674,8 @@ static const TransformChildPlan FRAME_CHILDREN_182[] = {{PEGRuleId::QualifiedSeq false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_196 = {FRAME_CHILDREN_182, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_183[] = {{PEGRuleId::CollationName, +static const TransformFramePlan FRAME_PLAN_198 = {FRAME_CHILDREN_184, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_185[] = {{PEGRuleId::CollationName, TransformChildKind::LIST, 2, 1, @@ -2673,8 +2689,8 @@ static const TransformChildPlan FRAME_CHILDREN_183[] = {{PEGRuleId::CollationNam false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_197 = {FRAME_CHILDREN_183, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_184[] = {{PEGRuleId::QualifiedTypeName, +static const TransformFramePlan FRAME_PLAN_199 = {FRAME_CHILDREN_185, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_186[] = {{PEGRuleId::QualifiedTypeName, TransformChildKind::LIST, 2, 1, @@ -2688,8 +2704,8 @@ static const TransformChildPlan FRAME_CHILDREN_184[] = {{PEGRuleId::QualifiedTyp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_198 = {FRAME_CHILDREN_184, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_185[] = {{PEGRuleId::DropSecretStorage, +static const TransformFramePlan FRAME_PLAN_200 = {FRAME_CHILDREN_186, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_187[] = {{PEGRuleId::DropSecretStorage, TransformChildKind::OPTIONAL, 4, 3, @@ -2717,8 +2733,8 @@ static const TransformChildPlan FRAME_CHILDREN_185[] = {{PEGRuleId::DropSecretSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_199 = {FRAME_CHILDREN_185, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_186[] = {{PEGRuleId::TableFunctionArguments, +static const TransformFramePlan FRAME_PLAN_201 = {FRAME_CHILDREN_187, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_188[] = {{PEGRuleId::TableFunctionArguments, TransformChildKind::OPTIONAL, 2, 1, @@ -2732,8 +2748,8 @@ static const TransformChildPlan FRAME_CHILDREN_186[] = {{PEGRuleId::TableFunctio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_200 = {FRAME_CHILDREN_186, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_187[] = {{PEGRuleId::ExplainableStatements, +static const TransformFramePlan FRAME_PLAN_202 = {FRAME_CHILDREN_188, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_189[] = {{PEGRuleId::ExplainableStatements, TransformChildKind::REQUIRED, 3, 2, @@ -2754,16 +2770,16 @@ static const TransformChildPlan FRAME_CHILDREN_187[] = {{PEGRuleId::ExplainableS false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_201 = {FRAME_CHILDREN_187, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_188[] = {{PEGRuleId::ExplainOption, +static const TransformFramePlan FRAME_PLAN_203 = {FRAME_CHILDREN_189, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_190[] = {{PEGRuleId::ExplainOption, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_202 = {FRAME_CHILDREN_188, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_189[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_204 = {FRAME_CHILDREN_190, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_191[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL, 1, 1, @@ -2777,9 +2793,9 @@ static const TransformChildPlan FRAME_CHILDREN_189[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_203 = {FRAME_CHILDREN_189, 2, 2, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_205 = {FRAME_CHILDREN_191, 2, 2, false, 0, {}}; static const char *const FRAME_NAMES_8[] = {"FuncNameKeyword", "TypeNameKeyword"}; -static const TransformFramePlan FRAME_PLAN_204 = {nullptr, +static const TransformFramePlan FRAME_PLAN_206 = {nullptr, 0, 1, false, @@ -2788,15 +2804,15 @@ static const TransformFramePlan FRAME_PLAN_204 = {nullptr, ParseResultTypeBit(ParseResultType::KEYWORD) | ParseResultTypeBit(ParseResultType::STRING), 0, true, false, 2, FRAME_NAMES_8}}; -static const TransformChildPlan FRAME_CHILDREN_190[] = {{PEGRuleId::SelectStatementInternal, +static const TransformChildPlan FRAME_CHILDREN_192[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_205 = {FRAME_CHILDREN_190, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_191[] = {{PEGRuleId::ExportOptions, +static const TransformFramePlan FRAME_PLAN_207 = {FRAME_CHILDREN_192, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_193[] = {{PEGRuleId::ExportOptions, TransformChildKind::OPTIONAL, 4, 1, @@ -2810,8 +2826,8 @@ static const TransformChildPlan FRAME_CHILDREN_191[] = {{PEGRuleId::ExportOption false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_206 = {FRAME_CHILDREN_191, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_192[] = {{PEGRuleId::ReservedSchemaQualification, +static const TransformFramePlan FRAME_PLAN_208 = {FRAME_CHILDREN_193, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_194[] = {{PEGRuleId::ReservedSchemaQualification, TransformChildKind::REPEAT, 3, 3, @@ -2839,8 +2855,8 @@ static const TransformChildPlan FRAME_CHILDREN_192[] = {{PEGRuleId::ReservedSche false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_207 = {FRAME_CHILDREN_192, 4, 4, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_193[] = {{PEGRuleId::ReservedTableQualification, +static const TransformFramePlan FRAME_PLAN_209 = {FRAME_CHILDREN_194, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_195[] = {{PEGRuleId::ReservedTableQualification, TransformChildKind::REQUIRED, 2, 2, @@ -2861,8 +2877,8 @@ static const TransformChildPlan FRAME_CHILDREN_193[] = {{PEGRuleId::ReservedTabl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_208 = {FRAME_CHILDREN_193, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_194[] = {{PEGRuleId::ReservedTableQualification, +static const TransformFramePlan FRAME_PLAN_210 = {FRAME_CHILDREN_195, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_196[] = {{PEGRuleId::ReservedTableQualification, TransformChildKind::REQUIRED, 1, 1, @@ -2876,16 +2892,16 @@ static const TransformChildPlan FRAME_CHILDREN_194[] = {{PEGRuleId::ReservedTabl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_209 = {FRAME_CHILDREN_194, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_195[] = {{PEGRuleId::TableQualification, +static const TransformFramePlan FRAME_PLAN_211 = {FRAME_CHILDREN_196, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_197[] = {{PEGRuleId::TableQualification, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_210 = {FRAME_CHILDREN_195, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_196[] = {{PEGRuleId::OverClause, +static const TransformFramePlan FRAME_PLAN_212 = {FRAME_CHILDREN_197, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_198[] = {{PEGRuleId::OverClause, TransformChildKind::OPTIONAL, 5, 4, @@ -2920,16 +2936,16 @@ static const TransformChildPlan FRAME_CHILDREN_196[] = {{PEGRuleId::OverClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_211 = {FRAME_CHILDREN_196, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_197[] = {{PEGRuleId::FunctionExpressionArgumentList, +static const TransformFramePlan FRAME_PLAN_213 = {FRAME_CHILDREN_198, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_199[] = {{PEGRuleId::FunctionExpressionArgumentList, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_212 = {FRAME_CHILDREN_197, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_198[] = {{PEGRuleId::IgnoreOrRespectNulls, +static const TransformFramePlan FRAME_PLAN_214 = {FRAME_CHILDREN_199, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_200[] = {{PEGRuleId::IgnoreOrRespectNulls, TransformChildKind::OPTIONAL, 3, 3, @@ -2957,16 +2973,16 @@ static const TransformChildPlan FRAME_CHILDREN_198[] = {{PEGRuleId::IgnoreOrResp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_213 = {FRAME_CHILDREN_198, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_199[] = {{PEGRuleId::FunctionArgument, +static const TransformFramePlan FRAME_PLAN_215 = {FRAME_CHILDREN_200, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_201[] = {{PEGRuleId::FunctionArgument, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_214 = {FRAME_CHILDREN_199, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_200[] = {{PEGRuleId::ReservedSchemaQualification, +static const TransformFramePlan FRAME_PLAN_216 = {FRAME_CHILDREN_201, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_202[] = {{PEGRuleId::ReservedSchemaQualification, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -2980,32 +2996,32 @@ static const TransformChildPlan FRAME_CHILDREN_200[] = {{PEGRuleId::ReservedSche false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_215 = {FRAME_CHILDREN_200, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_201[] = {{PEGRuleId::OrderByClause, +static const TransformFramePlan FRAME_PLAN_217 = {FRAME_CHILDREN_202, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_203[] = {{PEGRuleId::OrderByClause, TransformChildKind::REQUIRED, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_216 = {FRAME_CHILDREN_201, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_202[] = {{PEGRuleId::FilterClauseExpression, +static const TransformFramePlan FRAME_PLAN_218 = {FRAME_CHILDREN_203, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_204[] = {{PEGRuleId::FilterClauseExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_217 = {FRAME_CHILDREN_202, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_203[] = {{PEGRuleId::FilterClauseContents, +static const TransformFramePlan FRAME_PLAN_219 = {FRAME_CHILDREN_204, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_205[] = {{PEGRuleId::FilterClauseContents, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_218 = {FRAME_CHILDREN_203, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_204[] = {{PEGRuleId::CastArguments, +static const TransformFramePlan FRAME_PLAN_220 = {FRAME_CHILDREN_205, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_206[] = {{PEGRuleId::CastArguments, TransformChildKind::REQUIRED, 1, 1, @@ -3019,8 +3035,8 @@ static const TransformChildPlan FRAME_CHILDREN_204[] = {{PEGRuleId::CastArgument false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_219 = {FRAME_CHILDREN_204, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_205[] = {{PEGRuleId::Type, +static const TransformFramePlan FRAME_PLAN_221 = {FRAME_CHILDREN_206, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_207[] = {{PEGRuleId::Type, TransformChildKind::REQUIRED, 2, 1, @@ -3034,8 +3050,8 @@ static const TransformChildPlan FRAME_CHILDREN_205[] = {{PEGRuleId::Type, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_220 = {FRAME_CHILDREN_205, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_206[] = {{PEGRuleId::RenameList, +static const TransformFramePlan FRAME_PLAN_222 = {FRAME_CHILDREN_207, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_208[] = {{PEGRuleId::RenameList, TransformChildKind::OPTIONAL, 4, 3, @@ -3063,72 +3079,72 @@ static const TransformChildPlan FRAME_CHILDREN_206[] = {{PEGRuleId::RenameList, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_221 = {FRAME_CHILDREN_206, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_207[] = {{PEGRuleId::ColIdDot, +static const TransformFramePlan FRAME_PLAN_223 = {FRAME_CHILDREN_208, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_209[] = {{PEGRuleId::ColIdDot, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_222 = {FRAME_CHILDREN_207, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_208[] = {{PEGRuleId::ExcludeNames, +static const TransformFramePlan FRAME_PLAN_224 = {FRAME_CHILDREN_209, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_210[] = {{PEGRuleId::ExcludeNames, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_223 = {FRAME_CHILDREN_208, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_209[] = {{PEGRuleId::ExcludeName, +static const TransformFramePlan FRAME_PLAN_225 = {FRAME_CHILDREN_210, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_211[] = {{PEGRuleId::ExcludeName, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_224 = {FRAME_CHILDREN_209, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_210[] = {{PEGRuleId::ExcludeName, +static const TransformFramePlan FRAME_PLAN_226 = {FRAME_CHILDREN_211, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_212[] = {{PEGRuleId::ExcludeName, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_225 = {FRAME_CHILDREN_210, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_211[] = {{PEGRuleId::DottedIdentifier, +static const TransformFramePlan FRAME_PLAN_227 = {FRAME_CHILDREN_212, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_213[] = {{PEGRuleId::DottedIdentifier, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_226 = {FRAME_CHILDREN_211, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_212[] = {{PEGRuleId::ReplaceEntries, +static const TransformFramePlan FRAME_PLAN_228 = {FRAME_CHILDREN_213, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_214[] = {{PEGRuleId::ReplaceEntries, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_227 = {FRAME_CHILDREN_212, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_213[] = {{PEGRuleId::ReplaceEntry, +static const TransformFramePlan FRAME_PLAN_229 = {FRAME_CHILDREN_214, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_215[] = {{PEGRuleId::ReplaceEntry, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_228 = {FRAME_CHILDREN_213, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_214[] = {{PEGRuleId::ReplaceEntry, +static const TransformFramePlan FRAME_PLAN_230 = {FRAME_CHILDREN_215, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_216[] = {{PEGRuleId::ReplaceEntry, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_229 = {FRAME_CHILDREN_214, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_215[] = {{PEGRuleId::ColumnReference, +static const TransformFramePlan FRAME_PLAN_231 = {FRAME_CHILDREN_216, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_217[] = {{PEGRuleId::ColumnReference, TransformChildKind::REQUIRED, 2, 1, @@ -3142,32 +3158,32 @@ static const TransformChildPlan FRAME_CHILDREN_215[] = {{PEGRuleId::ColumnRefere false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_230 = {FRAME_CHILDREN_215, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_216[] = {{PEGRuleId::RenameEntries, +static const TransformFramePlan FRAME_PLAN_232 = {FRAME_CHILDREN_217, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_218[] = {{PEGRuleId::RenameEntries, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_231 = {FRAME_CHILDREN_216, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_217[] = {{PEGRuleId::RenameEntry, +static const TransformFramePlan FRAME_PLAN_233 = {FRAME_CHILDREN_218, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_219[] = {{PEGRuleId::RenameEntry, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_232 = {FRAME_CHILDREN_217, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_218[] = {{PEGRuleId::RenameEntry, +static const TransformFramePlan FRAME_PLAN_234 = {FRAME_CHILDREN_219, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_220[] = {{PEGRuleId::RenameEntry, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_233 = {FRAME_CHILDREN_218, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_219[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_235 = {FRAME_CHILDREN_220, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_221[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 2, 2, @@ -3188,8 +3204,8 @@ static const TransformChildPlan FRAME_CHILDREN_219[] = {{PEGRuleId::SubqueryRefe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_234 = {FRAME_CHILDREN_219, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_220[] = {{PEGRuleId::CaseElse, +static const TransformFramePlan FRAME_PLAN_236 = {FRAME_CHILDREN_221, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_222[] = {{PEGRuleId::CaseElse, TransformChildKind::OPTIONAL, 3, 2, @@ -3210,8 +3226,8 @@ static const TransformChildPlan FRAME_CHILDREN_220[] = {{PEGRuleId::CaseElse, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_235 = {FRAME_CHILDREN_220, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_221[] = {{PEGRuleId::CaseElse, +static const TransformFramePlan FRAME_PLAN_237 = {FRAME_CHILDREN_222, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_223[] = {{PEGRuleId::CaseElse, TransformChildKind::OPTIONAL, 2, 1, @@ -3225,8 +3241,8 @@ static const TransformChildPlan FRAME_CHILDREN_221[] = {{PEGRuleId::CaseElse, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_236 = {FRAME_CHILDREN_221, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_222[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_238 = {FRAME_CHILDREN_223, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_224[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 1, @@ -3240,8 +3256,8 @@ static const TransformChildPlan FRAME_CHILDREN_222[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_237 = {FRAME_CHILDREN_222, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_223[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_239 = {FRAME_CHILDREN_224, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_225[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 1, @@ -3255,8 +3271,8 @@ static const TransformChildPlan FRAME_CHILDREN_223[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_238 = {FRAME_CHILDREN_223, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_224[] = {{PEGRuleId::Interval, +static const TransformFramePlan FRAME_PLAN_240 = {FRAME_CHILDREN_225, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_226[] = {{PEGRuleId::Interval, TransformChildKind::OPTIONAL, 2, 1, @@ -3270,8 +3286,8 @@ static const TransformChildPlan FRAME_CHILDREN_224[] = {{PEGRuleId::Interval, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_239 = {FRAME_CHILDREN_224, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_225[] = {{PEGRuleId::WindowExcludeClause, +static const TransformFramePlan FRAME_PLAN_241 = {FRAME_CHILDREN_226, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_227[] = {{PEGRuleId::WindowExcludeClause, TransformChildKind::OPTIONAL, 2, 2, @@ -3292,16 +3308,16 @@ static const TransformChildPlan FRAME_CHILDREN_225[] = {{PEGRuleId::WindowExclud false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_240 = {FRAME_CHILDREN_225, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_226[] = {{PEGRuleId::FrameBound, +static const TransformFramePlan FRAME_PLAN_242 = {FRAME_CHILDREN_227, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_228[] = {{PEGRuleId::FrameBound, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_241 = {FRAME_CHILDREN_226, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_227[] = {{PEGRuleId::FrameBound, +static const TransformFramePlan FRAME_PLAN_243 = {FRAME_CHILDREN_228, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_229[] = {{PEGRuleId::FrameBound, TransformChildKind::REQUIRED, 3, 1, @@ -3315,16 +3331,16 @@ static const TransformChildPlan FRAME_CHILDREN_227[] = {{PEGRuleId::FrameBound, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_242 = {FRAME_CHILDREN_227, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_228[] = {{PEGRuleId::PrecedingOrFollowing, +static const TransformFramePlan FRAME_PLAN_244 = {FRAME_CHILDREN_229, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_230[] = {{PEGRuleId::PrecedingOrFollowing, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_243 = {FRAME_CHILDREN_228, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_229[] = {{PEGRuleId::PrecedingOrFollowing, +static const TransformFramePlan FRAME_PLAN_245 = {FRAME_CHILDREN_230, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_231[] = {{PEGRuleId::PrecedingOrFollowing, TransformChildKind::REQUIRED, 1, 1, @@ -3338,24 +3354,24 @@ static const TransformChildPlan FRAME_CHILDREN_229[] = {{PEGRuleId::PrecedingOrF false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_244 = {FRAME_CHILDREN_229, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_230[] = {{PEGRuleId::WindowExcludeElement, +static const TransformFramePlan FRAME_PLAN_246 = {FRAME_CHILDREN_231, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_232[] = {{PEGRuleId::WindowExcludeElement, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_245 = {FRAME_CHILDREN_230, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_231[] = {{PEGRuleId::WindowFrameNameContents, +static const TransformFramePlan FRAME_PLAN_247 = {FRAME_CHILDREN_232, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_233[] = {{PEGRuleId::WindowFrameNameContents, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_246 = {FRAME_CHILDREN_231, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_232[] = {{PEGRuleId::WindowFrameContents, +static const TransformFramePlan FRAME_PLAN_248 = {FRAME_CHILDREN_233, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_234[] = {{PEGRuleId::WindowFrameContents, TransformChildKind::REQUIRED, 1, 1, @@ -3369,16 +3385,16 @@ static const TransformChildPlan FRAME_CHILDREN_232[] = {{PEGRuleId::WindowFrameC false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_247 = {FRAME_CHILDREN_232, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_233[] = {{PEGRuleId::WindowFrameContents, +static const TransformFramePlan FRAME_PLAN_249 = {FRAME_CHILDREN_234, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_235[] = {{PEGRuleId::WindowFrameContents, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_248 = {FRAME_CHILDREN_233, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_234[] = {{PEGRuleId::FrameClause, +static const TransformFramePlan FRAME_PLAN_250 = {FRAME_CHILDREN_235, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_236[] = {{PEGRuleId::FrameClause, TransformChildKind::OPTIONAL, 2, 2, @@ -3399,40 +3415,40 @@ static const TransformChildPlan FRAME_CHILDREN_234[] = {{PEGRuleId::FrameClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_249 = {FRAME_CHILDREN_234, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_235[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_251 = {FRAME_CHILDREN_236, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_237[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_250 = {FRAME_CHILDREN_235, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_236[] = {{PEGRuleId::BoundedListExpression, +static const TransformFramePlan FRAME_PLAN_252 = {FRAME_CHILDREN_237, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_238[] = {{PEGRuleId::BoundedListExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_251 = {FRAME_CHILDREN_236, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_237[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_253 = {FRAME_CHILDREN_238, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_239[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_252 = {FRAME_CHILDREN_237, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_238[] = {{PEGRuleId::StructField, +static const TransformFramePlan FRAME_PLAN_254 = {FRAME_CHILDREN_239, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_240[] = {{PEGRuleId::StructField, TransformChildKind::OPTIONAL_LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_253 = {FRAME_CHILDREN_238, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_239[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_255 = {FRAME_CHILDREN_240, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_241[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -3446,24 +3462,24 @@ static const TransformChildPlan FRAME_CHILDREN_239[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_254 = {FRAME_CHILDREN_239, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_240[] = {{PEGRuleId::MapStructExpression, +static const TransformFramePlan FRAME_PLAN_256 = {FRAME_CHILDREN_241, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_242[] = {{PEGRuleId::MapStructExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_255 = {FRAME_CHILDREN_240, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_241[] = {{PEGRuleId::MapStructField, +static const TransformFramePlan FRAME_PLAN_257 = {FRAME_CHILDREN_242, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::MapStructField, TransformChildKind::OPTIONAL_LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_256 = {FRAME_CHILDREN_241, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_242[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_258 = {FRAME_CHILDREN_243, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -3477,8 +3493,8 @@ static const TransformChildPlan FRAME_CHILDREN_242[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_257 = {FRAME_CHILDREN_242, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_259 = {FRAME_CHILDREN_244, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_245[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 1, @@ -3492,8 +3508,8 @@ static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_258 = {FRAME_CHILDREN_243, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::ListComprehensionFilter, +static const TransformFramePlan FRAME_PLAN_260 = {FRAME_CHILDREN_245, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::ListComprehensionFilter, TransformChildKind::OPTIONAL, 6, 3, @@ -3521,16 +3537,16 @@ static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::ListComprehe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_259 = {FRAME_CHILDREN_244, 4, 4, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_245[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_261 = {FRAME_CHILDREN_246, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_260 = {FRAME_CHILDREN_245, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::FunctionExpression, +static const TransformFramePlan FRAME_PLAN_262 = {FRAME_CHILDREN_247, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_248[] = {{PEGRuleId::FunctionExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3544,24 +3560,24 @@ static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::FunctionExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_261 = {FRAME_CHILDREN_246, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::LogicalOrExpression, +static const TransformFramePlan FRAME_PLAN_263 = {FRAME_CHILDREN_248, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::LogicalOrExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_262 = {FRAME_CHILDREN_247, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_248[] = {{PEGRuleId::ColDefOrExpr, +static const TransformFramePlan FRAME_PLAN_264 = {FRAME_CHILDREN_249, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::ColDefOrExpr, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_263 = {FRAME_CHILDREN_248, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::LogicalOrExpressionTail, +static const TransformFramePlan FRAME_PLAN_265 = {FRAME_CHILDREN_250, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_251[] = {{PEGRuleId::LogicalOrExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3575,16 +3591,16 @@ static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::LogicalOrExp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_264 = {FRAME_CHILDREN_249, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::LogicalAndExpression, +static const TransformFramePlan FRAME_PLAN_266 = {FRAME_CHILDREN_251, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::LogicalAndExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_265 = {FRAME_CHILDREN_250, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_251[] = {{PEGRuleId::ColDefOrExpressionTail, +static const TransformFramePlan FRAME_PLAN_267 = {FRAME_CHILDREN_252, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_253[] = {{PEGRuleId::ColDefOrExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3598,16 +3614,16 @@ static const TransformChildPlan FRAME_CHILDREN_251[] = {{PEGRuleId::ColDefOrExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_266 = {FRAME_CHILDREN_251, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::ColDefAndExpr, +static const TransformFramePlan FRAME_PLAN_268 = {FRAME_CHILDREN_253, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_254[] = {{PEGRuleId::ColDefAndExpr, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_267 = {FRAME_CHILDREN_252, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_253[] = {{PEGRuleId::LogicalAndExpressionTail, +static const TransformFramePlan FRAME_PLAN_269 = {FRAME_CHILDREN_254, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_255[] = {{PEGRuleId::LogicalAndExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3621,16 +3637,16 @@ static const TransformChildPlan FRAME_CHILDREN_253[] = {{PEGRuleId::LogicalAndEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_268 = {FRAME_CHILDREN_253, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_254[] = {{PEGRuleId::LogicalNotExpression, +static const TransformFramePlan FRAME_PLAN_270 = {FRAME_CHILDREN_255, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::LogicalNotExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_269 = {FRAME_CHILDREN_254, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_255[] = {{PEGRuleId::ColDefAndExpressionTail, +static const TransformFramePlan FRAME_PLAN_271 = {FRAME_CHILDREN_256, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_257[] = {{PEGRuleId::ColDefAndExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3644,16 +3660,16 @@ static const TransformChildPlan FRAME_CHILDREN_255[] = {{PEGRuleId::ColDefAndExp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_270 = {FRAME_CHILDREN_255, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::IsDistinctFromExpression, +static const TransformFramePlan FRAME_PLAN_272 = {FRAME_CHILDREN_257, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::IsDistinctFromExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_271 = {FRAME_CHILDREN_256, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_257[] = {{PEGRuleId::IsExpression, +static const TransformFramePlan FRAME_PLAN_273 = {FRAME_CHILDREN_258, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_259[] = {{PEGRuleId::IsExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3667,16 +3683,16 @@ static const TransformChildPlan FRAME_CHILDREN_257[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_272 = {FRAME_CHILDREN_257, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::NotKeyword, +static const TransformFramePlan FRAME_PLAN_274 = {FRAME_CHILDREN_259, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::NotKeyword, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_273 = {FRAME_CHILDREN_258, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_259[] = {{PEGRuleId::IsExpressionContinuation, +static const TransformFramePlan FRAME_PLAN_275 = {FRAME_CHILDREN_260, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_261[] = {{PEGRuleId::IsExpressionContinuation, TransformChildKind::OPTIONAL, 1, 1, @@ -3690,8 +3706,8 @@ static const TransformChildPlan FRAME_CHILDREN_259[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_274 = {FRAME_CHILDREN_259, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::IsExpressionTail, +static const TransformFramePlan FRAME_PLAN_276 = {FRAME_CHILDREN_261, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_262[] = {{PEGRuleId::IsExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3705,64 +3721,64 @@ static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_275 = {FRAME_CHILDREN_260, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_261[] = {{PEGRuleId::IsTest, +static const TransformFramePlan FRAME_PLAN_277 = {FRAME_CHILDREN_262, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_263[] = {{PEGRuleId::IsTest, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_276 = {FRAME_CHILDREN_261, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_262[] = {{PEGRuleId::IsDistinctFromTail, +static const TransformFramePlan FRAME_PLAN_278 = {FRAME_CHILDREN_263, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_264[] = {{PEGRuleId::IsDistinctFromTail, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_277 = {FRAME_CHILDREN_262, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_263[] = {{PEGRuleId::ComparisonExpressionTail, +static const TransformFramePlan FRAME_PLAN_279 = {FRAME_CHILDREN_264, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_265[] = {{PEGRuleId::ComparisonExpressionTail, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_278 = {FRAME_CHILDREN_263, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_264[] = {{PEGRuleId::OtherOperatorTail, +static const TransformFramePlan FRAME_PLAN_280 = {FRAME_CHILDREN_265, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::OtherOperatorTail, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_279 = {FRAME_CHILDREN_264, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_265[] = {{PEGRuleId::CastOperator, +static const TransformFramePlan FRAME_PLAN_281 = {FRAME_CHILDREN_266, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::CastOperator, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_280 = {FRAME_CHILDREN_265, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::IsLiteralValue, +static const TransformFramePlan FRAME_PLAN_282 = {FRAME_CHILDREN_267, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::IsLiteralValue, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_281 = {FRAME_CHILDREN_266, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::IsNullOperator, +static const TransformFramePlan FRAME_PLAN_283 = {FRAME_CHILDREN_268, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::IsNullOperator, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_282 = {FRAME_CHILDREN_267, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::IsDistinctFromTail, +static const TransformFramePlan FRAME_PLAN_284 = {FRAME_CHILDREN_269, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::IsDistinctFromTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3776,8 +3792,8 @@ static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::IsDistinctFr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_283 = {FRAME_CHILDREN_268, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::ComparisonExpression, +static const TransformFramePlan FRAME_PLAN_285 = {FRAME_CHILDREN_270, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::ComparisonExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3791,8 +3807,8 @@ static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::ComparisonEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_284 = {FRAME_CHILDREN_269, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::ComparisonExpressionTail, +static const TransformFramePlan FRAME_PLAN_286 = {FRAME_CHILDREN_271, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::ComparisonExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3806,8 +3822,8 @@ static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::ComparisonEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_285 = {FRAME_CHILDREN_270, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::ComparisonOperand, +static const TransformFramePlan FRAME_PLAN_287 = {FRAME_CHILDREN_272, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::ComparisonOperand, TransformChildKind::REQUIRED, 1, 1, @@ -3821,8 +3837,8 @@ static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::ComparisonOp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_286 = {FRAME_CHILDREN_271, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::IsExpression, +static const TransformFramePlan FRAME_PLAN_288 = {FRAME_CHILDREN_273, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::IsExpression, TransformChildKind::REQUIRED, 1, 1, @@ -3836,8 +3852,8 @@ static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::IsExpression false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_287 = {FRAME_CHILDREN_272, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::BetweenLikeOp, +static const TransformFramePlan FRAME_PLAN_289 = {FRAME_CHILDREN_274, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::BetweenLikeOp, TransformChildKind::OPTIONAL, 2, 2, @@ -3858,8 +3874,8 @@ static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::BetweenLikeO false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_288 = {FRAME_CHILDREN_273, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::CastOperator, +static const TransformFramePlan FRAME_PLAN_290 = {FRAME_CHILDREN_275, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_276[] = {{PEGRuleId::CastOperator, TransformChildKind::OPTIONAL_REPEAT, 2, 1, @@ -3873,16 +3889,16 @@ static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::CastOperator false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_289 = {FRAME_CHILDREN_274, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::BetweenLikeOpExpression, +static const TransformFramePlan FRAME_PLAN_291 = {FRAME_CHILDREN_276, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_277[] = {{PEGRuleId::BetweenLikeOpExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_290 = {FRAME_CHILDREN_275, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_276[] = {{PEGRuleId::EscapeClause, +static const TransformFramePlan FRAME_PLAN_292 = {FRAME_CHILDREN_277, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_278[] = {{PEGRuleId::EscapeClause, TransformChildKind::OPTIONAL, 2, 2, @@ -3903,48 +3919,48 @@ static const TransformChildPlan FRAME_CHILDREN_276[] = {{PEGRuleId::EscapeClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_291 = {FRAME_CHILDREN_276, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_277[] = {{PEGRuleId::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_293 = {FRAME_CHILDREN_278, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_279[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_292 = {FRAME_CHILDREN_277, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_278[] = {{PEGRuleId::InExpression, +static const TransformFramePlan FRAME_PLAN_294 = {FRAME_CHILDREN_279, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_280[] = {{PEGRuleId::InExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_293 = {FRAME_CHILDREN_278, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_279[] = {{PEGRuleId::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_295 = {FRAME_CHILDREN_280, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_294 = {FRAME_CHILDREN_279, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_280[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_296 = {FRAME_CHILDREN_281, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_295 = {FRAME_CHILDREN_280, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::SelectStatementInternal, +static const TransformFramePlan FRAME_PLAN_297 = {FRAME_CHILDREN_282, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_283[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_296 = {FRAME_CHILDREN_281, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::OtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_298 = {FRAME_CHILDREN_283, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::OtherOperatorExpression, TransformChildKind::REQUIRED, 4, 1, @@ -3958,16 +3974,16 @@ static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::OtherOperato false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_297 = {FRAME_CHILDREN_282, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_283[] = {{PEGRuleId::InfixOtherOperatorExpression, +static const TransformFramePlan FRAME_PLAN_299 = {FRAME_CHILDREN_284, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::InfixOtherOperatorExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_298 = {FRAME_CHILDREN_283, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::OtherOperatorTail, +static const TransformFramePlan FRAME_PLAN_300 = {FRAME_CHILDREN_285, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::OtherOperatorTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -3981,8 +3997,8 @@ static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::OtherOperato false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_299 = {FRAME_CHILDREN_284, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_301 = {FRAME_CHILDREN_286, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_287[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 1, 1, @@ -3996,8 +4012,8 @@ static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::SubqueryRefe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_300 = {FRAME_CHILDREN_285, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::BitwiseExpression, +static const TransformFramePlan FRAME_PLAN_302 = {FRAME_CHILDREN_287, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_288[] = {{PEGRuleId::BitwiseExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4011,16 +4027,16 @@ static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::BitwiseExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_301 = {FRAME_CHILDREN_286, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_287[] = {{PEGRuleId::SingleArrowBody, +static const TransformFramePlan FRAME_PLAN_303 = {FRAME_CHILDREN_288, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_289[] = {{PEGRuleId::SingleArrowBody, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_302 = {FRAME_CHILDREN_287, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_288[] = {{PEGRuleId::ArrowChainTail, +static const TransformFramePlan FRAME_PLAN_304 = {FRAME_CHILDREN_289, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_290[] = {{PEGRuleId::ArrowChainTail, TransformChildKind::REPEAT, 1, 1, @@ -4034,48 +4050,48 @@ static const TransformChildPlan FRAME_CHILDREN_288[] = {{PEGRuleId::ArrowChainTa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_303 = {FRAME_CHILDREN_288, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_289[] = {{PEGRuleId::BitwiseExpression, +static const TransformFramePlan FRAME_PLAN_305 = {FRAME_CHILDREN_290, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::BitwiseExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_304 = {FRAME_CHILDREN_289, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_290[] = {{PEGRuleId::AnyAllOperator, +static const TransformFramePlan FRAME_PLAN_306 = {FRAME_CHILDREN_291, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::AnyAllOperator, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_305 = {FRAME_CHILDREN_290, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::AnyOrAll, +static const TransformFramePlan FRAME_PLAN_307 = {FRAME_CHILDREN_292, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::AnyOrAll, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_306 = {FRAME_CHILDREN_291, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::QualifiedOperatorContents, +static const TransformFramePlan FRAME_PLAN_308 = {FRAME_CHILDREN_293, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::QualifiedOperatorContents, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_307 = {FRAME_CHILDREN_292, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::ColIdDot, +static const TransformFramePlan FRAME_PLAN_309 = {FRAME_CHILDREN_294, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::ColIdDot, TransformChildKind::OPTIONAL_REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_308 = {FRAME_CHILDREN_293, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::BitwiseExpressionTail, +static const TransformFramePlan FRAME_PLAN_310 = {FRAME_CHILDREN_295, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::BitwiseExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4089,8 +4105,8 @@ static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::BitwiseExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_309 = {FRAME_CHILDREN_294, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::TildeExpression, +static const TransformFramePlan FRAME_PLAN_311 = {FRAME_CHILDREN_296, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::TildeExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4104,8 +4120,8 @@ static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::TildeExpress false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_310 = {FRAME_CHILDREN_295, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::AdditiveExpression, +static const TransformFramePlan FRAME_PLAN_312 = {FRAME_CHILDREN_297, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::AdditiveExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4119,8 +4135,8 @@ static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::AdditiveExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_311 = {FRAME_CHILDREN_296, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::AdditiveExpressionTail, +static const TransformFramePlan FRAME_PLAN_313 = {FRAME_CHILDREN_298, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::AdditiveExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4134,8 +4150,8 @@ static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::AdditiveExpr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_312 = {FRAME_CHILDREN_297, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::MultiplicativeExpression, +static const TransformFramePlan FRAME_PLAN_314 = {FRAME_CHILDREN_299, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::MultiplicativeExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4149,8 +4165,8 @@ static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::Multiplicati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_313 = {FRAME_CHILDREN_298, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::MultiplicativeExpressionTail, +static const TransformFramePlan FRAME_PLAN_315 = {FRAME_CHILDREN_300, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::MultiplicativeExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4164,8 +4180,8 @@ static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::Multiplicati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_314 = {FRAME_CHILDREN_299, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::ExponentiationExpression, +static const TransformFramePlan FRAME_PLAN_316 = {FRAME_CHILDREN_301, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::ExponentiationExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4179,8 +4195,8 @@ static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::Exponentiati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_315 = {FRAME_CHILDREN_300, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::ExponentiationExpressionTail, +static const TransformFramePlan FRAME_PLAN_317 = {FRAME_CHILDREN_302, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::ExponentiationExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4194,8 +4210,8 @@ static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::Exponentiati false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_316 = {FRAME_CHILDREN_301, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::CollateExpression, +static const TransformFramePlan FRAME_PLAN_318 = {FRAME_CHILDREN_303, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::CollateExpression, TransformChildKind::REQUIRED, 1, 1, @@ -4209,8 +4225,8 @@ static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::CollateExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_317 = {FRAME_CHILDREN_302, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::CollateExpressionTail, +static const TransformFramePlan FRAME_PLAN_319 = {FRAME_CHILDREN_304, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::CollateExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4224,16 +4240,16 @@ static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::CollateExpre false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_318 = {FRAME_CHILDREN_303, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::AtTimeZoneExpression, +static const TransformFramePlan FRAME_PLAN_320 = {FRAME_CHILDREN_305, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::AtTimeZoneExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_319 = {FRAME_CHILDREN_304, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::AtTimeZoneExpressionTail, +static const TransformFramePlan FRAME_PLAN_321 = {FRAME_CHILDREN_306, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::AtTimeZoneExpressionTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -4247,24 +4263,24 @@ static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::AtTimeZoneEx false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_320 = {FRAME_CHILDREN_305, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::UnaryExpression, +static const TransformFramePlan FRAME_PLAN_322 = {FRAME_CHILDREN_307, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::UnaryExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_321 = {FRAME_CHILDREN_306, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::TildeExpression, +static const TransformFramePlan FRAME_PLAN_323 = {FRAME_CHILDREN_308, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_309[] = {{PEGRuleId::TildeExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_322 = {FRAME_CHILDREN_307, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::IndirectionList, +static const TransformFramePlan FRAME_PLAN_324 = {FRAME_CHILDREN_309, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::IndirectionList, TransformChildKind::OPTIONAL, 1, 1, @@ -4278,24 +4294,24 @@ static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::IndirectionL false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_323 = {FRAME_CHILDREN_308, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_309[] = {{PEGRuleId::Indirection, +static const TransformFramePlan FRAME_PLAN_325 = {FRAME_CHILDREN_310, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::Indirection, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_324 = {FRAME_CHILDREN_309, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::MethodExpression, +static const TransformFramePlan FRAME_PLAN_326 = {FRAME_CHILDREN_311, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::MethodExpression, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_325 = {FRAME_CHILDREN_310, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::MethodExpressionArguments, +static const TransformFramePlan FRAME_PLAN_327 = {FRAME_CHILDREN_312, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::MethodExpressionArguments, TransformChildKind::REQUIRED, 1, 1, @@ -4309,16 +4325,16 @@ static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::MethodExpres false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_326 = {FRAME_CHILDREN_311, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::MethodExpressionArgumentList, +static const TransformFramePlan FRAME_PLAN_328 = {FRAME_CHILDREN_313, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::MethodExpressionArgumentList, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_327 = {FRAME_CHILDREN_312, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::IgnoreOrRespectNulls, +static const TransformFramePlan FRAME_PLAN_329 = {FRAME_CHILDREN_314, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::IgnoreOrRespectNulls, TransformChildKind::OPTIONAL, 3, 3, @@ -4346,16 +4362,16 @@ static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::IgnoreOrResp false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_328 = {FRAME_CHILDREN_313, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::SliceBound, +static const TransformFramePlan FRAME_PLAN_330 = {FRAME_CHILDREN_315, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_316[] = {{PEGRuleId::SliceBound, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_329 = {FRAME_CHILDREN_314, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::SliceUpperBound, +static const TransformFramePlan FRAME_PLAN_331 = {FRAME_CHILDREN_316, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_317[] = {{PEGRuleId::SliceUpperBound, TransformChildKind::OPTIONAL, 1, 1, @@ -4369,16 +4385,16 @@ static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::SliceUpperBo false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_330 = {FRAME_CHILDREN_315, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_316[] = {{PEGRuleId::StepSliceBound, +static const TransformFramePlan FRAME_PLAN_332 = {FRAME_CHILDREN_317, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::StepSliceBound, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_331 = {FRAME_CHILDREN_316, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_317[] = {{PEGRuleId::StepSliceBound, +static const TransformFramePlan FRAME_PLAN_333 = {FRAME_CHILDREN_318, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::StepSliceBound, TransformChildKind::OPTIONAL, 1, 1, @@ -4392,32 +4408,32 @@ static const TransformChildPlan FRAME_CHILDREN_317[] = {{PEGRuleId::StepSliceBou false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_332 = {FRAME_CHILDREN_317, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_334 = {FRAME_CHILDREN_319, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_320[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_333 = {FRAME_CHILDREN_318, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_335 = {FRAME_CHILDREN_320, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_321[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_334 = {FRAME_CHILDREN_319, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_320[] = {{PEGRuleId::ExtractArguments, +static const TransformFramePlan FRAME_PLAN_336 = {FRAME_CHILDREN_321, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::ExtractArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_335 = {FRAME_CHILDREN_320, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_321[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_337 = {FRAME_CHILDREN_322, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -4431,8 +4447,8 @@ static const TransformChildPlan FRAME_CHILDREN_321[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_336 = {FRAME_CHILDREN_321, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_338 = {FRAME_CHILDREN_323, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_324[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 1, @@ -4446,24 +4462,24 @@ static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_337 = {FRAME_CHILDREN_322, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::NullIfArguments, +static const TransformFramePlan FRAME_PLAN_339 = {FRAME_CHILDREN_324, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::NullIfArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_338 = {FRAME_CHILDREN_323, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_324[] = {{PEGRuleId::PositionArguments, +static const TransformFramePlan FRAME_PLAN_340 = {FRAME_CHILDREN_325, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::PositionArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_339 = {FRAME_CHILDREN_324, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_341 = {FRAME_CHILDREN_326, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_327[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -4477,32 +4493,32 @@ static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_340 = {FRAME_CHILDREN_325, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_342 = {FRAME_CHILDREN_327, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_328[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_341 = {FRAME_CHILDREN_326, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_327[] = {{PEGRuleId::SubstringArguments, +static const TransformFramePlan FRAME_PLAN_343 = {FRAME_CHILDREN_328, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_329[] = {{PEGRuleId::SubstringArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_342 = {FRAME_CHILDREN_327, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_328[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_344 = {FRAME_CHILDREN_329, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_343 = {FRAME_CHILDREN_328, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_329[] = {{PEGRuleId::SubstringFromFor, +static const TransformFramePlan FRAME_PLAN_345 = {FRAME_CHILDREN_330, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::SubstringFromFor, TransformChildKind::REQUIRED, 1, 1, @@ -4516,8 +4532,8 @@ static const TransformChildPlan FRAME_CHILDREN_329[] = {{PEGRuleId::SubstringFro false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_344 = {FRAME_CHILDREN_329, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::ForExpression, +static const TransformFramePlan FRAME_PLAN_346 = {FRAME_CHILDREN_331, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_332[] = {{PEGRuleId::ForExpression, TransformChildKind::OPTIONAL, 1, 1, @@ -4531,24 +4547,24 @@ static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::ForExpressio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_345 = {FRAME_CHILDREN_330, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::ForExpression, +static const TransformFramePlan FRAME_PLAN_347 = {FRAME_CHILDREN_332, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::ForExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_346 = {FRAME_CHILDREN_331, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_332[] = {{PEGRuleId::TrimArguments, +static const TransformFramePlan FRAME_PLAN_348 = {FRAME_CHILDREN_333, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::TrimArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_347 = {FRAME_CHILDREN_332, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_349 = {FRAME_CHILDREN_334, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 2, @@ -4569,24 +4585,24 @@ static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_348 = {FRAME_CHILDREN_333, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_350 = {FRAME_CHILDREN_335, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_349 = {FRAME_CHILDREN_334, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::OverlayArguments, +static const TransformFramePlan FRAME_PLAN_351 = {FRAME_CHILDREN_336, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::OverlayArguments, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_350 = {FRAME_CHILDREN_335, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::ForExpression, +static const TransformFramePlan FRAME_PLAN_352 = {FRAME_CHILDREN_337, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::ForExpression, TransformChildKind::OPTIONAL, 4, 3, @@ -4614,54 +4630,76 @@ static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::ForExpressio false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_351 = {FRAME_CHILDREN_336, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::ExtractDatePart, +static const TransformFramePlan FRAME_PLAN_353 = {FRAME_CHILDREN_338, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::ExtractDatePart, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_352 = {FRAME_CHILDREN_337, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::ExternalResourceCreationOptions, +static const TransformFramePlan FRAME_PLAN_354 = {FRAME_CHILDREN_339, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::ExternalResourceCreationOptions, TransformChildKind::OPTIONAL, 4, - 1, + 2, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, {PEGRuleId::AttachAlias, TransformChildKind::OPTIONAL, 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExternalResourceType, + TransformChildKind::REQUIRED, + 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_353 = {FRAME_CHILDREN_338, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_355 = {FRAME_CHILDREN_340, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 5, - 1, + 2, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, {PEGRuleId::AttachAlias, TransformChildKind::OPTIONAL, 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExternalResourceType, + TransformChildKind::REQUIRED, + 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_354 = {FRAME_CHILDREN_339, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::ColId, +static const TransformFramePlan FRAME_PLAN_356 = {FRAME_CHILDREN_341, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::ColId, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_355 = {FRAME_CHILDREN_340, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::AttachOptions, +static const TransformFramePlan FRAME_PLAN_357 = {FRAME_CHILDREN_342, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::BareName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_358 = {FRAME_CHILDREN_343, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::AttachOptions, TransformChildKind::OPTIONAL, 4, 2, @@ -4682,8 +4720,8 @@ static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::AttachOption false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_356 = {FRAME_CHILDREN_341, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::AttachOptions, +static const TransformFramePlan FRAME_PLAN_359 = {FRAME_CHILDREN_344, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::AttachOptions, TransformChildKind::OPTIONAL, 3, 1, @@ -4697,16 +4735,23 @@ static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::AttachOption false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_357 = {FRAME_CHILDREN_342, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::ExternalResourceCreationOptions, +static const TransformFramePlan FRAME_PLAN_360 = {FRAME_CHILDREN_345, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_346[] = {{PEGRuleId::ExternalResourceCreationOptions, TransformChildKind::OPTIONAL, 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExternalResourceType, + TransformChildKind::REQUIRED, + 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_358 = {FRAME_CHILDREN_343, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_361 = {FRAME_CHILDREN_346, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 10, 7, @@ -4762,24 +4807,24 @@ static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_359 = {FRAME_CHILDREN_344, 8, 8, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::InsertByName, +static const TransformFramePlan FRAME_PLAN_362 = {FRAME_CHILDREN_347, 8, 8, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::InsertByName, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_360 = {FRAME_CHILDREN_345, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_346[] = {{PEGRuleId::InsertByPosition, +static const TransformFramePlan FRAME_PLAN_363 = {FRAME_CHILDREN_348, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::InsertByPosition, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_361 = {FRAME_CHILDREN_346, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::InsertAlias, +static const TransformFramePlan FRAME_PLAN_364 = {FRAME_CHILDREN_349, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::InsertAlias, TransformChildKind::OPTIONAL, 1, 1, @@ -4793,8 +4838,8 @@ static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::InsertAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_362 = {FRAME_CHILDREN_347, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::OnConflictAction, +static const TransformFramePlan FRAME_PLAN_365 = {FRAME_CHILDREN_350, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::OnConflictAction, TransformChildKind::REQUIRED, 3, 1, @@ -4808,8 +4853,8 @@ static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::OnConflictAc false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_363 = {FRAME_CHILDREN_348, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::WhereClause, +static const TransformFramePlan FRAME_PLAN_366 = {FRAME_CHILDREN_351, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::WhereClause, TransformChildKind::OPTIONAL, 1, 1, @@ -4823,16 +4868,16 @@ static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::WhereClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_364 = {FRAME_CHILDREN_349, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::ConstraintName, +static const TransformFramePlan FRAME_PLAN_367 = {FRAME_CHILDREN_352, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::ConstraintName, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_365 = {FRAME_CHILDREN_350, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::WhereClause, +static const TransformFramePlan FRAME_PLAN_368 = {FRAME_CHILDREN_353, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::WhereClause, TransformChildKind::OPTIONAL, 4, 1, @@ -4846,16 +4891,16 @@ static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::WhereClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_366 = {FRAME_CHILDREN_351, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_369 = {FRAME_CHILDREN_354, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_367 = {FRAME_CHILDREN_352, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::ExtensionAlias, +static const TransformFramePlan FRAME_PLAN_370 = {FRAME_CHILDREN_355, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_356[] = {{PEGRuleId::ExtensionAlias, TransformChildKind::OPTIONAL, 3, 2, @@ -4876,8 +4921,8 @@ static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::ExtensionAli false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_368 = {FRAME_CHILDREN_353, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::VersionNumber, +static const TransformFramePlan FRAME_PLAN_371 = {FRAME_CHILDREN_356, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::VersionNumber, TransformChildKind::OPTIONAL, 5, 3, @@ -4905,17 +4950,17 @@ static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::VersionNumbe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_369 = {FRAME_CHILDREN_354, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::FromSourceName, +static const TransformFramePlan FRAME_PLAN_372 = {FRAME_CHILDREN_357, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::FromSourceName, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_370 = {FRAME_CHILDREN_355, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_373 = {FRAME_CHILDREN_358, 1, 1, false, 0, {}}; static const char *const FRAME_NAMES_9[] = {"Identifier"}; -static const TransformFramePlan FRAME_PLAN_371 = {nullptr, +static const TransformFramePlan FRAME_PLAN_374 = {nullptr, 0, 1, false, @@ -4924,15 +4969,15 @@ static const TransformFramePlan FRAME_PLAN_371 = {nullptr, ParseResultTypeBit(ParseResultType::KEYWORD) | ParseResultTypeBit(ParseResultType::STRING), 0, true, true, 1, FRAME_NAMES_9}}; -static const TransformChildPlan FRAME_CHILDREN_356[] = {{PEGRuleId::IdentifierOrStringLiteral, +static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::IdentifierOrStringLiteral, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_372 = {FRAME_CHILDREN_356, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::RepositoryPublicKey, +static const TransformFramePlan FRAME_PLAN_375 = {FRAME_CHILDREN_359, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::RepositoryPublicKey, TransformChildKind::OPTIONAL, 7, 4, @@ -4967,8 +5012,8 @@ static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::RepositoryPu false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_373 = {FRAME_CHILDREN_357, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::ExtensionRepositoryName, +static const TransformFramePlan FRAME_PLAN_376 = {FRAME_CHILDREN_360, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::ExtensionRepositoryName, TransformChildKind::REQUIRED, 5, 2, @@ -4989,8 +5034,8 @@ static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::ExtensionRep false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_374 = {FRAME_CHILDREN_358, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::ExtensionRepositoryName, +static const TransformFramePlan FRAME_PLAN_377 = {FRAME_CHILDREN_361, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::ExtensionRepositoryName, TransformChildKind::REQUIRED, 4, 1, @@ -5004,23 +5049,8 @@ static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::ExtensionRep false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_375 = {FRAME_CHILDREN_359, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::DotColLabel, - TransformChildKind::REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_376 = {FRAME_CHILDREN_360, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_378 = {FRAME_CHILDREN_362, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_363[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 2, 1, @@ -5034,88 +5064,88 @@ static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::TableAlias, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_377 = {FRAME_CHILDREN_361, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::MatchRecognizeClause, +static const TransformFramePlan FRAME_PLAN_379 = {FRAME_CHILDREN_363, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_364[] = {{PEGRuleId::MatchRecognizeClause, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_378 = {FRAME_CHILDREN_362, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_363[] = {{PEGRuleId::WindowPartition, +static const TransformFramePlan FRAME_PLAN_380 = {FRAME_CHILDREN_364, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::WindowPartition, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_379 = {FRAME_CHILDREN_363, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_364[] = {{PEGRuleId::OrderByClause, +static const TransformFramePlan FRAME_PLAN_381 = {FRAME_CHILDREN_365, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::OrderByClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_380 = {FRAME_CHILDREN_364, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::MeasuresClause, +static const TransformFramePlan FRAME_PLAN_382 = {FRAME_CHILDREN_366, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::MeasuresClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_381 = {FRAME_CHILDREN_365, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::RowsPerMatch, +static const TransformFramePlan FRAME_PLAN_383 = {FRAME_CHILDREN_367, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_368[] = {{PEGRuleId::RowsPerMatch, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_382 = {FRAME_CHILDREN_366, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::AfterMatchSkip, +static const TransformFramePlan FRAME_PLAN_384 = {FRAME_CHILDREN_368, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_369[] = {{PEGRuleId::AfterMatchSkip, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_383 = {FRAME_CHILDREN_367, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_368[] = {{PEGRuleId::PatternClause, +static const TransformFramePlan FRAME_PLAN_385 = {FRAME_CHILDREN_369, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_370[] = {{PEGRuleId::PatternClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_384 = {FRAME_CHILDREN_368, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_369[] = {{PEGRuleId::SubsetClause, +static const TransformFramePlan FRAME_PLAN_386 = {FRAME_CHILDREN_370, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_371[] = {{PEGRuleId::SubsetClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_385 = {FRAME_CHILDREN_369, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_370[] = {{PEGRuleId::DefineClause, +static const TransformFramePlan FRAME_PLAN_387 = {FRAME_CHILDREN_371, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::DefineClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_386 = {FRAME_CHILDREN_370, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_371[] = {{PEGRuleId::MeasuresElement, +static const TransformFramePlan FRAME_PLAN_388 = {FRAME_CHILDREN_372, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::MeasuresElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_387 = {FRAME_CHILDREN_371, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_389 = {FRAME_CHILDREN_373, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 2, 1, @@ -5129,48 +5159,48 @@ static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::ColLabelOrSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_388 = {FRAME_CHILDREN_372, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::AllRowsEmptyMatches, +static const TransformFramePlan FRAME_PLAN_390 = {FRAME_CHILDREN_374, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::AllRowsEmptyMatches, TransformChildKind::OPTIONAL, 4, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_389 = {FRAME_CHILDREN_373, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::AfterMatchSkipTarget, +static const TransformFramePlan FRAME_PLAN_391 = {FRAME_CHILDREN_375, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_376[] = {{PEGRuleId::AfterMatchSkipTarget, TransformChildKind::REQUIRED, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_390 = {FRAME_CHILDREN_374, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_392 = {FRAME_CHILDREN_376, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_377[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_391 = {FRAME_CHILDREN_375, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_376[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_393 = {FRAME_CHILDREN_377, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_378[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_392 = {FRAME_CHILDREN_376, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_377[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_394 = {FRAME_CHILDREN_378, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_393 = {FRAME_CHILDREN_377, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_378[] = {{PEGRuleId::RowPatternAlternative, +static const TransformFramePlan FRAME_PLAN_395 = {FRAME_CHILDREN_379, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::RowPatternAlternative, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5184,24 +5214,24 @@ static const TransformChildPlan FRAME_CHILDREN_378[] = {{PEGRuleId::RowPatternAl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_394 = {FRAME_CHILDREN_378, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::RowPatternTerm, +static const TransformFramePlan FRAME_PLAN_396 = {FRAME_CHILDREN_380, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::RowPatternTerm, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_395 = {FRAME_CHILDREN_379, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::RowPatternFactor, +static const TransformFramePlan FRAME_PLAN_397 = {FRAME_CHILDREN_381, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::RowPatternFactor, TransformChildKind::REPEAT, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_396 = {FRAME_CHILDREN_380, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::RowPatternQuantifier, +static const TransformFramePlan FRAME_PLAN_398 = {FRAME_CHILDREN_382, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::RowPatternQuantifier, TransformChildKind::OPTIONAL, 1, 1, @@ -5215,40 +5245,40 @@ static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::RowPatternQu false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_397 = {FRAME_CHILDREN_381, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_399 = {FRAME_CHILDREN_383, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::RowPattern, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_398 = {FRAME_CHILDREN_382, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_400 = {FRAME_CHILDREN_384, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_399 = {FRAME_CHILDREN_383, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::RowPattern, +static const TransformFramePlan FRAME_PLAN_401 = {FRAME_CHILDREN_385, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::RowPattern, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_400 = {FRAME_CHILDREN_384, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_402 = {FRAME_CHILDREN_386, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_401 = {FRAME_CHILDREN_385, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::QuantifierReluctant, +static const TransformFramePlan FRAME_PLAN_403 = {FRAME_CHILDREN_387, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::QuantifierReluctant, TransformChildKind::OPTIONAL, 1, 1, @@ -5262,24 +5292,24 @@ static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::QuantifierRe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_402 = {FRAME_CHILDREN_386, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::QuantifierBounds, +static const TransformFramePlan FRAME_PLAN_404 = {FRAME_CHILDREN_388, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::QuantifierBounds, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_403 = {FRAME_CHILDREN_387, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::SubsetElement, +static const TransformFramePlan FRAME_PLAN_405 = {FRAME_CHILDREN_389, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_390[] = {{PEGRuleId::SubsetElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_404 = {FRAME_CHILDREN_388, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::ColLabelOrString, +static const TransformFramePlan FRAME_PLAN_406 = {FRAME_CHILDREN_390, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_391[] = {{PEGRuleId::ColLabelOrString, TransformChildKind::LIST, 2, 1, @@ -5293,16 +5323,16 @@ static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::ColLabelOrSt false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_405 = {FRAME_CHILDREN_389, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_390[] = {{PEGRuleId::DefineElement, +static const TransformFramePlan FRAME_PLAN_407 = {FRAME_CHILDREN_391, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::DefineElement, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_406 = {FRAME_CHILDREN_390, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_391[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_408 = {FRAME_CHILDREN_392, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -5316,8 +5346,8 @@ static const TransformChildPlan FRAME_CHILDREN_391[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_407 = {FRAME_CHILDREN_391, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_409 = {FRAME_CHILDREN_393, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 7, 5, @@ -5359,16 +5389,16 @@ static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_408 = {FRAME_CHILDREN_392, 6, 6, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::TableRef, +static const TransformFramePlan FRAME_PLAN_410 = {FRAME_CHILDREN_394, 6, 6, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::TableRef, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_409 = {FRAME_CHILDREN_393, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::MatchedClauseAction, +static const TransformFramePlan FRAME_PLAN_411 = {FRAME_CHILDREN_395, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::MatchedClauseAction, TransformChildKind::REQUIRED, 4, 1, @@ -5382,48 +5412,48 @@ static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::MatchedClaus false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_410 = {FRAME_CHILDREN_394, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::UpdateMatchInfo, +static const TransformFramePlan FRAME_PLAN_412 = {FRAME_CHILDREN_396, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_397[] = {{PEGRuleId::UpdateMatchInfo, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_411 = {FRAME_CHILDREN_395, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::UpdateMatchSetClause, +static const TransformFramePlan FRAME_PLAN_413 = {FRAME_CHILDREN_397, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::UpdateMatchSetClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_412 = {FRAME_CHILDREN_396, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_397[] = {{PEGRuleId::ByNameOrPosition, +static const TransformFramePlan FRAME_PLAN_414 = {FRAME_CHILDREN_398, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::ByNameOrPosition, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_413 = {FRAME_CHILDREN_397, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::InsertMatchInfo, +static const TransformFramePlan FRAME_PLAN_415 = {FRAME_CHILDREN_399, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::InsertMatchInfo, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_414 = {FRAME_CHILDREN_398, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::ByNameOrPosition, +static const TransformFramePlan FRAME_PLAN_416 = {FRAME_CHILDREN_400, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::ByNameOrPosition, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_415 = {FRAME_CHILDREN_399, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_417 = {FRAME_CHILDREN_401, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_402[] = {{PEGRuleId::Expression, TransformChildKind::LIST, 2, 1, @@ -5437,16 +5467,16 @@ static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_416 = {FRAME_CHILDREN_400, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::UpdateMatchSetInfo, +static const TransformFramePlan FRAME_PLAN_418 = {FRAME_CHILDREN_402, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::UpdateMatchSetInfo, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_417 = {FRAME_CHILDREN_401, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_402[] = {{PEGRuleId::MatchedClauseAction, +static const TransformFramePlan FRAME_PLAN_419 = {FRAME_CHILDREN_403, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_404[] = {{PEGRuleId::MatchedClauseAction, TransformChildKind::REQUIRED, 6, 2, @@ -5467,24 +5497,24 @@ static const TransformChildPlan FRAME_CHILDREN_402[] = {{PEGRuleId::MatchedClaus false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_418 = {FRAME_CHILDREN_402, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::PivotColumnList, +static const TransformFramePlan FRAME_PLAN_420 = {FRAME_CHILDREN_404, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::PivotColumnList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_419 = {FRAME_CHILDREN_403, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_404[] = {{PEGRuleId::PivotColumnEntry, +static const TransformFramePlan FRAME_PLAN_421 = {FRAME_CHILDREN_405, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::PivotColumnEntry, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_420 = {FRAME_CHILDREN_404, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::SelectStatementInternal, +static const TransformFramePlan FRAME_PLAN_422 = {FRAME_CHILDREN_406, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_407[] = {{PEGRuleId::SelectStatementInternal, TransformChildKind::REQUIRED, 2, 1, @@ -5498,8 +5528,8 @@ static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::SelectStatem false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_421 = {FRAME_CHILDREN_405, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::OptionalParensNameList, +static const TransformFramePlan FRAME_PLAN_423 = {FRAME_CHILDREN_407, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::OptionalParensNameList, TransformChildKind::REQUIRED, 4, 1, @@ -5513,48 +5543,48 @@ static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::OptionalPare false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_422 = {FRAME_CHILDREN_406, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_407[] = {{PEGRuleId::ColIdOrString, +static const TransformFramePlan FRAME_PLAN_424 = {FRAME_CHILDREN_408, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::ColIdOrString, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_423 = {FRAME_CHILDREN_407, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::ColIdOrString, +static const TransformFramePlan FRAME_PLAN_425 = {FRAME_CHILDREN_409, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::ColIdOrString, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_424 = {FRAME_CHILDREN_408, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::PragmaAssignOrFunction, +static const TransformFramePlan FRAME_PLAN_426 = {FRAME_CHILDREN_410, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::PragmaAssignOrFunction, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_425 = {FRAME_CHILDREN_409, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::VariableList, +static const TransformFramePlan FRAME_PLAN_427 = {FRAME_CHILDREN_411, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::VariableList, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_426 = {FRAME_CHILDREN_410, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::PragmaParameters, +static const TransformFramePlan FRAME_PLAN_428 = {FRAME_CHILDREN_412, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::PragmaParameters, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_427 = {FRAME_CHILDREN_411, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::Statement, +static const TransformFramePlan FRAME_PLAN_429 = {FRAME_CHILDREN_413, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_414[] = {{PEGRuleId::Statement, TransformChildKind::REQUIRED, 4, 2, @@ -5575,11 +5605,11 @@ static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::Statement, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_428 = {FRAME_CHILDREN_412, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_413[] = { +static const TransformFramePlan FRAME_PLAN_430 = {FRAME_CHILDREN_414, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_415[] = { {PEGRuleId::Type, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_429 = {FRAME_CHILDREN_413, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_414[] = {{PEGRuleId::SelectSetOpChainTail, +static const TransformFramePlan FRAME_PLAN_431 = {FRAME_CHILDREN_415, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::SelectSetOpChainTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5593,8 +5623,8 @@ static const TransformChildPlan FRAME_CHILDREN_414[] = {{PEGRuleId::SelectSetOpC false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_430 = {FRAME_CHILDREN_414, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::IntersectChain, +static const TransformFramePlan FRAME_PLAN_432 = {FRAME_CHILDREN_416, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::IntersectChain, TransformChildKind::REQUIRED, 1, 1, @@ -5608,8 +5638,8 @@ static const TransformChildPlan FRAME_CHILDREN_415[] = {{PEGRuleId::IntersectCha false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_431 = {FRAME_CHILDREN_415, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::IntersectChainTail, +static const TransformFramePlan FRAME_PLAN_433 = {FRAME_CHILDREN_417, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::IntersectChainTail, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -5623,8 +5653,8 @@ static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::IntersectCha false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_432 = {FRAME_CHILDREN_416, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::SelectAtom, +static const TransformFramePlan FRAME_PLAN_434 = {FRAME_CHILDREN_418, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::SelectAtom, TransformChildKind::REQUIRED, 1, 1, @@ -5638,16 +5668,16 @@ static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::SelectAtom, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_433 = {FRAME_CHILDREN_417, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::DistinctOrAll, +static const TransformFramePlan FRAME_PLAN_435 = {FRAME_CHILDREN_419, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::DistinctOrAll, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_434 = {FRAME_CHILDREN_418, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::DistinctOrAll, +static const TransformFramePlan FRAME_PLAN_436 = {FRAME_CHILDREN_420, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::DistinctOrAll, TransformChildKind::OPTIONAL, 1, 1, @@ -5661,8 +5691,8 @@ static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::DistinctOrAl false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_435 = {FRAME_CHILDREN_419, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::LimitOffset, +static const TransformFramePlan FRAME_PLAN_437 = {FRAME_CHILDREN_421, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::LimitOffset, TransformChildKind::OPTIONAL, 1, 1, @@ -5676,8 +5706,8 @@ static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::LimitOffset, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_436 = {FRAME_CHILDREN_420, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::OffsetClause, +static const TransformFramePlan FRAME_PLAN_438 = {FRAME_CHILDREN_422, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::OffsetClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5691,8 +5721,8 @@ static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::OffsetClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_437 = {FRAME_CHILDREN_421, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::LimitClause, +static const TransformFramePlan FRAME_PLAN_439 = {FRAME_CHILDREN_423, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::LimitClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5706,8 +5736,8 @@ static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::LimitClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_438 = {FRAME_CHILDREN_422, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::FetchClause, +static const TransformFramePlan FRAME_PLAN_440 = {FRAME_CHILDREN_424, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::FetchClause, TransformChildKind::REQUIRED, 1, 1, @@ -5721,8 +5751,8 @@ static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::FetchClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_439 = {FRAME_CHILDREN_423, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::OffsetClause, +static const TransformFramePlan FRAME_PLAN_441 = {FRAME_CHILDREN_425, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_426[] = {{PEGRuleId::OffsetClause, TransformChildKind::REQUIRED, 1, 1, @@ -5736,32 +5766,32 @@ static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::OffsetClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_440 = {FRAME_CHILDREN_424, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::FetchClause, +static const TransformFramePlan FRAME_PLAN_442 = {FRAME_CHILDREN_426, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::FetchClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_441 = {FRAME_CHILDREN_425, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_426[] = {{PEGRuleId::BaseTableName, +static const TransformFramePlan FRAME_PLAN_443 = {FRAME_CHILDREN_427, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::BaseTableName, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_442 = {FRAME_CHILDREN_426, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::SimpleSelect, +static const TransformFramePlan FRAME_PLAN_444 = {FRAME_CHILDREN_428, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::SimpleSelect, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_443 = {FRAME_CHILDREN_427, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::FromClause, +static const TransformFramePlan FRAME_PLAN_445 = {FRAME_CHILDREN_429, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::FromClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5775,8 +5805,8 @@ static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::FromClause, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_444 = {FRAME_CHILDREN_428, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::SelectClause, +static const TransformFramePlan FRAME_PLAN_446 = {FRAME_CHILDREN_430, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::SelectClause, TransformChildKind::OPTIONAL, 1, 1, @@ -5790,8 +5820,8 @@ static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::SelectClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_445 = {FRAME_CHILDREN_429, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::CTEBody, +static const TransformFramePlan FRAME_PLAN_447 = {FRAME_CHILDREN_431, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::CTEBody, TransformChildKind::REQUIRED, 5, 4, @@ -5826,24 +5856,24 @@ static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::CTEBody, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_446 = {FRAME_CHILDREN_430, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::Statement, +static const TransformFramePlan FRAME_PLAN_448 = {FRAME_CHILDREN_432, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::Statement, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_447 = {FRAME_CHILDREN_431, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_449 = {FRAME_CHILDREN_433, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_448 = {FRAME_CHILDREN_432, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_450 = {FRAME_CHILDREN_434, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::TargetList, TransformChildKind::OPTIONAL, 2, 1, @@ -5857,24 +5887,24 @@ static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::TargetList, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_449 = {FRAME_CHILDREN_433, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::AliasedExpression, +static const TransformFramePlan FRAME_PLAN_451 = {FRAME_CHILDREN_435, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::AliasedExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_450 = {FRAME_CHILDREN_434, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::DistinctOnTargets, +static const TransformFramePlan FRAME_PLAN_452 = {FRAME_CHILDREN_436, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::DistinctOnTargets, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_451 = {FRAME_CHILDREN_435, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_453 = {FRAME_CHILDREN_437, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -5909,8 +5939,8 @@ static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_452 = {FRAME_CHILDREN_436, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_454 = {FRAME_CHILDREN_438, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -5945,8 +5975,8 @@ static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_453 = {FRAME_CHILDREN_437, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_455 = {FRAME_CHILDREN_439, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 3, 3, @@ -5974,8 +6004,8 @@ static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_454 = {FRAME_CHILDREN_438, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_456 = {FRAME_CHILDREN_440, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 3, 3, @@ -6003,8 +6033,8 @@ static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_455 = {FRAME_CHILDREN_439, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::JoinOrPivot, +static const TransformFramePlan FRAME_PLAN_457 = {FRAME_CHILDREN_441, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::JoinOrPivot, TransformChildKind::REPEAT, 1, 1, @@ -6018,8 +6048,8 @@ static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::JoinOrPivot, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_456 = {FRAME_CHILDREN_440, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_458 = {FRAME_CHILDREN_442, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 2, 1, @@ -6033,8 +6063,8 @@ static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::TableAlias, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_457 = {FRAME_CHILDREN_441, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::PivotGroupByList, +static const TransformFramePlan FRAME_PLAN_459 = {FRAME_CHILDREN_443, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::PivotGroupByList, TransformChildKind::OPTIONAL, 3, 2, @@ -6055,16 +6085,16 @@ static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::PivotGroupBy false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_458 = {FRAME_CHILDREN_442, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::OptionalParensNameList, +static const TransformFramePlan FRAME_PLAN_460 = {FRAME_CHILDREN_444, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::OptionalParensNameList, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_459 = {FRAME_CHILDREN_443, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::TableAlias, +static const TransformFramePlan FRAME_PLAN_461 = {FRAME_CHILDREN_445, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::TableAlias, TransformChildKind::OPTIONAL, 3, 2, @@ -6085,8 +6115,8 @@ static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::TableAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_460 = {FRAME_CHILDREN_444, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::UnpivotValueList, +static const TransformFramePlan FRAME_PLAN_462 = {FRAME_CHILDREN_446, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::UnpivotValueList, TransformChildKind::REPEAT, 2, 1, @@ -6100,16 +6130,16 @@ static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::UnpivotValue false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_461 = {FRAME_CHILDREN_445, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::BaseExpression, +static const TransformFramePlan FRAME_PLAN_463 = {FRAME_CHILDREN_447, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::BaseExpression, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_462 = {FRAME_CHILDREN_446, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::PivotValueTarget, +static const TransformFramePlan FRAME_PLAN_464 = {FRAME_CHILDREN_448, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::PivotValueTarget, TransformChildKind::REQUIRED, 2, 1, @@ -6123,16 +6153,16 @@ static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::PivotValueTa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_463 = {FRAME_CHILDREN_447, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::PivotTargetList, +static const TransformFramePlan FRAME_PLAN_465 = {FRAME_CHILDREN_449, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::PivotTargetList, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_464 = {FRAME_CHILDREN_448, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::UnpivotTargetList, +static const TransformFramePlan FRAME_PLAN_466 = {FRAME_CHILDREN_450, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::UnpivotTargetList, TransformChildKind::REQUIRED, 2, 1, @@ -6146,16 +6176,16 @@ static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::UnpivotTarge false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_465 = {FRAME_CHILDREN_449, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::TargetList, +static const TransformFramePlan FRAME_PLAN_467 = {FRAME_CHILDREN_451, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::TargetList, TransformChildKind::REQUIRED, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_466 = {FRAME_CHILDREN_450, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_468 = {FRAME_CHILDREN_452, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 5, 5, @@ -6197,8 +6227,8 @@ static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_467 = {FRAME_CHILDREN_451, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_469 = {FRAME_CHILDREN_453, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 4, 4, @@ -6233,8 +6263,8 @@ static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_468 = {FRAME_CHILDREN_452, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::SchemaQualification, +static const TransformFramePlan FRAME_PLAN_470 = {FRAME_CHILDREN_454, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::SchemaQualification, TransformChildKind::OPTIONAL_REPEAT, 1, 1, @@ -6248,16 +6278,16 @@ static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::SchemaQualif false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_469 = {FRAME_CHILDREN_453, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::FunctionArgument, +static const TransformFramePlan FRAME_PLAN_471 = {FRAME_CHILDREN_455, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::FunctionArgument, TransformChildKind::OPTIONAL_LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_470 = {FRAME_CHILDREN_454, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_472 = {FRAME_CHILDREN_456, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6271,8 +6301,8 @@ static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_471 = {FRAME_CHILDREN_455, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_473 = {FRAME_CHILDREN_457, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 2, @@ -6293,8 +6323,8 @@ static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_472 = {FRAME_CHILDREN_456, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::ColumnAliases, +static const TransformFramePlan FRAME_PLAN_474 = {FRAME_CHILDREN_458, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::ColumnAliases, TransformChildKind::OPTIONAL, 2, 1, @@ -6308,24 +6338,24 @@ static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::ColumnAliase false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_473 = {FRAME_CHILDREN_457, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::ColumnAliases, +static const TransformFramePlan FRAME_PLAN_475 = {FRAME_CHILDREN_459, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::ColumnAliases, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_474 = {FRAME_CHILDREN_458, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::AtSpecifier, +static const TransformFramePlan FRAME_PLAN_476 = {FRAME_CHILDREN_460, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::AtSpecifier, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_475 = {FRAME_CHILDREN_459, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_477 = {FRAME_CHILDREN_461, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6339,8 +6369,8 @@ static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_476 = {FRAME_CHILDREN_460, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_478 = {FRAME_CHILDREN_462, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 8, 4, @@ -6375,8 +6405,8 @@ static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_477 = {FRAME_CHILDREN_461, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_479 = {FRAME_CHILDREN_463, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 8, 4, @@ -6411,16 +6441,16 @@ static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_478 = {FRAME_CHILDREN_462, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::ValuesClause, +static const TransformFramePlan FRAME_PLAN_480 = {FRAME_CHILDREN_464, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::ValuesClause, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_479 = {FRAME_CHILDREN_463, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::WithOrdinality, +static const TransformFramePlan FRAME_PLAN_481 = {FRAME_CHILDREN_465, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::WithOrdinality, TransformChildKind::OPTIONAL, 3, 3, @@ -6448,8 +6478,8 @@ static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::WithOrdinali false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_480 = {FRAME_CHILDREN_464, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::SubqueryReference, +static const TransformFramePlan FRAME_PLAN_482 = {FRAME_CHILDREN_466, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::SubqueryReference, TransformChildKind::REQUIRED, 1, 1, @@ -6463,8 +6493,8 @@ static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::SubqueryRefe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_481 = {FRAME_CHILDREN_465, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_483 = {FRAME_CHILDREN_467, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 2, 2, @@ -6485,8 +6515,8 @@ static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::SampleClause false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_482 = {FRAME_CHILDREN_466, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::SampleClause, +static const TransformFramePlan FRAME_PLAN_484 = {FRAME_CHILDREN_468, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::SampleClause, TransformChildKind::OPTIONAL, 1, 1, @@ -6500,8 +6530,8 @@ static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::SampleClause false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_483 = {FRAME_CHILDREN_467, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::JoinQualifier, +static const TransformFramePlan FRAME_PLAN_485 = {FRAME_CHILDREN_469, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_470[] = {{PEGRuleId::JoinQualifier, TransformChildKind::REQUIRED, 4, 3, @@ -6529,8 +6559,8 @@ static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::JoinQualifie false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_484 = {FRAME_CHILDREN_468, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_469[] = { +static const TransformFramePlan FRAME_PLAN_486 = {FRAME_CHILDREN_470, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_471[] = { {PEGRuleId::JoinQualifier, TransformChildKind::REQUIRED, 4, @@ -6546,8 +6576,8 @@ static const TransformChildPlan FRAME_CHILDREN_469[] = { {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, {PEGRuleId::ColLabel, TransformChildKind::REQUIRED, 2, 0, false, {1, 1, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_485 = {FRAME_CHILDREN_469, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_470[] = {{PEGRuleId::InnerTableRef, +static const TransformFramePlan FRAME_PLAN_487 = {FRAME_CHILDREN_471, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::InnerTableRef, TransformChildKind::REQUIRED, 2, 1, @@ -6561,48 +6591,48 @@ static const TransformChildPlan FRAME_CHILDREN_470[] = {{PEGRuleId::InnerTableRe false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_486 = {FRAME_CHILDREN_470, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_471[] = {{PEGRuleId::UsingColumnName, +static const TransformFramePlan FRAME_PLAN_488 = {FRAME_CHILDREN_472, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::UsingColumnName, TransformChildKind::LIST, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_487 = {FRAME_CHILDREN_471, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::JoinType, +static const TransformFramePlan FRAME_PLAN_489 = {FRAME_CHILDREN_473, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::JoinType, TransformChildKind::OPTIONAL, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_488 = {FRAME_CHILDREN_472, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::GroupByExpressions, +static const TransformFramePlan FRAME_PLAN_490 = {FRAME_CHILDREN_474, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::GroupByExpressions, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_489 = {FRAME_CHILDREN_473, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::SampleEntry, +static const TransformFramePlan FRAME_PLAN_491 = {FRAME_CHILDREN_475, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::SampleEntry, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_490 = {FRAME_CHILDREN_474, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::WindowDefinition, +static const TransformFramePlan FRAME_PLAN_492 = {FRAME_CHILDREN_476, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::WindowDefinition, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_491 = {FRAME_CHILDREN_475, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::SampleProperties, +static const TransformFramePlan FRAME_PLAN_493 = {FRAME_CHILDREN_477, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_478[] = {{PEGRuleId::SampleProperties, TransformChildKind::OPTIONAL, 1, 1, @@ -6616,8 +6646,8 @@ static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::SampleProper false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_492 = {FRAME_CHILDREN_476, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::RepeatableSample, +static const TransformFramePlan FRAME_PLAN_494 = {FRAME_CHILDREN_478, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_479[] = {{PEGRuleId::RepeatableSample, TransformChildKind::OPTIONAL, 2, 2, @@ -6638,8 +6668,8 @@ static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::RepeatableSa false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_493 = {FRAME_CHILDREN_477, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_478[] = { +static const TransformFramePlan FRAME_PLAN_495 = {FRAME_CHILDREN_479, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_480[] = { {PEGRuleId::SampleSeed, TransformChildKind::OPTIONAL, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, 1, 0}}, {PEGRuleId::ColId, TransformChildKind::REQUIRED, @@ -6648,16 +6678,16 @@ static const TransformChildPlan FRAME_CHILDREN_478[] = { false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_494 = {FRAME_CHILDREN_478, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_479[] = {{PEGRuleId::SampleSeed, +static const TransformFramePlan FRAME_PLAN_496 = {FRAME_CHILDREN_480, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_481[] = {{PEGRuleId::SampleSeed, TransformChildKind::REQUIRED, 1, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_495 = {FRAME_CHILDREN_479, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_480[] = {{PEGRuleId::SampleUnit, +static const TransformFramePlan FRAME_PLAN_497 = {FRAME_CHILDREN_481, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::SampleUnit, TransformChildKind::OPTIONAL, 1, 1, @@ -6671,16 +6701,16 @@ static const TransformChildPlan FRAME_CHILDREN_480[] = {{PEGRuleId::SampleUnit, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_496 = {FRAME_CHILDREN_480, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_481[] = {{PEGRuleId::GroupByExpression, +static const TransformFramePlan FRAME_PLAN_498 = {FRAME_CHILDREN_482, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::GroupByExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_497 = {FRAME_CHILDREN_481, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_499 = {FRAME_CHILDREN_483, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_484[] = {{PEGRuleId::Expression, TransformChildKind::OPTIONAL_LIST, 1, 1, @@ -6694,32 +6724,32 @@ static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_498 = {FRAME_CHILDREN_482, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::GroupByExpression, +static const TransformFramePlan FRAME_PLAN_500 = {FRAME_CHILDREN_484, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_485[] = {{PEGRuleId::GroupByExpression, TransformChildKind::LIST, 2, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_499 = {FRAME_CHILDREN_483, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_484[] = {{PEGRuleId::OrderByExpressions, +static const TransformFramePlan FRAME_PLAN_501 = {FRAME_CHILDREN_485, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_486[] = {{PEGRuleId::OrderByExpressions, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_500 = {FRAME_CHILDREN_484, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_485[] = {{PEGRuleId::OrderByExpression, +static const TransformFramePlan FRAME_PLAN_502 = {FRAME_CHILDREN_486, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_487[] = {{PEGRuleId::OrderByExpression, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_501 = {FRAME_CHILDREN_485, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_486[] = {{PEGRuleId::NullsFirstOrLast, +static const TransformFramePlan FRAME_PLAN_503 = {FRAME_CHILDREN_487, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_488[] = {{PEGRuleId::NullsFirstOrLast, TransformChildKind::OPTIONAL, 2, 1, @@ -6733,32 +6763,32 @@ static const TransformChildPlan FRAME_CHILDREN_486[] = {{PEGRuleId::NullsFirstOr false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_502 = {FRAME_CHILDREN_486, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_487[] = {{PEGRuleId::LimitValue, +static const TransformFramePlan FRAME_PLAN_504 = {FRAME_CHILDREN_488, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_489[] = {{PEGRuleId::LimitValue, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_503 = {FRAME_CHILDREN_487, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_488[] = {{PEGRuleId::OffsetValue, +static const TransformFramePlan FRAME_PLAN_505 = {FRAME_CHILDREN_489, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::OffsetValue, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_504 = {FRAME_CHILDREN_488, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_489[] = {{PEGRuleId::FetchValue, +static const TransformFramePlan FRAME_PLAN_506 = {FRAME_CHILDREN_490, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::FetchValue, TransformChildKind::REQUIRED, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_505 = {FRAME_CHILDREN_489, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_507 = {FRAME_CHILDREN_491, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_492[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6772,56 +6802,56 @@ static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_506 = {FRAME_CHILDREN_490, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::ValuesExpressions, +static const TransformFramePlan FRAME_PLAN_508 = {FRAME_CHILDREN_492, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_493[] = {{PEGRuleId::ValuesExpressions, TransformChildKind::LIST, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_507 = {FRAME_CHILDREN_491, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_492[] = {{PEGRuleId::SetAssignmentOrTimeZone, +static const TransformFramePlan FRAME_PLAN_509 = {FRAME_CHILDREN_493, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_494[] = {{PEGRuleId::SetAssignmentOrTimeZone, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_508 = {FRAME_CHILDREN_492, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_493[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_510 = {FRAME_CHILDREN_494, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_495[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_509 = {FRAME_CHILDREN_493, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_494[] = {{PEGRuleId::ResetTarget, +static const TransformFramePlan FRAME_PLAN_511 = {FRAME_CHILDREN_495, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_496[] = {{PEGRuleId::ResetTarget, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_510 = {FRAME_CHILDREN_494, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_495[] = {{PEGRuleId::SettingScope, +static const TransformFramePlan FRAME_PLAN_512 = {FRAME_CHILDREN_496, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::SettingScope, TransformChildKind::OPTIONAL, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_511 = {FRAME_CHILDREN_495, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_496[] = {{PEGRuleId::SetVariableOrSetting, +static const TransformFramePlan FRAME_PLAN_513 = {FRAME_CHILDREN_497, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::SetVariableOrSetting, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_512 = {FRAME_CHILDREN_496, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::SetAssignment, +static const TransformFramePlan FRAME_PLAN_514 = {FRAME_CHILDREN_498, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::SetAssignment, TransformChildKind::REQUIRED, 1, 1, @@ -6835,8 +6865,8 @@ static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::SetAssignmen false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_513 = {FRAME_CHILDREN_497, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::ZoneValue, +static const TransformFramePlan FRAME_PLAN_515 = {FRAME_CHILDREN_499, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::ZoneValue, TransformChildKind::REQUIRED, 3, 1, @@ -6850,48 +6880,48 @@ static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::ZoneValue, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_514 = {FRAME_CHILDREN_498, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::Interval, +static const TransformFramePlan FRAME_PLAN_516 = {FRAME_CHILDREN_500, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_501[] = {{PEGRuleId::Interval, TransformChildKind::OPTIONAL, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_515 = {FRAME_CHILDREN_499, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::VariableScope, +static const TransformFramePlan FRAME_PLAN_517 = {FRAME_CHILDREN_501, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_502[] = {{PEGRuleId::VariableScope, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_516 = {FRAME_CHILDREN_500, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_501[] = {{PEGRuleId::VariableList, +static const TransformFramePlan FRAME_PLAN_518 = {FRAME_CHILDREN_502, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::VariableList, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_517 = {FRAME_CHILDREN_501, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_502[] = {{PEGRuleId::ReadOrWrite, +static const TransformFramePlan FRAME_PLAN_519 = {FRAME_CHILDREN_503, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::ReadOrWrite, TransformChildKind::OPTIONAL, 2, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_518 = {FRAME_CHILDREN_502, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::ReadOnlyOrReadWrite, +static const TransformFramePlan FRAME_PLAN_520 = {FRAME_CHILDREN_504, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::ReadOnlyOrReadWrite, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_519 = {FRAME_CHILDREN_503, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::ReturningClause, +static const TransformFramePlan FRAME_PLAN_521 = {FRAME_CHILDREN_505, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::ReturningClause, TransformChildKind::OPTIONAL, 6, 5, @@ -6933,8 +6963,8 @@ static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::ReturningCla false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_520 = {FRAME_CHILDREN_504, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::UpdateAlias, +static const TransformFramePlan FRAME_PLAN_522 = {FRAME_CHILDREN_506, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_507[] = {{PEGRuleId::UpdateAlias, TransformChildKind::OPTIONAL, 1, 1, @@ -6948,16 +6978,16 @@ static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::UpdateAlias, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_521 = {FRAME_CHILDREN_505, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::UpdateSetClause, +static const TransformFramePlan FRAME_PLAN_523 = {FRAME_CHILDREN_507, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_508[] = {{PEGRuleId::UpdateSetClause, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_522 = {FRAME_CHILDREN_506, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_507[] = {{PEGRuleId::Expression, +static const TransformFramePlan FRAME_PLAN_524 = {FRAME_CHILDREN_508, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_509[] = {{PEGRuleId::Expression, TransformChildKind::REQUIRED, 2, 1, @@ -6971,32 +7001,32 @@ static const TransformChildPlan FRAME_CHILDREN_507[] = {{PEGRuleId::Expression, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_523 = {FRAME_CHILDREN_507, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_508[] = {{PEGRuleId::DotIdentifier, +static const TransformFramePlan FRAME_PLAN_525 = {FRAME_CHILDREN_509, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_510[] = {{PEGRuleId::DotIdentifier, TransformChildKind::OPTIONAL_REPEAT, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_524 = {FRAME_CHILDREN_508, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_509[] = {{PEGRuleId::UseTarget, +static const TransformFramePlan FRAME_PLAN_526 = {FRAME_CHILDREN_510, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_511[] = {{PEGRuleId::UseTarget, TransformChildKind::REQUIRED, 1, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_525 = {FRAME_CHILDREN_509, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_510[] = {{PEGRuleId::DotIdentifier, +static const TransformFramePlan FRAME_PLAN_527 = {FRAME_CHILDREN_511, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_512[] = {{PEGRuleId::DotIdentifier, TransformChildKind::OPTIONAL_REPEAT, 3, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_526 = {FRAME_CHILDREN_510, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_511[] = {{PEGRuleId::AnalyzeTarget, +static const TransformFramePlan FRAME_PLAN_528 = {FRAME_CHILDREN_512, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_513[] = {{PEGRuleId::AnalyzeTarget, TransformChildKind::OPTIONAL, 2, 1, @@ -7010,16 +7040,16 @@ static const TransformChildPlan FRAME_CHILDREN_511[] = {{PEGRuleId::AnalyzeTarge false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_527 = {FRAME_CHILDREN_511, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_512[] = {{PEGRuleId::VacuumOption, +static const TransformFramePlan FRAME_PLAN_529 = {FRAME_CHILDREN_513, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_514[] = {{PEGRuleId::VacuumOption, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_528 = {FRAME_CHILDREN_512, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_513[] = {{PEGRuleId::OptAnalyze, +static const TransformFramePlan FRAME_PLAN_530 = {FRAME_CHILDREN_514, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_515[] = {{PEGRuleId::OptAnalyze, TransformChildKind::OPTIONAL, 3, 3, @@ -7047,15 +7077,15 @@ static const TransformChildPlan FRAME_CHILDREN_513[] = {{PEGRuleId::OptAnalyze, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_529 = {FRAME_CHILDREN_513, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_514[] = {{PEGRuleId::AnalyzeKeyword, +static const TransformFramePlan FRAME_PLAN_531 = {FRAME_CHILDREN_515, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_516[] = {{PEGRuleId::AnalyzeKeyword, TransformChildKind::REQUIRED, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_530 = {FRAME_CHILDREN_514, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_532 = {FRAME_CHILDREN_516, 1, 1, false, 0, {}}; static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"Statement", &PEGTransformerFactory::InitializeStatementTrampoline, @@ -7873,35 +7903,37 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ShowExternalResources", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeShowExternalResourcesTrampoline, &FRAME_PLAN_173}, {"ShowExternalResourcesType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_13}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_174}, + {"ShowExternalResourceTypes", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeShowExternalResourceTypesTrampoline, &FRAME_PLAN_175}, {"ShowDeprecatedSelect", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowDeprecatedSelectTrampoline, &FRAME_PLAN_174}, + &PEGTransformerFactory::FinalizeShowDeprecatedSelectTrampoline, &FRAME_PLAN_176}, {"DescribeSelect", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDescribeSelectTrampoline, &FRAME_PLAN_175}, + &PEGTransformerFactory::FinalizeDescribeSelectTrampoline, &FRAME_PLAN_177}, {"ShowAllTables", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowAllTablesTrampoline, &FRAME_PLAN_176}, + &PEGTransformerFactory::FinalizeShowAllTablesTrampoline, &FRAME_PLAN_178}, {"ShowTables", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowTablesTrampoline, &FRAME_PLAN_177}, + &PEGTransformerFactory::FinalizeShowTablesTrampoline, &FRAME_PLAN_179}, {"ShowByName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowByNameTrampoline, &FRAME_PLAN_178}, + &PEGTransformerFactory::FinalizeShowByNameTrampoline, &FRAME_PLAN_180}, {"DescribeByName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDescribeByNameTrampoline, &FRAME_PLAN_179}, + &PEGTransformerFactory::FinalizeDescribeByNameTrampoline, &FRAME_PLAN_181}, {"DescribeOrSummarize", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ShowTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeShowTargetTrampoline, &FRAME_PLAN_180}, + &PEGTransformerFactory::FinalizeShowTargetTrampoline, &FRAME_PLAN_182}, {"ShowDeprecatedQualifiedTableName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowDeprecatedQualifiedTableNameTrampoline, &FRAME_PLAN_181}, + &PEGTransformerFactory::FinalizeShowDeprecatedQualifiedTableNameTrampoline, &FRAME_PLAN_183}, {"ShowSettingName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeShowSettingNameTrampoline, &FRAME_PLAN_12}, {"DescribeTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DescribeBaseTableName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDescribeBaseTableNameTrampoline, &FRAME_PLAN_182}, + &PEGTransformerFactory::FinalizeDescribeBaseTableNameTrampoline, &FRAME_PLAN_184}, {"DescribeStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDescribeStringLiteralTrampoline, &FRAME_PLAN_12}, {"Summarize", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSummarizeTrampoline, &FRAME_PLAN_183}, + &PEGTransformerFactory::FinalizeSummarizeTrampoline, &FRAME_PLAN_185}, {"SummarizeRule", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSummarizeRuleTrampoline, &FRAME_PLAN_12}, {"ShowOrDescribe", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -7915,37 +7947,37 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DescRule", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDescRuleTrampoline, &FRAME_PLAN_12}, {"DetachStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDetachStatementTrampoline, &FRAME_PLAN_184}, + &PEGTransformerFactory::FinalizeDetachStatementTrampoline, &FRAME_PLAN_186}, {"DropStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropStatementTrampoline, &FRAME_PLAN_185}, + &PEGTransformerFactory::FinalizeDropStatementTrampoline, &FRAME_PLAN_187}, {"DropMemberStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropMemberStatementTrampoline, &FRAME_PLAN_186}, + &PEGTransformerFactory::FinalizeDropMemberStatementTrampoline, &FRAME_PLAN_188}, {"DropMember", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DropTableFunctionMember", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTableFunctionMemberTrampoline, &FRAME_PLAN_187}, + &PEGTransformerFactory::FinalizeDropTableFunctionMemberTrampoline, &FRAME_PLAN_189}, {"DropFunctionMember", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropFunctionMemberTrampoline, &FRAME_PLAN_188}, + &PEGTransformerFactory::FinalizeDropFunctionMemberTrampoline, &FRAME_PLAN_190}, {"DropEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DropTrigger", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTriggerTrampoline, &FRAME_PLAN_189}, + &PEGTransformerFactory::FinalizeDropTriggerTrampoline, &FRAME_PLAN_191}, {"DropTable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTableTrampoline, &FRAME_PLAN_190}, + &PEGTransformerFactory::FinalizeDropTableTrampoline, &FRAME_PLAN_192}, {"DropTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTableFunctionTrampoline, &FRAME_PLAN_191}, + &PEGTransformerFactory::FinalizeDropTableFunctionTrampoline, &FRAME_PLAN_193}, {"DropFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropFunctionTrampoline, &FRAME_PLAN_192}, + &PEGTransformerFactory::FinalizeDropFunctionTrampoline, &FRAME_PLAN_194}, {"DropFunctionSignature", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropFunctionSignatureTrampoline, &FRAME_PLAN_193}, + &PEGTransformerFactory::FinalizeDropFunctionSignatureTrampoline, &FRAME_PLAN_195}, {"DropSignatureType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DropSignatureAnyType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDropSignatureAnyTypeTrampoline, &FRAME_PLAN_12}, {"DropSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSchemaTrampoline, &FRAME_PLAN_194}, + &PEGTransformerFactory::FinalizeDropSchemaTrampoline, &FRAME_PLAN_196}, {"DropIndex", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropIndexTrampoline, &FRAME_PLAN_195}, + &PEGTransformerFactory::FinalizeDropIndexTrampoline, &FRAME_PLAN_197}, {"QualifiedIndexName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"QualifiedIndexNameString", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -7955,13 +7987,13 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CatalogReservedSchemaIndex", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline, &FRAME_PLAN_55}, {"DropSequence", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSequenceTrampoline, &FRAME_PLAN_196}, + &PEGTransformerFactory::FinalizeDropSequenceTrampoline, &FRAME_PLAN_198}, {"DropCollation", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropCollationTrampoline, &FRAME_PLAN_197}, + &PEGTransformerFactory::FinalizeDropCollationTrampoline, &FRAME_PLAN_199}, {"DropType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTypeTrampoline, &FRAME_PLAN_198}, + &PEGTransformerFactory::FinalizeDropTypeTrampoline, &FRAME_PLAN_200}, {"DropSecret", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSecretTrampoline, &FRAME_PLAN_199}, + &PEGTransformerFactory::FinalizeDropSecretTrampoline, &FRAME_PLAN_201}, {"TableOrView", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MaterializedViewEntry", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -7983,21 +8015,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DropSecretStorage", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDropSecretStorageTrampoline, &FRAME_PLAN_12}, {"ExecuteStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExecuteStatementTrampoline, &FRAME_PLAN_200}, + &PEGTransformerFactory::FinalizeExecuteStatementTrampoline, &FRAME_PLAN_202}, {"ExplainStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainStatementTrampoline, &FRAME_PLAN_201}, + &PEGTransformerFactory::FinalizeExplainStatementTrampoline, &FRAME_PLAN_203}, {"ExplainOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionListTrampoline, &FRAME_PLAN_202}, + &PEGTransformerFactory::FinalizeExplainOptionListTrampoline, &FRAME_PLAN_204}, {"ExplainOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionTrampoline, &FRAME_PLAN_203}, + &PEGTransformerFactory::FinalizeExplainOptionTrampoline, &FRAME_PLAN_205}, {"ExplainOptionName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionNameTrampoline, &FRAME_PLAN_204}, + &PEGTransformerFactory::FinalizeExplainOptionNameTrampoline, &FRAME_PLAN_206}, {"ExplainSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline, &FRAME_PLAN_205}, + &PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline, &FRAME_PLAN_207}, {"ExplainableStatements", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExportStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExportStatementTrampoline, &FRAME_PLAN_206}, + &PEGTransformerFactory::FinalizeExportStatementTrampoline, &FRAME_PLAN_208}, {"ExportSource", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExportSourceTrampoline, &FRAME_PLAN_12}, {"ExportOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8007,27 +8039,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ColumnReference", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeColumnReferenceTrampoline, &FRAME_PLAN_1}, {"NestedSchemaTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline, &FRAME_PLAN_207}, + &PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline, &FRAME_PLAN_209}, {"CatalogReservedSchemaTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline, &FRAME_PLAN_208}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline, &FRAME_PLAN_210}, {"SchemaReservedTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline, &FRAME_PLAN_209}, + &PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline, &FRAME_PLAN_211}, {"TableReservedColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline, &FRAME_PLAN_210}, + &PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline, &FRAME_PLAN_212}, {"FunctionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionTrampoline, &FRAME_PLAN_211}, + &PEGTransformerFactory::FinalizeFunctionExpressionTrampoline, &FRAME_PLAN_213}, {"FunctionExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline, &FRAME_PLAN_212}, + &PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline, &FRAME_PLAN_214}, {"FunctionExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline, &FRAME_PLAN_213}, + &PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline, &FRAME_PLAN_215}, {"FunctionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline, &FRAME_PLAN_214}, + &PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline, &FRAME_PLAN_216}, {"FunctionIdentifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"FunctionNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, {"CatalogReservedSchemaFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline, &FRAME_PLAN_215}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline, &FRAME_PLAN_217}, {"SchemaReservedFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSchemaReservedFunctionNameTrampoline, &FRAME_PLAN_56}, {"DistinctOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8037,11 +8069,11 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"AllKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAllKeywordTrampoline, &FRAME_PLAN_12}, {"WithinGroupClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline, &FRAME_PLAN_216}, + &PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline, &FRAME_PLAN_218}, {"FilterClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseTrampoline, &FRAME_PLAN_217}, + &PEGTransformerFactory::FinalizeFilterClauseTrampoline, &FRAME_PLAN_219}, {"FilterClauseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline, &FRAME_PLAN_218}, + &PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline, &FRAME_PLAN_220}, {"FilterClauseContents", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFilterClauseContentsTrampoline, &FRAME_PLAN_21}, {"IgnoreOrRespectNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8063,9 +8095,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FalseLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFalseLiteralTrampoline, &FRAME_PLAN_12}, {"CastExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCastExpressionTrampoline, &FRAME_PLAN_219}, + &PEGTransformerFactory::FinalizeCastExpressionTrampoline, &FRAME_PLAN_221}, {"CastArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCastArgumentsTrampoline, &FRAME_PLAN_220}, + &PEGTransformerFactory::FinalizeCastArgumentsTrampoline, &FRAME_PLAN_222}, {"CastOrTryCast", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CastKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8075,45 +8107,45 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ColIdDot", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeColIdDotTrampoline, &FRAME_PLAN_83}, {"StarExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStarExpressionTrampoline, &FRAME_PLAN_221}, + &PEGTransformerFactory::FinalizeStarExpressionTrampoline, &FRAME_PLAN_223}, {"StarQualifierList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStarQualifierListTrampoline, &FRAME_PLAN_222}, + &PEGTransformerFactory::FinalizeStarQualifierListTrampoline, &FRAME_PLAN_224}, {"ExcludeList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeListTrampoline, &FRAME_PLAN_223}, + &PEGTransformerFactory::FinalizeExcludeListTrampoline, &FRAME_PLAN_225}, {"ExcludeNames", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExcludeNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameListTrampoline, &FRAME_PLAN_224}, + &PEGTransformerFactory::FinalizeExcludeNameListTrampoline, &FRAME_PLAN_226}, {"ExcludeNameSingle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline, &FRAME_PLAN_225}, + &PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline, &FRAME_PLAN_227}, {"ExcludeName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExcludeDottedName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline, &FRAME_PLAN_226}, + &PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline, &FRAME_PLAN_228}, {"ExcludeColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExcludeColumnNameTrampoline, &FRAME_PLAN_38}, {"ReplaceList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceListTrampoline, &FRAME_PLAN_227}, + &PEGTransformerFactory::FinalizeReplaceListTrampoline, &FRAME_PLAN_229}, {"ReplaceEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ReplaceEntrySingle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline, &FRAME_PLAN_228}, + &PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline, &FRAME_PLAN_230}, {"ReplaceEntryList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntryListTrampoline, &FRAME_PLAN_229}, + &PEGTransformerFactory::FinalizeReplaceEntryListTrampoline, &FRAME_PLAN_231}, {"ReplaceEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntryTrampoline, &FRAME_PLAN_230}, + &PEGTransformerFactory::FinalizeReplaceEntryTrampoline, &FRAME_PLAN_232}, {"RenameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameListTrampoline, &FRAME_PLAN_231}, + &PEGTransformerFactory::FinalizeRenameListTrampoline, &FRAME_PLAN_233}, {"RenameEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RenameEntryList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameEntryListTrampoline, &FRAME_PLAN_232}, + &PEGTransformerFactory::FinalizeRenameEntryListTrampoline, &FRAME_PLAN_234}, {"SingleRenameEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline, &FRAME_PLAN_233}, + &PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline, &FRAME_PLAN_235}, {"RenameEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameEntryTrampoline, &FRAME_PLAN_225}, + &PEGTransformerFactory::FinalizeRenameEntryTrampoline, &FRAME_PLAN_227}, {"SubqueryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline, &FRAME_PLAN_234}, + &PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline, &FRAME_PLAN_236}, {"SubqueryNot", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSubqueryNotTrampoline, &FRAME_PLAN_12}, {"SubqueryExists", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8121,29 +8153,29 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CaseExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SimpleCaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleCaseExpressionTrampoline, &FRAME_PLAN_235}, + &PEGTransformerFactory::FinalizeSimpleCaseExpressionTrampoline, &FRAME_PLAN_237}, {"SearchedCaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSearchedCaseExpressionTrampoline, &FRAME_PLAN_236}, + &PEGTransformerFactory::FinalizeSearchedCaseExpressionTrampoline, &FRAME_PLAN_238}, {"SimpleCaseWhenThen", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleCaseWhenThenTrampoline, &FRAME_PLAN_237}, + &PEGTransformerFactory::FinalizeSimpleCaseWhenThenTrampoline, &FRAME_PLAN_239}, {"SimpleCaseWhenOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SimpleCaseWhenEquals", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSimpleCaseWhenEqualsTrampoline, &FRAME_PLAN_31}, {"CaseWhenThen", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCaseWhenThenTrampoline, &FRAME_PLAN_238}, + &PEGTransformerFactory::FinalizeCaseWhenThenTrampoline, &FRAME_PLAN_240}, {"CaseElse", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCaseElseTrampoline, &FRAME_PLAN_21}, {"TypeLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTypeLiteralTrampoline, &FRAME_PLAN_162}, {"IntervalLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntervalLiteralTrampoline, &FRAME_PLAN_239}, + &PEGTransformerFactory::FinalizeIntervalLiteralTrampoline, &FRAME_PLAN_241}, {"IntervalParameter", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IntervalStringParameter", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIntervalStringParameterTrampoline, &FRAME_PLAN_12}, {"FrameClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameClauseTrampoline, &FRAME_PLAN_240}, + &PEGTransformerFactory::FinalizeFrameClauseTrampoline, &FRAME_PLAN_242}, {"Framing", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeFramingTrampoline, &FRAME_PLAN_19}, {"RowsFraming", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8155,15 +8187,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FrameExtent", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SingleFrameExtent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline, &FRAME_PLAN_241}, + &PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline, &FRAME_PLAN_243}, {"BetweenFrameExtent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline, &FRAME_PLAN_242}, + &PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline, &FRAME_PLAN_244}, {"FrameBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"FrameUnbounded", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameUnboundedTrampoline, &FRAME_PLAN_243}, + &PEGTransformerFactory::FinalizeFrameUnboundedTrampoline, &FRAME_PLAN_245}, {"FrameExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameExpressionTrampoline, &FRAME_PLAN_244}, + &PEGTransformerFactory::FinalizeFrameExpressionTrampoline, &FRAME_PLAN_246}, {"FrameCurrentRow", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFrameCurrentRowTrampoline, &FRAME_PLAN_12}, {"PrecedingOrFollowing", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -8173,7 +8205,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FollowingFrame", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFollowingFrameTrampoline, &FRAME_PLAN_12}, {"WindowExcludeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline, &FRAME_PLAN_245}, + &PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline, &FRAME_PLAN_247}, {"WindowExcludeElement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExcludeCurrentRow", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8195,37 +8227,37 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WindowFrameDefinition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"WindowFrameNameContentsParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline, &FRAME_PLAN_246}, + &PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline, &FRAME_PLAN_248}, {"WindowFrameNameContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline, &FRAME_PLAN_247}, + &PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline, &FRAME_PLAN_249}, {"WindowFrameContentsParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline, &FRAME_PLAN_248}, + &PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline, &FRAME_PLAN_250}, {"WindowFrameContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline, &FRAME_PLAN_249}, + &PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline, &FRAME_PLAN_251}, {"BaseWindowName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBaseWindowNameTrampoline, &FRAME_PLAN_12}, {"WindowPartition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowPartitionTrampoline, &FRAME_PLAN_250}, + &PEGTransformerFactory::FinalizeWindowPartitionTrampoline, &FRAME_PLAN_252}, {"ListExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ArrayBoundedListExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline, &FRAME_PLAN_251}, + &PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline, &FRAME_PLAN_253}, {"ArrayParensSelect", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeArrayParensSelectTrampoline, &FRAME_PLAN_163}, {"BoundedListExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline, &FRAME_PLAN_252}, + &PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline, &FRAME_PLAN_254}, {"StructExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStructExpressionTrampoline, &FRAME_PLAN_253}, + &PEGTransformerFactory::FinalizeStructExpressionTrampoline, &FRAME_PLAN_255}, {"StructField", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStructFieldTrampoline, &FRAME_PLAN_254}, + &PEGTransformerFactory::FinalizeStructFieldTrampoline, &FRAME_PLAN_256}, {"MapExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapExpressionTrampoline, &FRAME_PLAN_255}, + &PEGTransformerFactory::FinalizeMapExpressionTrampoline, &FRAME_PLAN_257}, {"MapStructExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapStructExpressionTrampoline, &FRAME_PLAN_256}, + &PEGTransformerFactory::FinalizeMapStructExpressionTrampoline, &FRAME_PLAN_258}, {"MapStructField", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapStructFieldTrampoline, &FRAME_PLAN_257}, + &PEGTransformerFactory::FinalizeMapStructFieldTrampoline, &FRAME_PLAN_259}, {"GroupingExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingExpressionTrampoline, &FRAME_PLAN_258}, + &PEGTransformerFactory::FinalizeGroupingExpressionTrampoline, &FRAME_PLAN_260}, {"GroupingOrGroupingId", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"GroupingKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8247,61 +8279,61 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DefaultExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDefaultExpressionTrampoline, &FRAME_PLAN_12}, {"ListComprehensionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline, &FRAME_PLAN_259}, + &PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline, &FRAME_PLAN_261}, {"ListComprehensionFilter", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeListComprehensionFilterTrampoline, &FRAME_PLAN_21}, {"ParensExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParensExpressionTrampoline, &FRAME_PLAN_260}, + &PEGTransformerFactory::FinalizeParensExpressionTrampoline, &FRAME_PLAN_262}, {"MeasureSemanticsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline, &FRAME_PLAN_261}, + &PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline, &FRAME_PLAN_263}, {"SingleExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"Expression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_262}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_264}, {"ColumnDefaultExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline, &FRAME_PLAN_263}, + &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline, &FRAME_PLAN_265}, {"LogicalOrExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_264}, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_266}, {"LogicalOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_265}, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_267}, {"ColDefOrExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_266}, + &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_268}, {"ColDefOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_267}, + &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_269}, {"LogicalAndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_268}, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_270}, {"LogicalAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_269}, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_271}, {"ColDefAndExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_270}, + &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_272}, {"ColDefAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_271}, + &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_273}, {"LogicalNotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_272}, + &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_274}, {"NotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_273}, + &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_275}, {"NotKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotKeywordTrampoline, &FRAME_PLAN_12}, {"IsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_274}, + &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_276}, {"IsExpressionContinuation", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_275}, + &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_277}, {"IsExpressionTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IsTestTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_276}, + &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_278}, {"IsDistinctTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_277}, + &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_279}, {"IsComparisonTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_278}, + &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_280}, {"IsOtherOperatorTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_279}, + &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_281}, {"IsCastTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_280}, + &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_282}, {"IsTest", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IsLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_281}, + &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_283}, {"IsLiteralValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UnknownLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8313,23 +8345,23 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NotNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotNullOperatorTrampoline, &FRAME_PLAN_12}, {"IsNull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsNullTrampoline, - &FRAME_PLAN_282}, + &FRAME_PLAN_284}, {"IsNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsNullOperatorTrampoline, &FRAME_PLAN_12}, {"IsDistinctFromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_283}, + &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_285}, {"IsDistinctFromTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_284}, + &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_286}, {"IsDistinctFromOp", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsDistinctFromOpTrampoline, &FRAME_PLAN_12}, {"ComparisonExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_285}, + &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_287}, {"ComparisonExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_286}, + &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_288}, {"ComparisonOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NotComparisonOperand", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_287}, + &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_289}, {"ComparisonOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OperatorEqual", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8345,17 +8377,17 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OperatorGreaterThanEquals", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOperatorGreaterThanEqualsTrampoline, &FRAME_PLAN_12}, {"BetweenInLikeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_288}, + &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_290}, {"InPredicate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_289}, + &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_291}, {"BetweenLikeOp", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_290}, + &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_292}, {"BetweenLikeOpExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"LikeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_291}, + &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_293}, {"EscapeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_292}, + &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_294}, {"LikeVariations", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeLikeVariationsTrampoline, &FRAME_PLAN_19}, {"LikeToken", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8379,43 +8411,43 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NotSimilarToOp", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNotSimilarToOpTrampoline, &FRAME_PLAN_12}, {"InClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_293}, + &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_295}, {"InExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InContainsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_294}, + &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_296}, {"InExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_295}, + &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_297}, {"InSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_296}, + &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_298}, {"BetweenClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_297}, + &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_299}, {"OtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_298}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_300}, {"InfixOtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_299}, + &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_301}, {"OtherOperatorTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"AnyAllSubqueryTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_300}, + &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_302}, {"OtherOperatorExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_301}, + &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_303}, {"SingleArrowTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleArrowTailTrampoline, &FRAME_PLAN_302}, + &PEGTransformerFactory::FinalizeSingleArrowTailTrampoline, &FRAME_PLAN_304}, {"SingleArrowBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ArrowChainBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrowChainBodyTrampoline, &FRAME_PLAN_303}, + &PEGTransformerFactory::FinalizeArrowChainBodyTrampoline, &FRAME_PLAN_305}, {"ArrowChainTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DoubleArrowTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline, &FRAME_PLAN_304}, + &PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline, &FRAME_PLAN_306}, {"ArrowFullBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrowFullBodyTrampoline, &FRAME_PLAN_262}, + &PEGTransformerFactory::FinalizeArrowFullBodyTrampoline, &FRAME_PLAN_264}, {"OtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"AnyAllParsedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_305}, + &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_307}, {"NamedOtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeNamedOtherOperatorTrampoline, &FRAME_PLAN_54}, {"OperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8423,7 +8455,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"AnyOperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAnyOperatorLiteralTrampoline, &FRAME_PLAN_12}, {"AnyAllOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_306}, + &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_308}, {"AnyOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubqueryAny", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8431,49 +8463,49 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SubqueryAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSubqueryAllTrampoline, &FRAME_PLAN_12}, {"QualifiedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_307}, + &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_309}, {"QualifiedOperatorContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_308}, + &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_310}, {"BitwiseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_309}, + &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_311}, {"BitwiseExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_310}, + &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_312}, {"BitOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBitOperatorTrampoline, &FRAME_PLAN_12}, {"TildeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_311}, + &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_313}, {"AdditiveExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_312}, + &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_314}, {"AdditiveExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_313}, + &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_315}, {"Term", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTermTrampoline, &FRAME_PLAN_12}, {"MultiplicativeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_314}, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_316}, {"MultiplicativeExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_315}, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_317}, {"Factor", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFactorTrampoline, &FRAME_PLAN_12}, {"ExponentiationExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_316}, + &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_318}, {"ExponentiationExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_317}, + &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_319}, {"ExponentOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExponentOperatorTrampoline, &FRAME_PLAN_12}, {"CollateExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_318}, + &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_320}, {"CollateExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_319}, + &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_321}, {"AtTimeZoneExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_320}, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_322}, {"AtTimeZoneExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_321}, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_323}, {"UnaryExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PrefixExpression", &PEGTransformerFactory::InitializePrefixExpressionTrampoline, &PEGTransformerFactory::FinalizePrefixExpressionTrampoline, nullptr}, {"CustomPrefixExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_322}, + &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_324}, {"PrefixOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePrefixOperatorTrampoline, &FRAME_PLAN_19}, {"MinusPrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8483,9 +8515,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TildePrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTildePrefixOperatorTrampoline, &FRAME_PLAN_12}, {"BaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_323}, + &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_325}, {"IndirectionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_324}, + &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_326}, {"Indirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CastOperator", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8493,27 +8525,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"DotOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DotMethodOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_325}, + &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_327}, {"DotColumnOperator", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDotColumnOperatorTrampoline, &FRAME_PLAN_147}, {"MethodExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_326}, + &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_328}, {"MethodExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_327}, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_329}, {"MethodExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_328}, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_330}, {"MethodFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline, &FRAME_PLAN_214}, + &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline, &FRAME_PLAN_216}, {"SliceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_329}, + &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_331}, {"SliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_330}, + &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_332}, {"SliceUpperBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MinusStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_331}, + &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_333}, {"EndStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_332}, + &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_334}, {"EndSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeEndSliceBoundTrampoline, &FRAME_PLAN_66}, {"StepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8523,47 +8555,47 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SpecialFunctionExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CoalesceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_333}, + &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_335}, {"UnpackExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUnpackExpressionTrampoline, &FRAME_PLAN_134}, {"TryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTryExpressionTrampoline, &FRAME_PLAN_134}, {"ColumnsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_334}, + &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_336}, {"ExtractExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_335}, + &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_337}, {"ExtractArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_336}, + &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_338}, {"LambdaExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_337}, + &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_339}, {"NullIfExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_338}, + &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_340}, {"NullIfArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline, &FRAME_PLAN_257}, + &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline, &FRAME_PLAN_259}, {"PositionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_339}, + &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_341}, {"PositionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_340}, + &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_342}, {"RowExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_341}, + &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_343}, {"SubstringExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_342}, + &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_344}, {"SubstringArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubstringExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_343}, + &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_345}, {"SubstringParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_344}, + &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_346}, {"SubstringFromFor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SubstringFromOptionalFor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_345}, + &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_347}, {"SubstringFor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_346}, + &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_348}, {"TrimExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_347}, + &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_349}, {"TrimArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_348}, + &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_350}, {"TrimDirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeTrimDirectionTrampoline, &FRAME_PLAN_19}, {"TrimBoth", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8573,23 +8605,23 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TrimTrailing", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTrimTrailingTrampoline, &FRAME_PLAN_12}, {"TrimSource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_349}, + &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_351}, {"OverlayExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_350}, + &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_352}, {"OverlayArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OverlayParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_351}, + &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_353}, {"FromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFromExpressionTrampoline, &FRAME_PLAN_21}, {"ForExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeForExpressionTrampoline, &FRAME_PLAN_21}, {"OverlayExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_343}, + &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_345}, {"ExtractArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExtractDatePartArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_352}, + &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_354}, {"ExtractIdentifierArgument", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExtractIdentifierArgumentTrampoline, &FRAME_PLAN_12}, {"ExtractStringArgument", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8599,25 +8631,31 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ExternalResourceStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CreateExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_353}, + &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_355}, {"RegisterExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_354}, + &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_356}, {"DestroyExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_355}, + &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_357}, + {"ExternalResourceType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeExternalResourceTypeTrampoline, &FRAME_PLAN_19}, + {"ExternalResourceTypeName", &PEGTransformerFactory::InitializePlannedTrampoline, + &PEGTransformerFactory::FinalizeExternalResourceTypeNameTrampoline, &FRAME_PLAN_358}, + {"BareName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeBareNameTrampoline, &FRAME_PLAN_149}, {"ExternalResourceCreationOptions", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_33}, {"AttachToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_356}, + &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_359}, {"ConnectToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_357}, + &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_360}, {"ExternalResourceSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ExternalResourceCreateClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_358}, + &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_361}, {"ExternalResourceReferenceClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExternalResourceReferenceClauseTrampoline, &FRAME_PLAN_32}, {"InsertStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_359}, + &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_362}, {"OrAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertOrReplace", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8627,15 +8665,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ByNameOrPosition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertByNameOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_360}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_363}, {"InsertByPositionOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_361}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_364}, {"InsertByName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertByNameTrampoline, &FRAME_PLAN_12}, {"InsertByPosition", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertByPositionTrampoline, &FRAME_PLAN_12}, {"InsertTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_362}, + &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_365}, {"InsertAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertAliasTrampoline, &FRAME_PLAN_12}, {"ColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8645,31 +8683,31 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"InsertValues", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectInsertValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline, &FRAME_PLAN_205}, + &PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline, &FRAME_PLAN_207}, {"DefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDefaultValuesTrampoline, &FRAME_PLAN_12}, {"OnConflictClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_363}, + &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_366}, {"OnConflictTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnConflictExpressionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_364}, + &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_367}, {"OnConflictIndexTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_365}, + &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_368}, {"OnConflictAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnConflictUpdate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_366}, + &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_369}, {"OnConflictNothing", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOnConflictNothingTrampoline, &FRAME_PLAN_12}, {"ReturningClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_367}, + &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_370}, {"LoadStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_368}, + &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_371}, {"ExtensionAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExtensionAliasTrampoline, &FRAME_PLAN_12}, {"InstallStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_369}, + &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_372}, {"InstallAndLoad", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInstallAndLoadTrampoline, &FRAME_PLAN_12}, {"UpdateExtensionsStatement", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8677,57 +8715,55 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FromSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"FromSourceIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline, &FRAME_PLAN_370}, + &PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline, &FRAME_PLAN_373}, {"FromSourceString", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFromSourceStringTrampoline, &FRAME_PLAN_12}, {"FromSourceName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeFromSourceNameTrampoline, &FRAME_PLAN_371}, + &PEGTransformerFactory::FinalizeFromSourceNameTrampoline, &FRAME_PLAN_374}, {"VersionNumber", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_372}, + &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_375}, {"ExtensionRepositoryStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CreateExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, &FRAME_PLAN_373}, + &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, &FRAME_PLAN_376}, {"RepositoryPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRepositoryPrefixTrampoline, &FRAME_PLAN_12}, {"RepositoryPublicKey", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline, &FRAME_PLAN_12}, {"CreateExtensionRepositoryFromHostStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExtensionRepositoryFromHostStmtTrampoline, &FRAME_PLAN_374}, + &PEGTransformerFactory::FinalizeCreateExtensionRepositoryFromHostStmtTrampoline, &FRAME_PLAN_377}, {"DropExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_375}, + &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_378}, {"ExtensionRepositoryName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeExtensionRepositoryNameTrampoline, &FRAME_PLAN_149}, - {"ExtensionRepositoryHostName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtensionRepositoryHostNameTrampoline, &FRAME_PLAN_376}, {"TableMatchRecognizeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_377}, + &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_379}, {"MatchRecognizeBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_378}, + &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_380}, {"MatchRecognizeClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MRPartition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_379}, + &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_381}, {"MROrderBy", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_380}, + &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_382}, {"MRMeasures", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_381}, + &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_383}, {"MRRows", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRRowsTrampoline, - &FRAME_PLAN_382}, + &FRAME_PLAN_384}, {"MRSkip", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRSkipTrampoline, - &FRAME_PLAN_383}, + &FRAME_PLAN_385}, {"MRPattern", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_384}, + &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_386}, {"MRSubset", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_385}, + &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_387}, {"MRDefineAuto", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRDefineAutoTrampoline, &FRAME_PLAN_12}, {"MRDefine", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_386}, + &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_388}, {"MeasuresClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_387}, + &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_389}, {"MeasuresElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_388}, + &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_390}, {"MeasureSemantics", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RunningSemantics", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8739,7 +8775,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OneRowPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOneRowPerMatchTrampoline, &FRAME_PLAN_12}, {"AllRowsPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_389}, + &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_391}, {"AllRowsEmptyMatches", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ShowEmptyMatches", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8749,7 +8785,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WithUnmatchedRows", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWithUnmatchedRowsTrampoline, &FRAME_PLAN_12}, {"AfterMatchSkip", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_390}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_392}, {"AfterMatchSkipTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SkipToNextRow", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8757,25 +8793,25 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SkipPastLastRow", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSkipPastLastRowTrampoline, &FRAME_PLAN_12}, {"SkipToFirstVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_391}, + &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_393}, {"SkipToLastVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_391}, + &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_393}, {"SkipToVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_392}, + &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_394}, {"PatternClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_393}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_395}, {"RowPattern", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_394}, + &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_396}, {"RowPatternAlternative", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_395}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_397}, {"RowPatternTerm", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_396}, + &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_398}, {"RowPatternFactor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_397}, + &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_399}, {"RowPatternPrimary", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"RowPatternPermute", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_398}, + &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_400}, {"RowPatternAnchor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PatternStart", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8783,15 +8819,15 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"PatternEnd", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePatternEndTrampoline, &FRAME_PLAN_12}, {"RowPatternGroup", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_399}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_401}, {"RowPatternEmpty", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRowPatternEmptyTrampoline, &FRAME_PLAN_12}, {"RowPatternExclusion", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_400}, + &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_402}, {"RowPatternLabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_401}, + &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_403}, {"RowPatternQuantifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_402}, + &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_404}, {"RowPatternQuantifierKind", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"QuantifierReluctant", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8803,7 +8839,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"QuantifierOptional", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQuantifierOptionalTrampoline, &FRAME_PLAN_12}, {"QuantifierRange", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_403}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_405}, {"QuantifierBounds", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"QuantifierMinMax", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8815,55 +8851,55 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"QuantifierExact", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQuantifierExactTrampoline, &FRAME_PLAN_12}, {"SubsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_404}, + &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_406}, {"SubsetElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_405}, + &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_407}, {"DefineClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_406}, + &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_408}, {"DefineElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_407}, + &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_409}, {"MergeIntoStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_408}, + &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_410}, {"MergeIntoUsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_409}, + &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_411}, {"MergeMatch", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"MatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_410}, + &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_412}, {"MatchedClauseAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_411}, + &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_413}, {"UpdateMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateMatchSetAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_412}, + &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_414}, {"UpdateByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_413}, + &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_415}, {"DeleteMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDeleteMatchClauseTrampoline, &FRAME_PLAN_12}, {"InsertMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_414}, + &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_416}, {"InsertMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"InsertDefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeInsertDefaultValuesTrampoline, &FRAME_PLAN_12}, {"InsertByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_415}, + &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_417}, {"InsertValuesList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_416}, + &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_418}, {"DoNothingMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDoNothingMatchClauseTrampoline, &FRAME_PLAN_12}, {"ErrorMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeErrorMatchClauseTrampoline, &FRAME_PLAN_66}, {"UpdateMatchSetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_417}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_419}, {"UpdateMatchSetInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeUpdateMatchSetInfoTrampoline, &FRAME_PLAN_80}, {"AndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAndExpressionTrampoline, &FRAME_PLAN_21}, {"NotMatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_418}, + &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_420}, {"BySourceOrTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BySource", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8873,27 +8909,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"PivotStatement", &PEGTransformerFactory::InitializePivotStatementTrampoline, &PEGTransformerFactory::FinalizePivotStatementTrampoline, nullptr}, {"PivotOn", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotOnTrampoline, - &FRAME_PLAN_419}, + &FRAME_PLAN_421}, {"PivotUsing", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_367}, + &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_370}, {"PivotColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_420}, + &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_422}, {"PivotColumnEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PivotColumnExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotColumnExpressionTrampoline, &FRAME_PLAN_31}, {"PivotColumnSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_421}, + &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_423}, {"UnpivotStatement", &PEGTransformerFactory::InitializeUnpivotStatementTrampoline, &PEGTransformerFactory::FinalizeUnpivotStatementTrampoline, nullptr}, {"IntoNameValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_422}, + &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_424}, {"OptionalParensNameList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ParenthesizedNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_423}, + &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_425}, {"BareNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_424}, + &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_426}, {"IncludeOrExcludeNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"IncludeNulls", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8905,41 +8941,41 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"UnpivotHeaderSingle", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUnpivotHeaderSingleTrampoline, &FRAME_PLAN_38}, {"UnpivotHeaderList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_423}, + &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_425}, {"PragmaStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_425}, + &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_427}, {"PragmaAssignOrFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PragmaAssign", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_426}, + &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_428}, {"PragmaFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_427}, + &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_429}, {"PragmaParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_295}, + &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_297}, {"PrepareStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_428}, + &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_430}, {"TypeList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_429}, + &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_431}, {"SelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectStatementTrampoline, &FRAME_PLAN_205}, + &PEGTransformerFactory::FinalizeSelectStatementTrampoline, &FRAME_PLAN_207}, {"SelectStatementInternal", &PEGTransformerFactory::InitializeSelectStatementInternalTrampoline, &PEGTransformerFactory::FinalizeSelectStatementInternalTrampoline, nullptr}, {"SelectSetOpChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_430}, + &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_432}, {"SelectSetOpChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_431}, + &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_433}, {"IntersectChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_432}, + &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_434}, {"IntersectChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_433}, + &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_435}, {"SetIntersectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_434}, + &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_436}, {"SelectAtom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_296}, + &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_298}, {"SetopClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_435}, + &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_437}, {"SetopType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetopUnion", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -8949,107 +8985,107 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SelectStatementType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResultModifiers", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_436}, + &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_438}, {"LimitOffset", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"LimitOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_437}, + &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_439}, {"OffsetLimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_438}, + &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_440}, {"OffsetFetchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_439}, + &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_441}, {"FetchOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_440}, + &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_442}, {"FetchOnlyClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_441}, + &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_443}, {"TableStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_442}, + &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_444}, {"OptionalParensSimpleSelect", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SimpleSelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_443}, + &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_445}, {"SimpleSelect", &PEGTransformerFactory::InitializeSimpleSelectTrampoline, &PEGTransformerFactory::FinalizeSimpleSelectTrampoline, nullptr}, {"SelectFrom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SelectFromClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_444}, + &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_446}, {"FromSelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_445}, + &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_447}, {"WithStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_446}, + &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_448}, {"CTEBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CTESelectBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_296}, + &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_298}, {"CTEDMLBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_447}, + &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_449}, {"UsingKey", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_448}, + &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_450}, {"Materialized", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMaterializedTrampoline, &FRAME_PLAN_12}, {"WithClause", &PEGTransformerFactory::InitializeWithClauseTrampoline, &PEGTransformerFactory::FinalizeWithClauseTrampoline, nullptr}, {"SelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_449}, + &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_451}, {"TargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_450}, + &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_452}, {"ColumnAliases", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_423}, + &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_425}, {"DistinctClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"DistinctAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDistinctAllTrampoline, &FRAME_PLAN_12}, {"DistinctOn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_451}, + &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_453}, {"DistinctOnTargets", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_333}, + &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_335}, {"InnerTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableRef", &PEGTransformerFactory::InitializeTableRefTrampoline, &PEGTransformerFactory::FinalizeTableRefTrampoline, nullptr}, {"TableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_452}, + &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_454}, {"BaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_453}, + &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_455}, {"TableAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTableAliasColonTrampoline, &FRAME_PLAN_38}, {"ValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_454}, + &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_456}, {"ParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_455}, + &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_457}, {"JoinedTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"JoinedTableRefChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinedTableRefChainTrampoline, &FRAME_PLAN_456}, + &PEGTransformerFactory::FinalizeJoinedTableRefChainTrampoline, &FRAME_PLAN_458}, {"JoinOrPivot", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TablePivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_457}, + &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_459}, {"TablePivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_458}, + &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_460}, {"PivotGroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_459}, + &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_461}, {"TableUnpivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_460}, + &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_462}, {"TableUnpivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_461}, + &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_463}, {"PivotHeader", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_462}, + &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_464}, {"PivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_463}, + &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_465}, {"PivotValueTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"PivotEnumTarget", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotEnumTargetTrampoline, &FRAME_PLAN_12}, {"PivotListTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_464}, + &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_466}, {"UnpivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_465}, + &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_467}, {"PivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_466}, + &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_468}, {"UnpivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_466}, + &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_468}, {"Lateral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeLateralTrampoline, &FRAME_PLAN_12}, {"BaseTableName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9065,37 +9101,37 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"TableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableFunctionLateralOpt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_467}, + &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_469}, {"TableFunctionAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_468}, + &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_470}, {"WithOrdinality", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWithOrdinalityTrampoline, &FRAME_PLAN_12}, {"QualifiedTableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"CatalogReservedSchemaTableFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableFunctionNameTrampoline, &FRAME_PLAN_469}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableFunctionNameTrampoline, &FRAME_PLAN_471}, {"TableFunctionNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTableFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, {"TableFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_470}, + &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_472}, {"FunctionArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NamedFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_471}, + &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_473}, {"PositionalFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePositionalFunctionArgumentTrampoline, &FRAME_PLAN_31}, {"NamedParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_472}, + &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_474}, {"TableAlias", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"TableAliasAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_473}, + &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_475}, {"TableAliasWithoutAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_474}, + &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_476}, {"AtClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_475}, + &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_477}, {"AtSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_476}, + &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_478}, {"AtUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeAtUnitTrampoline, &FRAME_PLAN_19}, {"VersionAtUnit", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9107,21 +9143,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NearestJoinClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestJoinAliased", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_477}, + &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_479}, {"NearestJoinBare", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_478}, + &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_480}, {"NearestBareTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_479}, + &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_481}, {"NearestTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_480}, + &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_482}, {"NearestTableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_481}, + &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_483}, {"NearestBaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_482}, + &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_484}, {"NearestParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_483}, + &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_485}, {"ApproxOrExact", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"NearestApprox", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9135,19 +9171,19 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NearestSimilarity", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNearestSimilarityTrampoline, &FRAME_PLAN_12}, {"RegularJoinClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_484}, + &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_486}, {"JoinByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_485}, + &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_487}, {"Asof", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAsofTrampoline, &FRAME_PLAN_12}, {"JoinWithoutOnClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_486}, + &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_488}, {"JoinQualifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OnClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOnClauseTrampoline, &FRAME_PLAN_21}, {"UsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_487}, + &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_489}, {"UsingColumnName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeUsingColumnNameTrampoline, &FRAME_PLAN_149}, {"JoinType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9157,7 +9193,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CrossJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCrossJoinPrefixTrampoline, &FRAME_PLAN_12}, {"NaturalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_488}, + &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_490}, {"PositionalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePositionalJoinPrefixTrampoline, &FRAME_PLAN_12}, {"FullJoin", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9177,35 +9213,35 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"WhereClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeWhereClauseTrampoline, &FRAME_PLAN_21}, {"GroupByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_489}, + &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_491}, {"HavingClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeHavingClauseTrampoline, &FRAME_PLAN_21}, {"QualifyClause", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeQualifyClauseTrampoline, &FRAME_PLAN_21}, {"SampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_490}, + &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_492}, {"SelectSampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_490}, + &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_492}, {"WindowClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_491}, + &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_493}, {"WindowDefinition", &PEGTransformerFactory::InitializeWindowDefinitionTrampoline, &PEGTransformerFactory::FinalizeWindowDefinitionTrampoline, nullptr}, {"SampleEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SampleEntryCount", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_492}, + &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_494}, {"SampleEntryFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_493}, + &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_495}, {"SampleFunction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSampleFunctionTrampoline, &FRAME_PLAN_83}, {"SampleProperties", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_494}, + &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_496}, {"RepeatableSample", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_495}, + &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_497}, {"SampleSeed", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeSampleSeedTrampoline, &FRAME_PLAN_12}, {"SampleCount", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_496}, + &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_498}, {"SampleValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SampleUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9219,7 +9255,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"GroupByAll", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeGroupByAllTrampoline, &FRAME_PLAN_12}, {"GroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_497}, + &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_499}, {"GroupByExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"GroupByBaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9227,7 +9263,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"EmptyGroupingItem", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeEmptyGroupingItemTrampoline, &FRAME_PLAN_12}, {"CubeOrRollupClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_498}, + &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_500}, {"CubeOrRollup", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeCubeOrRollupTrampoline, &FRAME_PLAN_19}, {"CubeKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9235,9 +9271,9 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"RollupKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRollupKeywordTrampoline, &FRAME_PLAN_12}, {"GroupingSetsClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_499}, + &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_501}, {"SubqueryReference", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_296}, + &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_298}, {"OrderByExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOrderByExpressionTrampoline, &FRAME_PLAN_98}, {"DescOrAsc", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9253,17 +9289,17 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"NullsLast", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeNullsLastTrampoline, &FRAME_PLAN_12}, {"OrderByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_500}, + &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_502}, {"OrderByExpressions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"OrderByExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_501}, + &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_503}, {"OrderByAll", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_502}, + &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_504}, {"LimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_503}, + &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_505}, {"OffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_504}, + &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_506}, {"OffsetValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOffsetValueTrampoline, &FRAME_PLAN_31}, {"LimitValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9279,45 +9315,45 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"FetchClauseWithoutValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFetchClauseWithoutValueTrampoline, &FRAME_PLAN_12}, {"FetchClauseWithValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_505}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_507}, {"FetchValue", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFetchValueTrampoline, &FRAME_PLAN_31}, {"AliasedExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ColIdExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_506}, + &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_508}, {"ExpressionAsCollabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_388}, + &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_390}, {"ExpressionOptIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeExpressionOptIdentifierTrampoline, &FRAME_PLAN_31}, {"ValuesClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_507}, + &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_509}, {"ValuesExpressions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_295}, + &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_297}, {"SetStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetKeywordStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_508}, + &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_510}, {"VariableAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_509}, + &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_511}, {"SetAssignmentOrTimeZone", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResetStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_510}, + &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_512}, {"ResetTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ResetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_511}, + &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_513}, {"ResetVariableOrSetting", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_512}, + &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_514}, {"SetSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_511}, + &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_513}, {"StandardAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_513}, + &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_515}, {"SetVariableOrSetting", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_514}, + &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_516}, {"ZoneValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ZoneLocal", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9329,13 +9365,13 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ZoneIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeZoneIdentifierTrampoline, &FRAME_PLAN_12}, {"ZoneIntervalWithInterval", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_515}, + &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_517}, {"ZoneIntervalWithPrecision", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeZoneIntervalWithPrecisionTrampoline, &FRAME_PLAN_12}, {"SetSetting", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_511}, + &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_513}, {"SetVariable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_516}, + &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_518}, {"VariableScope", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeVariableScopeTrampoline, &FRAME_PLAN_12}, {"SettingScope", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9347,19 +9383,19 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"GlobalScope", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeGlobalScopeTrampoline, &FRAME_PLAN_12}, {"SetAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_517}, + &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_519}, {"VariableList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_343}, + &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_345}, {"TransactionStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BeginTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_518}, + &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_520}, {"RollbackTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRollbackTransactionTrampoline, &FRAME_PLAN_12}, {"CommitTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCommitTransactionTrampoline, &FRAME_PLAN_12}, {"ReadOrWrite", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_519}, + &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_521}, {"ReadOnlyOrReadWrite", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"ReadOnly", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9367,27 +9403,27 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"ReadWrite", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeReadWriteTrampoline, &FRAME_PLAN_12}, {"UpdateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_520}, + &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_522}, {"UpdateTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"BaseTableSet", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableSetTrampoline, &FRAME_PLAN_182}, + &PEGTransformerFactory::FinalizeBaseTableSetTrampoline, &FRAME_PLAN_184}, {"BaseTableAliasSet", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_521}, + &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_523}, {"UpdateAlias", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUpdateAliasTrampoline, &FRAME_PLAN_32}, {"UpdateSetClauseList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_522}, + &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_524}, {"UpdateSetClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"UpdateSetTuple", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeUpdateSetTupleTrampoline, &FRAME_PLAN_17}, {"UpdateSetElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_523}, + &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_525}, {"UpdateSetColumnTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_524}, + &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_526}, {"UseStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_525}, + &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_527}, {"UseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"SchemaNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, @@ -9395,21 +9431,21 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"CatalogNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeCatalogNameAsUseTargetTrampoline, &FRAME_PLAN_54}, {"UseTargetCatalogSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_526}, + &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_528}, {"DotIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDotIdentifierTrampoline, &FRAME_PLAN_12}, {"VacuumStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_527}, + &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_529}, {"VacuumOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, {"VacuumParensOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_528}, + &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_530}, {"VacuumLegacyOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_529}, + &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_531}, {"VacuumOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizeVacuumOptionTrampoline, &FRAME_PLAN_19}, {"OptAnalyze", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_530}, + &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_532}, {"OptFull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOptFullTrampoline, &FRAME_PLAN_12}, {"OptFreeze", &PEGTransformerFactory::InitializePlannedTrampoline, @@ -9417,7 +9453,7 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"OptVerbose", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOptVerboseTrampoline, &FRAME_PLAN_12}, {"NameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_423}, + &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_425}, }; static case_insensitive_map_t BuildGeneratedTransformFrameOps() { @@ -13055,14 +13091,22 @@ PEGTransformerFactory::FinalizeShowExternalResourcesTrampoline(PEGTransformer &t bool has_result {}; auto &has_result_opt = list_pr.GetChild(1).Cast(); has_result = has_result_opt.HasResult(); - optional show_external_resources_type {}; + optional show_external_resources_type {}; if (process.child_results[1]) { - show_external_resources_type = process.TakeResult(1); + show_external_resources_type = process.TakeResult(1); } auto result = TransformShowExternalResources(transformer, show_rule, has_result, show_external_resources_type); return transformer.MakeResult>(std::move(result)); } +arena_ptr +PEGTransformerFactory::FinalizeShowExternalResourceTypesTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto show_rule = process.TakeResult(0); + auto result = TransformShowExternalResourceTypes(transformer, show_rule); + return transformer.MakeResult>(std::move(result)); +} + arena_ptr PEGTransformerFactory::FinalizeShowDeprecatedSelectTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16476,17 +16520,16 @@ PEGTransformerFactory::FinalizeExtractStringArgumentTrampoline(PEGTransformer &t arena_ptr PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto string_literal = TransformStringLiteral(transformer, list_pr.GetChild(2)); + auto external_resource_type = process.TakeResult(0); optional attach_alias {}; - if (process.child_results[0]) { - attach_alias = process.TakeResult(0); + if (process.child_results[1]) { + attach_alias = process.TakeResult(1); } optional> external_resource_creation_options {}; - if (process.child_results[1]) { - external_resource_creation_options = process.TakeResult>(1); + if (process.child_results[2]) { + external_resource_creation_options = process.TakeResult>(2); } - auto result = TransformCreateExternalResourceStmt(transformer, string_literal, attach_alias, + auto result = TransformCreateExternalResourceStmt(transformer, external_resource_type, attach_alias, external_resource_creation_options); return transformer.MakeResult>(std::move(result)); } @@ -16494,15 +16537,14 @@ PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline(PEGTransform arena_ptr PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto string_literal = TransformStringLiteral(transformer, list_pr.GetChild(2)); + auto external_resource_type = process.TakeResult(0); optional attach_alias {}; - if (process.child_results[0]) { - attach_alias = process.TakeResult(0); + if (process.child_results[1]) { + attach_alias = process.TakeResult(1); } - auto expression = process.TakeResult>(1); + auto expression = process.TakeResult>(2); auto result = - TransformRegisterExternalResourceStmt(transformer, string_literal, attach_alias, std::move(expression)); + TransformRegisterExternalResourceStmt(transformer, external_resource_type, attach_alias, std::move(expression)); return transformer.MakeResult>(std::move(result)); } @@ -16514,6 +16556,59 @@ PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline(PEGTransfor return transformer.MakeResult>(std::move(result)); } +arena_ptr +PEGTransformerFactory::FinalizeExternalResourceTypeTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + string result; + if (process.child_results[0]) { + result = process.TakeResult(0); + } else { + auto &list_pr = process.parse_result.Cast(); + auto &choice_result = list_pr.Child(0).GetResult(); + if (choice_result.type == ParseResultType::IDENTIFIER) { + result = choice_result.Cast().identifier.GetIdentifierName(); + } else if (choice_result.type == ParseResultType::KEYWORD) { + result = choice_result.Cast().keyword; + } else if (choice_result.type == ParseResultType::STRING) { + result = choice_result.Cast().result; + } else if (choice_result.type == ParseResultType::OPERATOR) { + result = choice_result.Cast().operator_token; + } else { + result = transformer.Transform(choice_result); + } + } + return transformer.MakeResult(result); +} + +arena_ptr +PEGTransformerFactory::FinalizeExternalResourceTypeNameTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + auto bare_name = process.TakeResult(0); + auto result = TransformExternalResourceTypeName(transformer, bare_name); + return transformer.MakeResult(result); +} + +arena_ptr PEGTransformerFactory::FinalizeBareNameTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + Identifier result; + if (process.child_results[0]) { + result = process.TakeResult(0); + } else { + auto &list_pr = process.parse_result.Cast(); + auto &choice_result = list_pr.Child(0).GetResult(); + if (choice_result.type == ParseResultType::IDENTIFIER) { + result = choice_result.Cast().identifier; + } else if (choice_result.type == ParseResultType::KEYWORD) { + result = Identifier(choice_result.Cast().keyword); + } else if (choice_result.type == ParseResultType::STRING) { + result = Identifier(choice_result.Cast().result); + } else { + result = Identifier(TransformIdentifierOrKeyword(transformer, choice_result)); + } + } + return transformer.MakeResult(result); +} + arena_ptr PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { @@ -16543,14 +16638,13 @@ PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline(PEGTransforme arena_ptr PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto string_literal = TransformStringLiteral(transformer, list_pr.GetChild(3)); + auto external_resource_type = process.TakeResult(0); optional> external_resource_creation_options {}; - if (process.child_results[0]) { - external_resource_creation_options = process.TakeResult>(0); + if (process.child_results[1]) { + external_resource_creation_options = process.TakeResult>(1); } auto result = - TransformExternalResourceCreateClause(transformer, string_literal, external_resource_creation_options); + TransformExternalResourceCreateClause(transformer, external_resource_type, external_resource_creation_options); return transformer.MakeResult>(std::move(result)); } @@ -16970,23 +17064,6 @@ PEGTransformerFactory::FinalizeExtensionRepositoryNameTrampoline(PEGTransformer return transformer.MakeResult(result); } -arena_ptr -PEGTransformerFactory::FinalizeExtensionRepositoryHostNameTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto &dynamic_repeat_pr = list_pr.GetChild(1).Cast(); - auto dynamic_repeat_children = dynamic_repeat_pr.GetChildren(); - auto dynamic_child_count = dynamic_repeat_children.size(); - auto col_id = process.TakeResult(0); - vector dot_col_label; - dot_col_label.reserve(dynamic_child_count); - for (idx_t i = 1; i < 1 + dynamic_child_count; i++) { - dot_col_label.push_back(process.TakeResult(i)); - } - auto result = TransformExtensionRepositoryHostName(transformer, col_id, dot_col_label); - return transformer.MakeResult(result); -} - arena_ptr PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { diff --git a/src/duckdb/src/parser/peg/transformer/transform_load.cpp b/src/duckdb/src/parser/peg/transformer/transform_load.cpp index 6698aa27e..ea200713b 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_load.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_load.cpp @@ -116,16 +116,6 @@ unique_ptr PEGTransformerFactory::TransformCreateExtensionReposito } // carlopi.github.io: the words joined back into the host name -Identifier PEGTransformerFactory::TransformExtensionRepositoryHostName(PEGTransformer &transformer, - const Identifier &col_id, - const vector &dot_col_label) { - auto name = col_id.GetIdentifierName(); - for (auto &label : dot_col_label) { - name += "." + label; - } - return Identifier(name); -} - // CREATE EXTENSION REPOSITORY : the host names the prefix when the statement runs unique_ptr PEGTransformerFactory::TransformCreateExtensionRepositoryFromHostStmt( PEGTransformer &transformer, const optional &or_replace, const optional &if_not_exists, diff --git a/src/duckdb/src/parser/query_node.cpp b/src/duckdb/src/parser/query_node.cpp index 623878f0a..fb27e3b92 100644 --- a/src/duckdb/src/parser/query_node.cpp +++ b/src/duckdb/src/parser/query_node.cpp @@ -169,25 +169,6 @@ void QueryNode::CopyProperties(QueryNode &other) const { } } -void QueryNode::AddDistinct() { - // check if we already have a DISTINCT modifier - for (idx_t modifier_idx = modifiers.size(); modifier_idx > 0; modifier_idx--) { - auto &modifier = *modifiers[modifier_idx - 1]; - if (modifier.type == ResultModifierType::DISTINCT_MODIFIER) { - auto &distinct_modifier = modifier.Cast(); - if (distinct_modifier.distinct_on_targets.empty()) { - // we have a DISTINCT without an ON clause - this distinct does not need to be added - return; - } - } else if (modifier.type == ResultModifierType::LIMIT_MODIFIER) { - // we encountered a LIMIT or LIMIT PERCENT - these change the result of DISTINCT, so we do need to push a - // DISTINCT relation - break; - } - } - modifiers.push_back(make_uniq()); -} - void QueryNode::VerifyDeserialized(const unique_ptr &node) { if (!node) { throw SerializationException("Failed to deserialize query node: missing query node"); diff --git a/src/duckdb/src/parser/statement/relation_statement.cpp b/src/duckdb/src/parser/statement/relation_statement.cpp deleted file mode 100644 index 023d3cac9..000000000 --- a/src/duckdb/src/parser/statement/relation_statement.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "duckdb/parser/statement/relation_statement.hpp" -#include "duckdb/main/relation/query_relation.hpp" - -namespace duckdb { - -RelationStatement::RelationStatement(shared_ptr relation_p) - : SQLStatement(StatementType::RELATION_STATEMENT), relation(std::move(relation_p)) { - query = relation->GetQuery(); -} - -unique_ptr RelationStatement::Copy() const { - return unique_ptr(new RelationStatement(*this)); -} - -string RelationStatement::ToString() const { - return relation->ToString(); -} - -} // namespace duckdb diff --git a/src/duckdb/src/parser/tableref/delimgetref.cpp b/src/duckdb/src/parser/tableref/delimgetref.cpp deleted file mode 100644 index ec6952122..000000000 --- a/src/duckdb/src/parser/tableref/delimgetref.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "duckdb/parser/tableref/delimgetref.hpp" -#include "duckdb/common/serializer/deserializer.hpp" -#include "duckdb/common/serializer/serializer.hpp" - -namespace duckdb { - -string DelimGetRef::ToString() const { - return ""; -} - -bool DelimGetRef::Equals(const TableRef &other) const { - return TableRef::Equals(other); -} - -unique_ptr DelimGetRef::Copy() { - auto copy = make_uniq(types); - CopyProperties(*copy); - return std::move(copy); -} - -void DelimGetRef::Serialize(Serializer &serializer) const { - TableRef::Serialize(serializer); - serializer.WriteProperty>(105, "chunk_types", types); -} - -unique_ptr DelimGetRef::Deserialize(Deserializer &deserializer) { - vector types = deserializer.ReadProperty>(105, "chunk_types"); - auto result = duckdb::unique_ptr(new DelimGetRef(types)); - return std::move(result); -} - -} // namespace duckdb diff --git a/src/duckdb/src/parser/token_iterator.cpp b/src/duckdb/src/parser/token_iterator.cpp index 1130d9e89..8ad2a7995 100644 --- a/src/duckdb/src/parser/token_iterator.cpp +++ b/src/duckdb/src/parser/token_iterator.cpp @@ -11,9 +11,7 @@ TokenIterator::TokenIterator(unique_ptr> owned_tokens_p) if (!owned_tokens) { throw InternalException("Cannot construct an owning TokenIterator without tokens"); } - for (auto &token : tokens) { - token.ResetLiteralInfo(); - } + // Owned tokens come straight from the tokenizer and keep the literal info it cached on them. } TokenIterator::TokenIterator(TokenizerBehavior &behavior) @@ -69,40 +67,25 @@ const MatcherToken &TokenIterator::Previous() const { return GetToken(position - 1); } -const MatcherToken &TokenIterator::GetToken(idx_t index) const { - if (index >= tokens.size()) { - throw InternalException("Token index %llu is out of range (size %llu)", index, tokens.size()); - } - return tokens[index]; +void TokenIterator::ThrowIndexError(idx_t index) const { + throw InternalException("Token index %llu is out of range (size %llu)", index, tokens.size()); } -void TokenIterator::Advance(idx_t count) { - if (count > tokens.size() - position) { - throw InternalException("Cannot advance TokenIterator by %llu tokens from position %llu (size %llu)", count, - position, tokens.size()); - } - position += count; +void TokenIterator::ThrowAdvanceError(idx_t count) const { + throw InternalException("Cannot advance TokenIterator by %llu tokens from position %llu (size %llu)", count, + position, tokens.size()); } -void TokenIterator::SetPosition(idx_t position_p) { - if (position_p > tokens.size()) { - throw InternalException("Token position %llu is out of range (size %llu)", position_p, tokens.size()); - } - position = position_p; +void TokenIterator::ThrowPositionError(idx_t position_p) const { + throw InternalException("Token position %llu is out of range (size %llu)", position_p, tokens.size()); } -void TokenIterator::SetPosition(const TokenIterator &other) { - if (&tokens != &other.tokens) { - throw InternalException("Cannot set TokenIterator position from a different token collection"); - } - SetPosition(other.position); +void TokenIterator::ThrowCollectionError() const { + throw InternalException("Cannot set TokenIterator position from a different token collection"); } -void TokenIterator::SetPreviousTokenType(TokenType type) { - if (position == 0) { - throw InternalException("TokenIterator has no previous token to annotate"); - } - tokens[position - 1].type = type; +void TokenIterator::ThrowNoPreviousError() const { + throw InternalException("TokenIterator has no previous token to annotate"); } vector TokenIterator::RemainingTokens() const { diff --git a/src/duckdb/src/planner/binder.cpp b/src/duckdb/src/planner/binder.cpp index 1cbfd2dc9..ffa0974b6 100644 --- a/src/duckdb/src/planner/binder.cpp +++ b/src/duckdb/src/planner/binder.cpp @@ -87,8 +87,6 @@ BoundStatement Binder::Bind(SQLStatement &statement) { return Bind(statement.Cast()); case StatementType::UPDATE_STATEMENT: return Bind(statement.Cast()); - case StatementType::RELATION_STATEMENT: - return Bind(statement.Cast()); case StatementType::CREATE_STATEMENT: return Bind(statement.Cast()); case StatementType::DROP_STATEMENT: @@ -180,9 +178,6 @@ BoundStatement Binder::Bind(TableRef &ref) { case TableReferenceType::SHOW_REF: result = Bind(ref.Cast()); break; - case TableReferenceType::DELIM_GET: - result = Bind(ref.Cast()); - break; case TableReferenceType::MATCH_RECOGNIZE: result = Bind(ref.Cast()); break; diff --git a/src/duckdb/src/planner/binder/expression/bind_between_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_between_expression.cpp index e3e89e046..18c98f067 100644 --- a/src/duckdb/src/planner/binder/expression/bind_between_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_between_expression.cpp @@ -62,7 +62,7 @@ BindResult ExpressionBinder::BindExpression(BetweenExpression &expr, idx_t depth // expression has side effects: we cannot duplicate it // create a bound_between directly return BindResult( - BoundBetweenExpression::Create(std::move(input), std::move(lower), std::move(upper), true, true)); + BoundBetweenExpression::Create(context, std::move(input), std::move(lower), std::move(upper), true, true)); } } diff --git a/src/duckdb/src/planner/binder/expression/bind_comparison_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_comparison_expression.cpp index ef8e37c5e..441562e22 100644 --- a/src/duckdb/src/planner/binder/expression/bind_comparison_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_comparison_expression.cpp @@ -5,7 +5,6 @@ #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_parameter_expression.hpp" #include "duckdb/planner/expression_binder.hpp" -#include "duckdb/catalog/catalog_entry/collate_catalog_entry.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/function/scalar/string_functions.hpp" diff --git a/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp index 5967688f3..aa7f56242 100644 --- a/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp @@ -176,7 +176,7 @@ MacroFunction &ExpressionBinder::UnfoldMacroExpression(FunctionExpression &funct InsertionOrderPreservingMap, Identifier, identifier_map_t> named_arguments; binder.lambda_bindings = lambda_bindings; auto bind_result = MacroFunction::BindMacroFunction(binder, macro_func.macros, macro_func.name, function, - positional_arguments, named_arguments, depth); + positional_arguments, named_arguments, depth, this); if (!bind_result.error.empty()) { throw BinderException(*expr, bind_result.error); } @@ -209,7 +209,7 @@ BindResult ExpressionBinder::BindMacro(FunctionExpression &function, ScalarMacro unique_ptr &expr) { auto stack_checker = StackCheck(*expr, 3); // expanding nested macros can take a long time, allow the query to be interrupted - context.InterruptCheck(); + context.FastInterruptCheck(); // unfold the macro expression auto &member = UnfoldMacroExpression(function, macro_func, expr, depth); diff --git a/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp index 0e92f4899..bb9bf0d2b 100644 --- a/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp @@ -264,7 +264,7 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) if (extract_expr_type.id() != LogicalTypeId::STRUCT && extract_expr_type.id() != LogicalTypeId::UNION && extract_expr_type.id() != LogicalTypeId::MAP && extract_expr_type.id() != LogicalTypeId::SQLNULL && !extract_expr_type.IsJSONType() && extract_expr_type.id() != LogicalTypeId::VARIANT && - extract_expr_type.id() != LogicalTypeId::GEOMETRY) { + extract_expr_type.id() != LogicalTypeId::GEOMETRY && extract_expr_type.id() != LogicalTypeId::GEOGRAPHY) { return BindResult(StringUtil::Format("Cannot extract field %s from expression \"%s\" because it is not a " "struct, union, map, json or geometry", name_exp.ToString(), extract_exp.ToString())); @@ -292,7 +292,8 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) const_exp.WithValue(Value(StringUtil::Format("$.\"%s\"", const_exp.GetValue().ToString()))); } } - } else if (extract_expr_type.id() == LogicalTypeId::GEOMETRY) { + } else if (extract_expr_type.id() == LogicalTypeId::GEOMETRY || + extract_expr_type.id() == LogicalTypeId::GEOGRAPHY) { function_name = "vertex_extract"; } else { function_name = "struct_extract"; diff --git a/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp index a346f94a9..7511c9b90 100644 --- a/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp @@ -254,7 +254,7 @@ BindResult BaseSelectBinder::BindWindowExpression(WindowExpression &window, idx_ LogicalType sql_type; unique_ptr aggregate; unique_ptr window_func; - unique_ptr bind_info; + cow_ptr bind_info; vector> children; if (entry->type == CatalogType::AGGREGATE_FUNCTION_ENTRY) { diff --git a/src/duckdb/src/planner/binder/query_node/bind_table_macro_node.cpp b/src/duckdb/src/planner/binder/query_node/bind_table_macro_node.cpp index 5b4e01ca8..dd424ea18 100644 --- a/src/duckdb/src/planner/binder/query_node/bind_table_macro_node.cpp +++ b/src/duckdb/src/planner/binder/query_node/bind_table_macro_node.cpp @@ -20,13 +20,13 @@ namespace duckdb { unique_ptr Binder::BindTableMacro(FunctionExpression &function, TableMacroCatalogEntry ¯o_func, idx_t depth) { // expanding nested macros can take a long time, allow the query to be interrupted - context.InterruptCheck(); + context.FastInterruptCheck(); // validate the arguments and separate positional and default arguments vector> positional_arguments; InsertionOrderPreservingMap, Identifier, identifier_map_t> named_arguments; auto bind_result = MacroFunction::BindMacroFunction(*this, macro_func.macros, macro_func.name, function, - positional_arguments, named_arguments, depth); + positional_arguments, named_arguments, depth, nullptr); if (!bind_result.error.empty()) { throw BinderException(function, bind_result.error); } diff --git a/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp b/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp index 0bc3c7833..3f6bceeef 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp @@ -218,7 +218,7 @@ unique_ptr Binder::CreatePlan(BoundSelectNode &statement) { } if (!statement.windows.empty()) { - auto win = make_uniq(statement.window_index); + auto win = make_uniq(statement.window_index, optional_idx()); win->expressions = std::move(statement.windows); // visit the window expressions for (auto &expr : win->expressions) { diff --git a/src/duckdb/src/planner/binder/query_node/plan_setop.cpp b/src/duckdb/src/planner/binder/query_node/plan_setop.cpp index deba4feb2..3fa39bc82 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_setop.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_setop.cpp @@ -1,17 +1,10 @@ #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" -#include "duckdb/planner/expression/bound_window_expression.hpp" -#include "duckdb/planner/expression_binder.hpp" -#include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_projection.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" -#include "duckdb/planner/operator/logical_window.hpp" #include "duckdb/planner/query_node/bound_set_operation_node.hpp" -#include "duckdb/function/builtin_function_lookup.hpp" #include "duckdb/function/table/read_csv.hpp" -#include "duckdb/function/window/rows_functions.hpp" -#include "duckdb/function/window_function.hpp" #include "duckdb/planner/operator/logical_get.hpp" namespace duckdb { @@ -77,64 +70,6 @@ unique_ptr Binder::CastLogicalOperatorToTypes(const vector AddRowNumber(Binder &binder, const vector &types, - unique_ptr child) { - auto &context = binder.context; - auto bindings = child->GetColumnBindings(); - auto row_number = GetBuiltinWindowFunction(context, RowNumberFun::Name, {})->Bind(context); - row_number->WindowStartMutable() = WindowBoundary::UNBOUNDED_PRECEDING; - row_number->WindowEndMutable() = WindowBoundary::UNBOUNDED_FOLLOWING; - for (idx_t i = 0; i < types.size(); i++) { - unique_ptr partition = make_uniq(types[i], bindings[i]); - ExpressionBinder::PushCollation(context, partition, types[i]); - row_number->PartitionsMutable().push_back(std::move(partition)); - } - auto window = make_uniq(binder.GenerateTableIndex()); - window->expressions.push_back(std::move(row_number)); - window->AddChild(std::move(child)); - return std::move(window); -} - -//! Plans EXCEPT as an ANTI join and INTERSECT as a SEMI join on all columns, which compares them with the collations -//! of both children and treats NULLs as equal -static unique_ptr CreateSetOperationJoin(Binder &binder, BoundSetOperationNode &node, - unique_ptr left, - unique_ptr right) { - auto &types = node.types; - auto compared_types = types; - if (node.setop_all) { - left = AddRowNumber(binder, types, std::move(left)); - right = AddRowNumber(binder, types, std::move(right)); - compared_types.push_back(LogicalType::BIGINT); - } - auto left_bindings = left->GetColumnBindings(); - auto right_bindings = right->GetColumnBindings(); - D_ASSERT(left_bindings.size() == compared_types.size() && right_bindings.size() == compared_types.size()); - - auto join_type = node.setop_type == SetOperationType::EXCEPT ? JoinType::ANTI : JoinType::SEMI; - auto join = make_uniq(join_type); - for (idx_t i = 0; i < compared_types.size(); i++) { - auto &type = compared_types[i]; - JoinCondition condition(make_uniq(type, left_bindings[i]), - make_uniq(type, right_bindings[i]), - ExpressionType::COMPARE_NOT_DISTINCT_FROM); - ExpressionBinder::PushCollation(binder.context, condition.LeftReference(), type); - ExpressionBinder::PushCollation(binder.context, condition.RightReference(), type); - join->conditions.push_back(std::move(condition)); - } - join->AddChild(std::move(left)); - join->AddChild(std::move(right)); - - vector> select_list; - for (idx_t i = 0; i < types.size(); i++) { - select_list.push_back(make_uniq(types[i], left_bindings[i])); - } - auto projection = make_uniq(node.setop_index, std::move(select_list)); - projection->AddChild(std::move(join)); - return std::move(projection); -} - unique_ptr Binder::CreatePlan(BoundSetOperationNode &node) { // Generate the logical plan for the children of the set operation D_ASSERT(node.bound_children.size() >= 2); @@ -154,10 +89,25 @@ unique_ptr Binder::CreatePlan(BoundSetOperationNode &node) { LogicalOperatorType::LOGICAL_UNION, node.setop_all); break; case SetOperationType::EXCEPT: - case SetOperationType::INTERSECT: + case SetOperationType::INTERSECT: { D_ASSERT(children.size() == 2); - root = CreateSetOperationJoin(*this, node, std::move(children[0]), std::move(children[1])); + auto logical_type = node.setop_type == SetOperationType::EXCEPT ? LogicalOperatorType::LOGICAL_EXCEPT + : LogicalOperatorType::LOGICAL_INTERSECT; + if (node.setop_all) { + // EXCEPT ALL and INTERSECT ALL stay a set operation until the optimizer has moved the filters around + // it and chooses how to run it (see SetOperationAggregate) + auto setop = make_uniq(node.setop_index, node.types.size(), std::move(children), + logical_type, true); + // the types of the set operation carry the collations its columns are compared under + setop->comparison_types = node.types; + root = std::move(setop); + } else { + // EXCEPT is an ANTI join and INTERSECT a SEMI join on all columns + root = LogicalSetOperation::CreateJoin(*this, node.types, node.setop_index, logical_type, false, + std::move(children[0]), std::move(children[1])); + } break; + } default: throw InternalException("Unsupported logical operator type for set-operation"); } diff --git a/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp b/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp index 7ca298240..4745854df 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_subquery.cpp @@ -27,12 +27,16 @@ #include "duckdb/planner/logical_operator_visitor.hpp" #include "duckdb/function/function_binder.hpp" #include "duckdb/planner/subquery/flatten_dependent_join.hpp" +#include "duckdb/planner/subquery/has_volatile_expressions.hpp" #include "duckdb/common/enums/logical_operator_type.hpp" #include "duckdb/planner/operator/logical_dependent_join.hpp" #include "duckdb/planner/subquery/recursive_dependent_join_planner.hpp" #include "duckdb/function/scalar/generic_functions.hpp" #include "duckdb/function/scalar/struct_functions.hpp" #include "duckdb/main/settings.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/expression/bound_unnest_expression.hpp" namespace duckdb { @@ -454,43 +458,6 @@ static bool PerformDelimOnType(const LogicalType &type) { return true; } -//! Like IsVolatile, but ignores error() -//! Error is deterministic, so it can be evaluated once per distinct correlated value -//! FIXME: remove once `error` no longer has to be volatile (fixing blockers is WIP) -static bool IsVolatileIgnoringError(const Expression &expr) { - switch (expr.GetExpressionClass()) { - case ExpressionClass::BOUND_FUNCTION: { - auto &function = expr.Cast().Function(); - if (function.HasBindLambdaCallback() || - (function.GetName() != ErrorFun::Name && function.GetStability() == FunctionStability::VOLATILE)) { - return expr.IsVolatile(); - } - break; - } - case ExpressionClass::BOUND_CASE: - case ExpressionClass::BOUND_CONJUNCTION: - case ExpressionClass::BOUND_OPERATOR: - break; - default: - return expr.IsVolatile(); - } - bool is_volatile = false; - ExpressionIterator::EnumerateChildren( - expr, [&](const Expression &child) { is_volatile = is_volatile || IsVolatileIgnoringError(child); }); - return is_volatile; -} - -static bool HasVolatileExpressionsIgnoringError(const LogicalOperator &op) { - bool is_volatile = false; - LogicalOperatorVisitor::EnumerateExpressions(op, [&](const unique_ptr *expression) { - is_volatile = is_volatile || IsVolatileIgnoringError(**expression); - }); - for (auto &child : op.children) { - is_volatile = is_volatile || (child && HasVolatileExpressionsIgnoringError(*child)); - } - return is_volatile; -} - static bool PerformDuplicateElimination(Binder &binder, CorrelatedColumns &correlated_columns, optional_ptr dependent_plan = nullptr) { bool perform_delim = !dependent_plan || !HasVolatileExpressionsIgnoringError(*dependent_plan); @@ -826,6 +793,208 @@ void RecursiveDependentJoinPlanner::PlanJoinChildFilters(LogicalOperator &op) { } } +//! Whether an expression on the right side of a lateral join can be evaluated over the left rows: it has no subquery, +//! and every correlated column it reads is a column of the left side +static bool ReadsOnlyLateralInput(const Expression &expr, const column_binding_map_t &left_columns) { + switch (expr.GetExpressionClass()) { + case ExpressionClass::BOUND_SUBQUERY: + return false; + case ExpressionClass::BOUND_COLUMN_REF: { + auto &colref = expr.Cast(); + return colref.Depth() == 0 || + (colref.Depth() == 1 && left_columns.find(colref.Binding()) != left_columns.end()); + } + default: + break; + } + bool result = true; + ExpressionIterator::EnumerateChildren( + expr, [&](const Expression &child) { result = result && ReadsOnlyLateralInput(child, left_columns); }); + return result; +} + +//! Replaces the references of the given depth to the columns of the left side by references to the bindings under +//! which the operator below provides these columns +static void BindToLateralInput(unique_ptr &expr, const column_binding_map_t &left_columns, + const vector &left_bindings, idx_t depth) { + if (expr->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto &colref = expr->Cast(); + auto entry = left_columns.find(colref.Binding()); + if (colref.Depth() == depth && entry != left_columns.end()) { + expr = colref.WithBinding(left_bindings[entry->second], 0); + } + return; + } + ExpressionIterator::EnumerateChildren( + *expr, [&](unique_ptr &child) { BindToLateralInput(child, left_columns, left_bindings, depth); }); +} + +//! The unnest table function over one list that is computed in a projection over a DUMMY_SCAN +static bool IsLateralUnnestFunction(LogicalOperator &op) { + if (op.type != LogicalOperatorType::LOGICAL_GET || op.children.size() != 1) { + return false; + } + auto &get = op.Cast(); + if (!ExpressionBinder::IsUnnestFunction(get.function.GetName()) || get.ordinality_idx.IsValid() || + !get.named_parameters.empty() || !get.projected_input.empty() || get.returned_types.size() != 1) { + return false; + } + auto &projection = *get.children[0]; + if (projection.type != LogicalOperatorType::LOGICAL_PROJECTION || projection.expressions.size() != 1 || + projection.children[0]->type != LogicalOperatorType::LOGICAL_DUMMY_SCAN) { + return false; + } + auto &list_type = projection.expressions[0]->GetReturnType(); + return list_type.id() == LogicalTypeId::LIST || list_type.id() == LogicalTypeId::ARRAY; +} + +//! An inner lateral join whose right side unnests a list that is computed from the left row alone +//! DEPENDENT_JOIN(left, GET unnest -> PROJECTION(list) -> DUMMY_SCAN) +//! is the UNNEST of that list over the left rows: the UNNEST passes the columns of the left side through and takes +//! over the table index of the function, so the join keeps its column bindings. +//! The same holds for a lateral subquery around the unnest, as long as its operators map every row on its own +//! (PROJECTION, FILTER, UNNEST): the operators then run over the left rows instead of the single row of the +//! DUMMY_SCAN, and the projections pass the columns of the left side through. These columns get new bindings, which +//! are returned as replacements. +//! Any other join is left to the general decorrelation. +static BindingReplacementGraph PlanLateralUnnest(Binder &binder, unique_ptr &op) { + BindingReplacementGraph replacements; + if (op->type != LogicalOperatorType::LOGICAL_DEPENDENT_JOIN) { + return replacements; + } + auto &join = op->Cast(); + if (join.join_type != JoinType::INNER || join.any_join || + Optimizer::OptimizerDisabled(binder.context, OptimizerType::UNNEST_REWRITER)) { + return replacements; + } + if (Optimizer::OptimizerDisabled(binder.context, OptimizerType::FILTER_PUSHDOWN) || + Settings::Get(binder.context)) { + // a filter on the left columns above the join guards the list: the join does not unnest the rows that the + // filter removes. Above an UNNEST that takes the filter pushdown + return replacements; + } + const auto original_bindings = join.children[0]->GetColumnBindings(); + column_binding_map_t left_columns; + for (idx_t i = 0; i < original_bindings.size(); i++) { + left_columns[original_bindings[i]] = i; + } + + // the right side, from the top down to the DUMMY_SCAN + bool has_unnest = false; + bool has_projection = false; + bool can_throw = false; + idx_t operator_count = 0; + reference current = *join.children[1]; + while (current.get().type != LogicalOperatorType::LOGICAL_DUMMY_SCAN) { + reference expression_operator = current; + switch (current.get().type) { + case LogicalOperatorType::LOGICAL_PROJECTION: + has_projection = true; + break; + case LogicalOperatorType::LOGICAL_FILTER: + if (current.get().HasProjectionMap()) { + return replacements; + } + break; + case LogicalOperatorType::LOGICAL_UNNEST: + has_unnest = true; + break; + case LogicalOperatorType::LOGICAL_GET: + if (!IsLateralUnnestFunction(current)) { + return replacements; + } + has_unnest = true; + // the list is computed in the projection below the function, which becomes part of the UNNEST + expression_operator = *current.get().children[0]; + break; + default: + return replacements; + } + for (auto &expr : expression_operator.get().expressions) { + // a volatile expression is evaluated for every left row by the join, also for rows that a LIMIT above + // does not need; a subquery or a column of an enclosing query needs the general decorrelation + if (expr->IsVolatile() || !ReadsOnlyLateralInput(*expr, left_columns)) { + return replacements; + } + can_throw = can_throw || expr->CanThrow(); + } + operator_count++; + current = *expression_operator.get().children[0]; + } + if (!has_unnest) { + return replacements; + } + if (has_projection && can_throw) { + // a filter on the left columns above the join guards the expressions of the right side: the join evaluates + // them for the left rows that pass it. Such a filter does not always move below a projection + return replacements; + } + if (join.condition && + (join.condition->IsVolatile() || join.condition->CanThrow() || join.condition->HasSubquery())) { + // the ON condition becomes a filter over the joined rows. The join does not evaluate its condition once for + // every one of them, so only a condition that gives the same result however often and on whichever of these + // rows it is evaluated can move there + return replacements; + } + + vector> operators; + auto right = std::move(join.children[1]); + for (idx_t i = 0; i < operator_count; i++) { + auto child = std::move(right->children[0]); + operators.push_back(std::move(right)); + right = std::move(child); + } + + // rebuild the right side over the left side, bottom-up + auto result = std::move(join.children[0]); + result->ResolveOperatorTypes(); + const auto left_types = result->types; + auto left_bindings = original_bindings; + while (!operators.empty()) { + auto right_operator = std::move(operators.back()); + operators.pop_back(); + if (right_operator->type == LogicalOperatorType::LOGICAL_GET) { + auto &get = right_operator->Cast(); + auto list = std::move(right->expressions[0]); + BindToLateralInput(list, left_columns, left_bindings, 1); + auto unnest_expr = make_uniq(get.returned_types[0]); + unnest_expr->ChildMutable() = BoundCastExpression::AddArrayCastToList(binder.context, std::move(list)); + auto unnest = make_uniq(get.table_index); + unnest->expressions.push_back(std::move(unnest_expr)); + unnest->AddChild(std::move(result)); + result = std::move(unnest); + continue; + } + for (auto &expr : right_operator->expressions) { + BindToLateralInput(expr, left_columns, left_bindings, 1); + } + right_operator->children[0] = std::move(result); + if (right_operator->type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto &projection = right_operator->Cast(); + for (idx_t i = 0; i < left_bindings.size(); i++) { + auto left_column = make_uniq(left_types[i], left_bindings[i]); + auto column_index = ColumnBinding::PushExpression(projection.expressions, std::move(left_column)); + left_bindings[i] = ColumnBinding(projection.table_index, column_index); + } + } + result = std::move(right_operator); + } + if (join.condition) { + // the ON condition of an inner join filters the joined rows + BindToLateralInput(join.condition, left_columns, left_bindings, 0); + auto filter = make_uniq(std::move(join.condition)); + filter->AddChild(std::move(result)); + result = std::move(filter); + } + for (idx_t i = 0; i < left_bindings.size(); i++) { + if (left_bindings[i] != original_bindings[i]) { + replacements.Add(original_bindings[i], left_bindings[i]); + } + } + op = std::move(result); + return replacements; +} + BindingReplacementGraph RecursiveDependentJoinPlanner::PlanOperator(unique_ptr &op_ptr) { PlanJoinChildFilters(*op_ptr); if (op_ptr->type == LogicalOperatorType::LOGICAL_ANY_JOIN && @@ -864,6 +1033,7 @@ BindingReplacementGraph RecursiveDependentJoinPlanner::PlanOperator(unique_ptrGetColumnBindings(), operator_replacements); return operator_replacements; } diff --git a/src/duckdb/src/planner/binder/statement/bind_create.cpp b/src/duckdb/src/planner/binder/statement/bind_create.cpp index a1bfce806..729dbfc3a 100644 --- a/src/duckdb/src/planner/binder/statement/bind_create.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_create.cpp @@ -276,12 +276,7 @@ QualifiedName Binder::BindTableName(CatalogEntryRetriever &retriever, const Qual catalog = DatabaseManager::GetDefaultDatabase(retriever.GetContext()); } } - auto result = QualifiedName::FromCatalogSchema(std::move(catalog), std::move(schema_path), resolved.Name()); - auto catalog_entry = Catalog::GetCatalogEntry(retriever, result.Catalog()); - if (catalog_entry) { - catalog_entry->CheckNestedSchemaSupport(result, CatalogType::TABLE_ENTRY); - } - return result; + return QualifiedName::FromCatalogSchema(std::move(catalog), std::move(schema_path), resolved.Name()); } QualifiedName Binder::BindTableName(const QualifiedName &name) { diff --git a/src/duckdb/src/planner/binder/statement/bind_drop.cpp b/src/duckdb/src/planner/binder/statement/bind_drop.cpp index a38b00eeb..2127c2e2b 100644 --- a/src/duckdb/src/planner/binder/statement/bind_drop.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_drop.cpp @@ -48,7 +48,6 @@ BoundStatement Binder::Bind(DropStatement &stmt) { // dropping a schema is never read-only because there are no temporary schemas. The catalog is the leading // component of the resolved path ([catalog, parent schemas..., schema]) auto &catalog = Catalog::GetCatalog(context, stmt.info->GetQualifiedName().Path().front()); - catalog.CheckNestedSchemaSupport(stmt.info->GetQualifiedName(), CatalogType::SCHEMA_ENTRY); properties.RegisterDBModify(catalog, context, stmt.info->GetModifications()); break; } diff --git a/src/duckdb/src/planner/binder/statement/bind_relation.cpp b/src/duckdb/src/planner/binder/statement/bind_relation.cpp deleted file mode 100644 index c3c911310..000000000 --- a/src/duckdb/src/planner/binder/statement/bind_relation.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "duckdb/catalog/catalog.hpp" -#include "duckdb/main/relation.hpp" -#include "duckdb/parser/expression/constant_expression.hpp" -#include "duckdb/parser/statement/insert_statement.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/parser/statement/relation_statement.hpp" - -namespace duckdb { - -BoundStatement Binder::Bind(RelationStatement &stmt) { - return stmt.relation->Bind(*this); -} - -} // namespace duckdb diff --git a/src/duckdb/src/planner/binder/tableref/bind_delimgetref.cpp b/src/duckdb/src/planner/binder/tableref/bind_delimgetref.cpp deleted file mode 100644 index 698cfbffb..000000000 --- a/src/duckdb/src/planner/binder/tableref/bind_delimgetref.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "duckdb/parser/tableref/delimgetref.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/planner/operator/logical_delim_get.hpp" - -namespace duckdb { - -BoundStatement Binder::Bind(DelimGetRef &ref) { - // Have to add bindings - auto tbl_idx = GenerateTableIndex(); - string internal_name = "__internal_delim_get_ref_" + std::to_string(tbl_idx.index); - - BoundStatement result; - result.types = std::move(ref.types); - result.names = ref.internal_aliases; - result.plan = make_uniq(tbl_idx, result.types); - - bind_context.AddGenericBinding(tbl_idx, Identifier(internal_name), result.names, result.types); - return result; -} - -} // namespace duckdb diff --git a/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp b/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp index 5557f2b48..685162a4b 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp @@ -687,7 +687,7 @@ static unique_ptr PlanPatternWindow(Binder &binder, ClientContext &c bound_window->OrderByMutable() = std::move(inputs.orders); const auto window_index = binder.GenerateTableIndex(); - auto logical_window = make_uniq(window_index); + auto logical_window = make_uniq(window_index, optional_idx()); logical_window->expressions.push_back(std::move(bound_window)); logical_window->AddChild(std::move(bound_define.plan)); diff --git a/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp b/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp index 92c66b71d..9094868b6 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_table_function.cpp @@ -408,7 +408,7 @@ BoundStatement Binder::BindTableFunctionInternal(BoundTableFunction &table_funct AddPostgresSetofColumnAlias(bind_context, bind_index, setof_column_name); auto window_index = GenerateTableIndex(); - auto window = make_uniq(window_index); + auto window = make_uniq(window_index, optional_idx()); auto row_number = GetBuiltinWindowFunction(context, RowNumberFun::Name, {})->Bind(context); row_number->WindowStartMutable() = WindowBoundary::UNBOUNDED_PRECEDING; row_number->WindowEndMutable() = WindowBoundary::CURRENT_ROW_ROWS; diff --git a/src/duckdb/src/planner/collation_binding.cpp b/src/duckdb/src/planner/collation_binding.cpp index 3accfb4c7..ba8205c1a 100644 --- a/src/duckdb/src/planner/collation_binding.cpp +++ b/src/duckdb/src/planner/collation_binding.cpp @@ -1,5 +1,4 @@ #include "duckdb/planner/collation_binding.hpp" -#include "duckdb/catalog/catalog_entry/collate_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_case_expression.hpp" @@ -10,17 +9,67 @@ #include "duckdb/main/config.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/catalog/catalog.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" +#include "duckdb/common/exception/catalog_exception.hpp" +#include #include "duckdb/function/function_binder.hpp" namespace duckdb { -constexpr const char *CollateCatalogEntry::Name; +Identifier CollationFunctions::GetSchema() { + return Identifier(SCHEMA); +} + +void CollationFunctions::SetCombinable(ScalarFunction &function) { + function.GetProperties().SetProperty(COMBINABLE_PROPERTY, Value::BOOLEAN(true)); +} -static vector GetVarcharCollationFunctions(ClientContext &context, const LogicalType &sql_type, - CollationType type) { +CollationFunction CollationFunctions::Lookup(ClientContext &context, const string &collation) { + auto &catalog = Catalog::GetSystemCatalog(context); + QualifiedName qualified_name(catalog.GetName(), GetSchema(), Identifier(collation)); + auto entry = catalog.GetEntry(context, qualified_name, OnEntryNotFound::RETURN_NULL); + if (!entry && + Catalog::AutoLoadExtensionByCatalogEntry(*context.db, CatalogType::COLLATION_ENTRY, Identifier(collation))) { + entry = catalog.GetEntry(context, qualified_name, OnEntryNotFound::RETURN_NULL); + } + if (!entry) { + auto candidates = StringUtil::TopNJaroWinkler(GetCollations(context), collation, 1); + throw CatalogException::MissingEntry(CatalogType::COLLATION_ENTRY, Identifier(collation), + candidates.empty() ? string() : candidates[0]); + } + auto function = entry->functions.GetFunctionByArguments(context, {LogicalType::VARCHAR}); + if (!function) { + throw CatalogException("Collation function \"%s\" must take a single VARCHAR argument", collation); + } + return CollationFunction {CollationFunctionName(GetSchema(), entry->name), + function->GetProperties().GetBooleanProperty(COMBINABLE_PROPERTY)}; +} + +vector CollationFunctions::GetCollations(ClientContext &context) { + // only list what Lookup resolves: scalar functions in the collation schema that take a single VARCHAR vector result; + auto schema = Catalog::GetSystemCatalog(context).GetSchema(context, GetSchema(), OnEntryNotFound::RETURN_NULL); + if (!schema) { + return result; + } + schema->Scan(context, CatalogType::SCALAR_FUNCTION_ENTRY, [&](CatalogEntry &entry) { + if (entry.type != CatalogType::SCALAR_FUNCTION_ENTRY) { + return; + } + auto &function_entry = entry.Cast(); + if (!FunctionBinder::SelectFunction(context, function_entry.functions, {LogicalType::VARCHAR}).IsSuccess()) { + return; + } + result.push_back(entry.name.GetIdentifierName()); + }); + return result; +} + +static vector GetVarcharCollationFunctions(ClientContext &context, const LogicalType &sql_type, + CollationType type) { if (sql_type.id() != LogicalTypeId::VARCHAR) { // only VARCHAR columns require collation - return result; + return vector(); } // replace default collation with system collation auto str_collation = StringType::GetCollation(sql_type); @@ -34,67 +83,70 @@ static vector GetVarcharCollationFunctions(ClientContext &context, const // bind the collation if (collation.empty() || collation == "binary" || collation == "c" || collation == "posix") { // no collation or binary collation: skip - return result; + return vector(); } - auto &catalog = Catalog::GetSystemCatalog(context); - auto splits = StringUtil::Split(StringUtil::Lower(collation), "."); - vector> entries; + vector functions; + string non_combinable_collation; + vector combinable_functions; unordered_set collations; - for (auto &collation_argument : splits) { + for (auto &collation_argument : StringUtil::Split(collation, ".")) { if (collations.count(collation_argument)) { // we already applied this collation continue; } - auto &collation_entry = catalog.GetEntry( - context, QualifiedName(catalog.GetName(), Identifier::DefaultSchema(), Identifier(collation_argument))); - if (collation_entry.combinable) { - entries.insert(entries.begin(), collation_entry); - } else { - if (!entries.empty() && !entries.back().get().combinable) { - throw BinderException("Cannot combine collation types %s and %s", entries.back().get().name, - collation_entry.name); - } - entries.push_back(collation_entry); - } collations.insert(collation_argument); - } - for (auto &entry : entries) { - auto &collation_entry = entry.get(); - if (!collation_entry.combinable && type == CollationType::COMBINABLE_COLLATIONS) { - // not a combinable collation - only apply the (preceding) combinable collations - break; + auto function = CollationFunctions::Lookup(context, collation_argument); + if (function.combinable) { + combinable_functions.push_back(function.function); + continue; + } + if (!functions.empty()) { + throw BinderException("Cannot combine collation types %s and %s", Identifier(non_combinable_collation), + Identifier(collation_argument)); } - result.push_back(collation_entry.function.GetName().GetIdentifierName()); + non_combinable_collation = collation_argument; + functions.push_back(function.function); } - return result; + // combinable collations are applied first, in reverse order of specification + std::reverse(combinable_functions.begin(), combinable_functions.end()); + if (type == CollationType::COMBINABLE_COLLATIONS) { + // only apply the combinable collations + return combinable_functions; + } + combinable_functions.insert(combinable_functions.end(), functions.begin(), functions.end()); + return combinable_functions; } -static vector GetTimeTZCollationFunctions(ClientContext &, const LogicalType &sql_type, CollationType) { +static vector GetTimeTZCollationFunctions(ClientContext &, const LogicalType &sql_type, + CollationType) { if (sql_type.id() != LogicalTypeId::TIME_TZ) { - return vector(); + return vector(); } - return {"timetz_byte_comparable"}; + return {CollationFunctionName(Identifier("timetz_byte_comparable"))}; } -static vector GetBitStringCollationFunctions(ClientContext &, const LogicalType &sql_type, CollationType) { +static vector GetBitStringCollationFunctions(ClientContext &, const LogicalType &sql_type, + CollationType) { if (sql_type.id() != LogicalTypeId::BIT) { - return vector(); + return vector(); } - return {"bitstring_byte_comparable"}; + return {CollationFunctionName(Identifier("bitstring_byte_comparable"))}; } -static vector GetIntervalCollationFunctions(ClientContext &, const LogicalType &sql_type, CollationType) { +static vector GetIntervalCollationFunctions(ClientContext &, const LogicalType &sql_type, + CollationType) { if (sql_type.id() != LogicalTypeId::INTERVAL) { - return vector(); + return vector(); } - return {"normalized_interval"}; + return {CollationFunctionName(Identifier("normalized_interval"))}; } -static vector GetVariantCollationFunctions(ClientContext &, const LogicalType &sql_type, CollationType) { +static vector GetVariantCollationFunctions(ClientContext &, const LogicalType &sql_type, + CollationType) { if (sql_type.id() != LogicalTypeId::VARIANT) { - return vector(); + return vector(); } - return {"variant_comparator"}; + return {CollationFunctionName(Identifier("variant_comparator"))}; } CollationBinding::CollationBinding() { @@ -109,15 +161,30 @@ void CollationBinding::RegisterCollation(CollationCallback callback) { collations.push_back(callback); } -//! Binds the scalar function with the given name (looked up from the system catalog) around "source". -static unique_ptr ApplyCollationFunction(ClientContext &context, const string &function_name, +//! Binds the given collation function around "source" +static unique_ptr ApplyCollationFunction(ClientContext &context, const CollationFunctionName &function_name, unique_ptr source) { auto source_alias = source->GetAlias(); vector> children; children.push_back(std::move(source)); FunctionBinder function_binder(context); - return function_binder.BindScalarFunction(Identifier::DefaultSchema(), Identifier(function_name), - std::move(children), false, nullptr, std::move(source_alias)); + unique_ptr function; + if (function_name.schema == Identifier::DefaultSchema()) { + function = function_binder.BindScalarFunction(function_name.schema, function_name.name, std::move(children)); + } else { + // functions outside of the default schema, such as the collations, live in the system catalog + auto &catalog = Catalog::GetSystemCatalog(context); + auto entry = catalog.GetEntry( + context, QualifiedName(catalog.GetName(), function_name.schema, function_name.name), + OnEntryNotFound::THROW_EXCEPTION); + ErrorData error; + function = function_binder.BindScalarFunction(*entry, std::move(children), error); + if (!function) { + error.Throw(); + } + } + function->SetAlias(source_alias); + return function; } //! Pushes collations into STRUCT/TUPLE fields using invoke with a lambda that rebuilds the value and preserves NULLs. diff --git a/src/duckdb/src/planner/expression/bound_aggregate_expression.cpp b/src/duckdb/src/planner/expression/bound_aggregate_expression.cpp index 53d78a4c1..a995fa165 100644 --- a/src/duckdb/src/planner/expression/bound_aggregate_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_aggregate_expression.cpp @@ -4,6 +4,7 @@ #include "duckdb/catalog/catalog_entry/aggregate_function_catalog_entry.hpp" #include "duckdb/common/types/hash.hpp" +#include "duckdb/function/create_sort_key.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/function/function_serialization.hpp" #include "duckdb/function/scalar/generic_common.hpp" @@ -12,7 +13,7 @@ namespace duckdb { BoundAggregateExpression::BoundAggregateExpression(BoundAggregateFunction function, vector> children, - unique_ptr filter, unique_ptr bind_info, + unique_ptr filter, cow_ptr bind_info, AggregateType aggr_type) : Expression(ExpressionType::BOUND_AGGREGATE, ExpressionClass::BOUND_AGGREGATE, function.GetReturnType()), function(std::move(function)), children(std::move(children)), bind_info(std::move(bind_info)), @@ -120,6 +121,12 @@ bool BoundAggregateExpression::PropagatesNullValues() const { : Expression::PropagatesNullValues(); } +bool BoundAggregateExpression::CanForwardSingletonInputDomain() const { + return function.HasSingleValueIdentity() || + (children.size() == 2 && function.GetProperties().GetBooleanProperty(NON_NULL_SELECTOR_DOMAIN_PROPERTY) && + CreateSortKeyHelpers::IsNonNullSortKey(*children[1])); +} + unique_ptr BoundAggregateExpression::Copy() const { vector> new_children; new_children.reserve(children.size()); @@ -160,6 +167,7 @@ unique_ptr BoundAggregateExpression::Deserialize(Deserializer &deser deserializer.ReadPropertyWithExplicitDefault(205, "order_bys", result->order_bys, unique_ptr()); deserializer.ReadPropertyWithExplicitDefault(206, "state_export", result->state_export_mode, AggregateStateExportMode::NONE); + deserializer.ReadDeletedProperty(207, "single_value_identity"); if (result->state_export_mode == AggregateStateExportMode::STATE_EXPORT) { if (!return_type.IsAggregateState()) { throw SerializationException("Aggregate State export should return an aggregate state type"); diff --git a/src/duckdb/src/planner/expression/bound_cast_expression.cpp b/src/duckdb/src/planner/expression/bound_cast_expression.cpp index d4675b0e5..7f18699d5 100644 --- a/src/duckdb/src/planner/expression/bound_cast_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_cast_expression.cpp @@ -292,9 +292,14 @@ static bool IsLosslessExactNumericToFloatingCast(const LogicalType &source_type, } } -bool BoundCastExpression::IsLosslessIntegralToFloatingCast(const LogicalType &source_type, - const LogicalType &target_type) { - return source_type.IsIntegral() && IsLosslessExactNumericToFloatingCast(source_type, target_type); +bool BoundCastExpression::CastIsOrderPreserving(const LogicalType &source_type, const LogicalType &target_type) { + if (IsExactNumeric(source_type) && IsExactNumeric(target_type)) { + return CastIsInvertible(source_type, target_type); + } + if (IsLosslessExactNumericToFloatingCast(source_type, target_type)) { + return true; + } + return source_type.id() == LogicalTypeId::FLOAT && target_type.id() == LogicalTypeId::DOUBLE; } //! Whether every value of the type has a unique VARCHAR representation that casts back to the same value @@ -326,20 +331,10 @@ bool BoundCastExpression::CastIsInvertibleForEquality(const LogicalType &source_ // a collation can make distinct strings equal return HasCanonicalVarcharRepresentation(source_type) && StringType::GetCollation(target_type).empty(); } - if (IsExactNumeric(source_type) && IsExactNumeric(target_type)) { - return CastIsInvertible(source_type, target_type); - } - if (IsLosslessExactNumericToFloatingCast(source_type, target_type)) { + if (CastIsOrderPreserving(source_type, target_type)) { return true; } - switch (source_type.id()) { - case LogicalTypeId::BOOLEAN: - return target_type.IsIntegral(); - case LogicalTypeId::FLOAT: - return target_type.id() == LogicalTypeId::DOUBLE; - default: - return false; - } + return source_type.id() == LogicalTypeId::BOOLEAN && target_type.IsIntegral(); } optional BoundCastExpression::TryInvertConstant(ClientContext &context, const BoundFunctionExpression &cast_expr, @@ -498,6 +493,11 @@ bool BoundCastExpression::CastCanThrow(const LogicalType &source_type, const Log if (source_type.id() == LogicalTypeId::GEOMETRY && target_type.id() == LogicalTypeId::GEOMETRY) { return false; } + // The same holds for geography -> geography, and geography -> geometry needs no coordinate validation + if (source_type.id() == LogicalTypeId::GEOGRAPHY && + (target_type.id() == LogicalTypeId::GEOGRAPHY || target_type.id() == LogicalTypeId::GEOMETRY)) { + return false; + } // Casting from a string requires parsing it, which throws whenever the string is not a valid representation of // the target type. Types that sit above VARCHAR in the coercion lattice (e.g. UUID, BLOB, BIT, nested types) // would otherwise be considered safe by the max-type check below. diff --git a/src/duckdb/src/planner/expression/bound_function_expression.cpp b/src/duckdb/src/planner/expression/bound_function_expression.cpp index 5586ad6d1..a36d25feb 100644 --- a/src/duckdb/src/planner/expression/bound_function_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_function_expression.cpp @@ -21,7 +21,7 @@ static optional_ptr GetLambdaExpression(const BoundFunctionExp BoundFunctionExpression::BoundFunctionExpression(BoundScalarFunction bound_function, vector> arguments, - unique_ptr bind_info_p, bool is_operator, + cow_ptr bind_info_p, bool is_operator, Identifier alias_p, QueryLocation location) : Expression(GetFunctionExpressionType(bound_function, arguments, bind_info_p.get()), ExpressionClass::BOUND_FUNCTION, bound_function.GetReturnType()), @@ -34,7 +34,7 @@ BoundFunctionExpression::BoundFunctionExpression(BoundScalarFunction bound_funct ExpressionType BoundFunctionExpression::GetFunctionExpressionType(const BoundScalarFunction &bound_function, const vector> &arguments, - optional_ptr bind_info_p) { + optional_ptr bind_info_p) { FunctionToStringInput input(bound_function, bind_info_p.get(), arguments); return bound_function.GetExpressionType(input); } @@ -188,7 +188,7 @@ namespace { //! Plans serialized before the lambda expression was kept in the children do not contain it. Recover it from //! the bind data, so that the children line up with the function's arguments either way. -void RestoreErasedLambdaChild(const BoundScalarFunction &function, optional_ptr bind_info, +void RestoreErasedLambdaChild(const BoundScalarFunction &function, optional_ptr bind_info, vector> &children) { if (!function.HasBindLambdaCallback() || !bind_info) { return; @@ -226,7 +226,7 @@ unique_ptr BoundFunctionExpression::Deserialize(Deserializer &deseri if (entry.first.HasBindExpressionCallback()) { // bind the function expression auto &context = deserializer.Get(); - auto bind_input = FunctionBindExpressionInput(context, entry.first, entry.second, children); + auto bind_input = FunctionBindExpressionInput(context, entry.first, entry.second.get(), children); // replace the function expression with the bound expression auto bound_expression = entry.first.GetBindExpressionCallback()(bind_input); if (bound_expression) { diff --git a/src/duckdb/src/planner/expression/bound_window_expression.cpp b/src/duckdb/src/planner/expression/bound_window_expression.cpp index 4f646f4e1..21466321a 100644 --- a/src/duckdb/src/planner/expression/bound_window_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_window_expression.cpp @@ -13,7 +13,7 @@ namespace duckdb { BoundWindowExpression::BoundWindowExpression(LogicalType return_type, unique_ptr aggregate, - unique_ptr window, unique_ptr bind_info) + unique_ptr window, cow_ptr bind_info) : Expression(window.get() ? window->window_enum : ExpressionType::WINDOW_AGGREGATE, ExpressionClass::BOUND_WINDOW, std::move(return_type)), aggregate(std::move(aggregate)), window(std::move(window)), bind_info(std::move(bind_info)), ignore_nulls(false), diff --git a/src/duckdb/src/planner/expression/legacy_bound_between_expression.cpp b/src/duckdb/src/planner/expression/legacy_bound_between_expression.cpp index 091d4cf64..793e9b149 100644 --- a/src/duckdb/src/planner/expression/legacy_bound_between_expression.cpp +++ b/src/duckdb/src/planner/expression/legacy_bound_between_expression.cpp @@ -12,13 +12,12 @@ LegacyBoundBetweenExpression::LegacyBoundBetweenExpression(unique_ptr LegacyBoundBetweenExpression::DeserializeLegacyExpression(unique_ptr input, - unique_ptr lower, - unique_ptr upper, - bool lower_inclusive, - bool upper_inclusive) { - return BoundBetweenExpression::Create(std::move(input), std::move(lower), std::move(upper), lower_inclusive, - upper_inclusive); +unique_ptr +LegacyBoundBetweenExpression::DeserializeLegacyExpression(ClientContext &context, unique_ptr input, + unique_ptr lower, unique_ptr upper, + bool lower_inclusive, bool upper_inclusive) { + return BoundBetweenExpression::Create(context, std::move(input), std::move(lower), std::move(upper), + lower_inclusive, upper_inclusive); } string LegacyBoundBetweenExpression::ToString() const { diff --git a/src/duckdb/src/planner/expression/window_range_info.cpp b/src/duckdb/src/planner/expression/window_range_info.cpp index 2301b1f02..a126bb366 100644 --- a/src/duckdb/src/planner/expression/window_range_info.cpp +++ b/src/duckdb/src/planner/expression/window_range_info.cpp @@ -31,8 +31,8 @@ bool WindowRangeCast::Capture(const Expression &expression, const Expression &op if (!BoundCastExpression::HasValidBindData(cast)) { return false; } - casts.push_back({BoundCastExpression::SourceType(cast), cast.GetReturnType(), - BoundCastExpression::IsTryCast(cast), BoundCastExpression::IsDefaultCast(cast)}); + casts.push_back( + {BoundCastExpression::SourceType(cast), cast.GetReturnType(), BoundCastExpression::IsTryCast(cast)}); current = &BoundCastExpression::Child(cast); } return true; @@ -49,8 +49,7 @@ optional_ptr WindowRangeCast::Match(const Expression &expressi if (!BoundCastExpression::HasValidBindData(cast) || !BoundCastExpression::SourceType(cast).EqualsIncludingCollation(origin.source_type) || !cast.GetReturnType().EqualsIncludingCollation(origin.target_type) || - BoundCastExpression::IsTryCast(cast) != origin.try_cast || - BoundCastExpression::IsDefaultCast(cast) != origin.default_cast) { + BoundCastExpression::IsTryCast(cast) != origin.try_cast) { return nullptr; } current = &BoundCastExpression::Child(cast); @@ -114,7 +113,10 @@ void WindowRangeCast::Serialize(Serializer &serializer) const { serializer.WriteProperty(100, "source_type", source_type); serializer.WriteProperty(101, "target_type", target_type); serializer.WriteProperty(102, "try_cast", try_cast); - serializer.WriteProperty(103, "default_cast", default_cast); + if (!serializer.ShouldSerialize(StorageVersion::V2_1_0)) { + // readers before v2.1.0 require the removed default-cast flag + serializer.WriteProperty(103, "default_cast", false); + } } WindowRangeCast WindowRangeCast::Deserialize(Deserializer &deserializer) { @@ -122,7 +124,7 @@ WindowRangeCast WindowRangeCast::Deserialize(Deserializer &deserializer) { deserializer.ReadProperty(100, "source_type", result.source_type); deserializer.ReadProperty(101, "target_type", result.target_type); deserializer.ReadProperty(102, "try_cast", result.try_cast); - deserializer.ReadProperty(103, "default_cast", result.default_cast); + deserializer.ReadDeletedProperty(103, "default_cast"); return result; } diff --git a/src/duckdb/src/planner/expression_binder/index_binder.cpp b/src/duckdb/src/planner/expression_binder/index_binder.cpp index 26ce29df9..01c472485 100644 --- a/src/duckdb/src/planner/expression_binder/index_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/index_binder.cpp @@ -469,8 +469,7 @@ unique_ptr IndexBinder::BindCreateIndex(ClientContext &context, auto &get = plan->Cast(); InitCreateIndexInfo(get, *create_index_info); - auto &bind_data = get.bind_data->Cast(); - bind_data.is_create_index = true; + get.bind_data.write().Cast().is_create_index = true; auto result = make_uniq(std::move(create_index_info), std::move(expressions), table_entry, std::move(alter_table_info)); diff --git a/src/duckdb/src/planner/expression_nullability.cpp b/src/duckdb/src/planner/expression_nullability.cpp index c317acc7c..d7f825142 100644 --- a/src/duckdb/src/planner/expression_nullability.cpp +++ b/src/duckdb/src/planner/expression_nullability.cpp @@ -1,8 +1,10 @@ #include "duckdb/planner/expression_nullability.hpp" #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" +#include "duckdb/common/vector/vector_iterator.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_conjunction_expression.hpp" #include "duckdb/planner/expression/bound_operator_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" @@ -30,9 +32,8 @@ bool ExpressionBecomesNull(const Expression &expr, return child_becomes_null; } -NotNullExpressionAnalyzer::NotNullExpressionAnalyzer(ClientContext &context_p, - optional_ptr plan_root_p) - : context(context_p), plan_root(plan_root_p) { +NotNullExpressionAnalyzer::NotNullExpressionAnalyzer(ClientContext &context_p, LogicalOperator &plan_root_p) + : context(context_p), plan_root(plan_root_p), has_dml_cte(plan_root.CTEContainsDML()) { } static bool GetColumnRefBinding(const Expression &expr, ColumnBinding &binding) { @@ -105,11 +106,8 @@ static bool JoinOutputPreservesChildNonNullability(JoinType join_type, idx_t chi } optional_ptr NotNullExpressionAnalyzer::FindCTE(TableIndex cte_index) { - if (!plan_root) { - return nullptr; - } vector> operators; - operators.push_back(*plan_root); + operators.push_back(plan_root); while (!operators.empty()) { auto &op = operators.back().get(); operators.pop_back(); @@ -125,6 +123,12 @@ optional_ptr NotNullExpressionAnalyzer::FindCTE(TableIndex cte_index } bool NotNullExpressionAnalyzer::IsNotNull(LogicalOperator &op, const Expression &expr, vector &seen_ctes) { + if (expr.IsVolatile()) { + return false; + } + if (expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { + return !expr.Cast().GetValue().IsNull(); + } switch (op.type) { case LogicalOperatorType::LOGICAL_PROJECTION: { auto &projection = op.Cast(); @@ -200,7 +204,7 @@ bool NotNullExpressionAnalyzer::IsNotNull(LogicalOperator &op, const Expression } } auto table = get.GetTable(); - if (!table) { + if (!table || has_dml_cte) { return false; } auto &column_index = get.GetColumnIndex(binding); @@ -212,6 +216,30 @@ bool NotNullExpressionAnalyzer::IsNotNull(LogicalOperator &op, const Expression // unknown statistics must not count as proof of non-nullability return stats && stats->CanHaveNoNull() && !stats->CanHaveNull(); } + case LogicalOperatorType::LOGICAL_CHUNK_GET: { + ColumnBinding binding; + if (!GetColumnRefBinding(expr, binding)) { + return false; + } + auto &get = op.Cast(); + // Borrowed collections can be populated after planning. + if (binding.table_index != get.table_index || !get.collection.get_owned_unique() || + binding.column_index.GetIndex() >= get.GetColumnIds().size()) { + return false; + } + for (auto &chunk : get.collection->Chunks({get.GetColumnIds()[binding.column_index.GetIndex()]})) { + auto validity = chunk.data[0].Validity(); + if (validity.CannotHaveNull()) { + continue; + } + for (idx_t i = 0; i < validity.size(); i++) { + if (!validity.IsValid(i)) { + return false; + } + } + } + return true; + } case LogicalOperatorType::LOGICAL_CTE_REF: { ColumnBinding binding; if (!GetColumnRefBinding(expr, binding)) { diff --git a/src/duckdb/src/planner/filter/expression_filter.cpp b/src/duckdb/src/planner/filter/expression_filter.cpp index 07d98a406..8515f12b0 100644 --- a/src/duckdb/src/planner/filter/expression_filter.cpp +++ b/src/duckdb/src/planner/filter/expression_filter.cpp @@ -83,6 +83,16 @@ unique_ptr ExpressionFilter::CreateComparisonFilter(Expression return make_uniq(std::move(comparison)); } +unique_ptr ExpressionFilter::CreateSelectivityOptionalFilter(unique_ptr child_expr, + const LogicalType &column_type, + SelectivityOptionalFilterType type) { + float selectivity_threshold; + idx_t n_vectors_to_check; + GetThresholdAndVectorsToCheck(type, selectivity_threshold, n_vectors_to_check); + return make_uniq(CreateSelectivityOptionalFilterExpression( + std::move(child_expr), column_type, selectivity_threshold, n_vectors_to_check)); +} + bool ExpressionFilter::IsSimpleFilterColumnRef(const Expression &expr) { return expr.GetExpressionClass() == ExpressionClass::BOUND_REF || expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF; @@ -305,7 +315,7 @@ static optional_ptr TryGetExpressionStats(optional_ptrCast(); - FunctionStatisticsInput input(func_copy, func_copy.BindInfo(), child_stats, &expr_copy); + FunctionStatisticsInput input(func_copy, func_copy.BindInfoMutable(), child_stats, &expr_copy); owned_stats.push_back(func.Function().GetStatisticsCallback()(*context_p, input)); return owned_stats.back().get(); } diff --git a/src/duckdb/src/planner/filter/table_filter_bloom_function.cpp b/src/duckdb/src/planner/filter/table_filter_bloom_function.cpp index 2971c621e..c05a4d913 100644 --- a/src/duckdb/src/planner/filter/table_filter_bloom_function.cpp +++ b/src/duckdb/src/planner/filter/table_filter_bloom_function.cpp @@ -16,6 +16,8 @@ #include "duckdb/common/vector_size.hpp" #include "duckdb/execution/expression_executor_state.hpp" #include "duckdb/execution/ht_entry.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/storage/block_allocator.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/storage/statistics/numeric_stats.hpp" #include "duckdb/storage/buffer_manager.hpp" @@ -41,32 +43,52 @@ static_assert(MAX_NUM_SECTORS <= (1ULL << SECTOR_HASH_SHIFT) && N_BITS * 8 <= SE //! A filter is sized from a cardinality estimate, so never let it claim more than this share of the memory budget static constexpr idx_t MAX_MEMORY_FRACTION = 64; -void BloomFilter::Initialize(ClientContext &context_p, idx_t number_of_rows, idx_t max_bitmap_bytes) { +void BloomFilter::Initialize(ClientContext &context_p, idx_t number_of_rows, idx_t max_bitmap_bytes, + Initialization initialization_p) { // a published filter is shared with probe-side consumers and must stay immutable D_ASSERT(!published); + read_copy.Reset(); BufferManager &buffer_manager = BufferManager::GetBufferManager(context_p); // a capped filter stays complete - fewer sectors only raise the false positive rate, and Seal drops a // filter that ended up too dense to reject anything const idx_t min_sectors = MIN_NUM_BITS >> LOG_SECTOR_SIZE; const idx_t budget_bytes = MinValue(buffer_manager.GetMaxMemory() / MAX_MEMORY_FRACTION, max_bitmap_bytes); + memory_budget = budget_bytes; const idx_t budget_sectors = MaxValue(PreviousPowerOfTwo(budget_bytes / sizeof(uint64_t)), min_sectors); num_sectors = MinValue(GetNumberOfSectors(number_of_rows), budget_sectors); bitmask = num_sectors - 1; - if (allocated_sectors < num_sectors) { - buf_ = buffer_manager.GetBufferAllocator().Allocate(64 + num_sectors * sizeof(uint64_t)); - // make sure blocks is a 64-byte aligned pointer, i.e., cache-line aligned - bf = reinterpret_cast((64ULL + reinterpret_cast(buf_.get())) & ~63ULL); - allocated_sectors = num_sectors; + const auto allocation_size = 64 + GetBitmapSize(); + if (buf_.GetSize() < allocation_size) { + buf_ = buffer_manager.GetBufferAllocator().AllocateHuge(allocation_size); + } + // Reused read buffers need the same cache-line alignment as fresh build buffers. + bf = reinterpret_cast((64ULL + reinterpret_cast(buf_.get())) & ~63ULL); + initialization = initialization_p; + if (initialization == Initialization::IMMEDIATE) { + std::fill_n(bf, num_sectors, 0); } - std::fill_n(bf, num_sectors, 0); initialized = true; sealed = false; useful = false; } +void BloomFilter::InitializeRange(idx_t begin, idx_t end, idx_t total) { + if (initialization != Initialization::DEFERRED || sealed) { + return; + } + D_ASSERT(initialized); + D_ASSERT(IsPowerOfTwo(total) && total >= num_sectors); + D_ASSERT(begin <= end && end <= total); + // Both extents are powers of two; division maps adjacent work ranges to disjoint sectors. + const auto entries_per_sector = total / num_sectors; + const auto sector_begin = begin / entries_per_sector; + const auto sector_end = end / entries_per_sector; + std::fill_n(bf + sector_begin, sector_end - sector_begin, 0); +} + void BloomFilter::Fold(idx_t new_num_sectors) { D_ASSERT(initialized); D_ASSERT(!sealed); @@ -120,17 +142,18 @@ void BloomFilter::Seal(ClientContext &context) { } if (target_sectors < num_sectors) { Fold(target_sectors); - // the filter was sized from an estimate, so hand the memory folding freed up back to the allocator - auto &allocator = BufferManager::GetBufferManager(context).GetBufferAllocator(); - auto compacted_buf = allocator.Allocate(64 + num_sectors * sizeof(uint64_t)); - auto compacted_bf = - reinterpret_cast((64ULL + reinterpret_cast(compacted_buf.get())) & ~63ULL); - std::copy_n(bf, num_sectors, compacted_bf); - buf_ = std::move(compacted_buf); - bf = compacted_bf; - allocated_sectors = num_sectors; } } + // Keep modest spare capacity; reuse can shrink the active size even without folding. + if (num_sectors <= (buf_.GetSize() - 64) / sizeof(uint64_t) / 4) { + auto &allocator = BufferManager::GetBufferManager(context).GetBufferAllocator(); + auto compacted_buf = allocator.AllocateHuge(64 + num_sectors * sizeof(uint64_t)); + auto compacted_bf = + reinterpret_cast((64ULL + reinterpret_cast(compacted_buf.get())) & ~63ULL); + std::copy_n(bf, num_sectors, compacted_bf); + buf_ = std::move(compacted_buf); + bf = compacted_bf; + } sealed = true; // a filter that accepts more than the scan-time policy tolerates gets paused on its first vectors anyway, // so it is not worth the memory it holds or the hashing it costs @@ -140,6 +163,46 @@ void BloomFilter::Seal(ClientContext &context) { useful = std::pow(density, static_cast(N_BITS)) < static_cast(selectivity_threshold); } +HugeAllocation BloomFilter::CopyBuffer(ClientContext &context) const { + D_ASSERT(initialized && sealed && !published); + const auto size = GetBitmapSize(); + auto result = BufferAllocator::Get(context).AllocateHuge(size); + constexpr idx_t COPY_CHUNK_SIZE = idx_t(4) * 1024 * 1024; + for (idx_t offset = 0; offset < size; offset += COPY_CHUNK_SIZE) { + context.InterruptCheck(); + memcpy(result.get() + offset, data_ptr_cast(bf) + offset, MinValue(COPY_CHUNK_SIZE, size - offset)); + } + return result; +} + +void BloomFilter::ReplaceBuffer(HugeAllocation buffer) { + D_ASSERT(initialized && sealed && !published && !read_copy.IsSet()); + D_ASSERT(buffer.IsSet() && buffer.GetSize() == GetBitmapSize()); + // Move assignment exchanges owners; the old buffer is released before returning. + buf_ = std::move(buffer); + bf = reinterpret_cast(buf_.get()); +} + +void BloomFilter::InstallReadCopy(HugeAllocation buffer) { + D_ASSERT(initialized && sealed && !published && !read_copy.IsSet()); + D_ASSERT(buffer.IsSet() && buffer.GetSize() == GetBitmapSize()); + read_copy = std::move(buffer); +} + +BloomFilter::ReadView BloomFilter::GetReadView(idx_t buffer_index) const { + D_ASSERT(initialized && sealed); + D_ASSERT(buffer_index == 0 || (buffer_index == 1 && read_copy.IsSet())); + return ReadView(buffer_index == 0 ? bf : reinterpret_cast(read_copy.get()), bitmask); +} + +BloomFilter::ReadView GetBloomFilterReadView(const BloomFilter &filter, const BloomFilterReadLocality &locality) { + if (!locality.replica_group.IsValid()) { + return filter.GetReadView(); + } + const auto group = BlockAllocator::GetLocalShardGroup(locality.shard_count); + return filter.GetReadView(group == locality.replica_group.GetIndex() ? 1 : 0); +} + idx_t BloomFilter::GetNumberOfSectors(idx_t number_of_rows) { const idx_t min_bits = MaxValue(MIN_NUM_BITS, number_of_rows * MIN_NUM_BITS_PER_KEY); return MinValue(NextPowerOfTwo(min_bits) >> LOG_SECTOR_SIZE, MAX_NUM_SECTORS); @@ -160,6 +223,12 @@ inline uint64_t GetMask(const hash_t hash) { return mask; } +static inline bool LookupBloomBuffer(const uint64_t *buffer, hash_t hash, uint64_t bitmask) { + const auto mask = GetMask(hash); + const auto &slot = *reinterpret_cast *>(&buffer[GetBloomSectorIndex(hash, bitmask)]); + return (slot.load(std::memory_order_relaxed) & mask) == mask; +} + void BloomFilter::InsertHashes(const Vector &hashes_v, const SelectionVector &sel, const idx_t count) { D_ASSERT(hashes_v.GetType() == LogicalType::HASH); if (count == 0) { @@ -184,38 +253,39 @@ void BloomFilter::InsertHashes(const Vector &hashes_v) { } } -idx_t BloomFilter::LookupHashes(const Vector &hashes_v, SelectionVector &result_sel, const idx_t count) const { +idx_t BloomFilter::ReadView::LookupHashes(const Vector &hashes_v, SelectionVector &result_sel, + const idx_t count) const { D_ASSERT(hashes_v.GetVectorType() == VectorType::FLAT_VECTOR); D_ASSERT(hashes_v.GetType() == LogicalType::HASH); const auto hashes = FlatVector::GetData(hashes_v); - const bool prefetch = count >= 128 && num_sectors * sizeof(uint64_t) >= 1024ULL * 1024ULL; + const bool prefetch = count >= 128 && (bitmask + 1) * sizeof(uint64_t) >= 1024ULL * 1024ULL; idx_t found_count = 0; for (idx_t i = 0; i < count; i++) { result_sel.set_index(found_count, i); - found_count += LookupOne(hashes[i]); + found_count += LookupBloomBuffer(buffer, hashes[i], bitmask); if (prefetch) { - PrefetchHashTableEntry(i, count, - [&](idx_t next_idx) { return &bf[GetBloomSectorIndex(hashes[next_idx], bitmask)]; }); + PrefetchHashTableEntry( + i, count, [&](idx_t next_idx) { return &buffer[GetBloomSectorIndex(hashes[next_idx], bitmask)]; }); } } return found_count; } -idx_t BloomFilter::LookupHashes(const Vector &hashes_v, const SelectionVector &sel, SelectionVector &result_sel, - const idx_t count) const { +idx_t BloomFilter::ReadView::LookupHashes(const Vector &hashes_v, const SelectionVector &sel, + SelectionVector &result_sel, const idx_t count) const { D_ASSERT(hashes_v.GetVectorType() == VectorType::FLAT_VECTOR); D_ASSERT(hashes_v.GetType() == LogicalType::HASH); const auto hashes = FlatVector::GetData(hashes_v); - const bool prefetch = count >= 128 && num_sectors * sizeof(uint64_t) >= 1024ULL * 1024ULL; + const bool prefetch = count >= 128 && (bitmask + 1) * sizeof(uint64_t) >= 1024ULL * 1024ULL; idx_t found_count = 0; for (idx_t i = 0; i < count; i++) { result_sel.set_index(found_count, i); - found_count += LookupOne(hashes[sel.get_index_unsafe(i)]); + found_count += LookupBloomBuffer(buffer, hashes[sel.get_index_unsafe(i)], bitmask); if (prefetch) { PrefetchHashTableEntry(i, count, [&](idx_t next_idx) { - return &bf[GetBloomSectorIndex(hashes[sel.get_index_unsafe(next_idx)], bitmask)]; + return &buffer[GetBloomSectorIndex(hashes[sel.get_index_unsafe(next_idx)], bitmask)]; }); } } @@ -236,27 +306,35 @@ inline void BloomFilter::InsertOne(const hash_t hash) { } } +bool BloomFilter::ReadView::LookupOne(const uint64_t hash) const { + return LookupBloomBuffer(buffer, hash, bitmask); +} + bool BloomFilter::LookupOne(const uint64_t hash) const { - D_ASSERT(initialized); - D_ASSERT(sealed); - const auto bf_offset = GetBloomSectorIndex(hash, bitmask); - const uint64_t mask = GetMask(hash); - atomic &slot = *reinterpret_cast *>(&bf[bf_offset]); - auto bf_entry = slot.load(std::memory_order_relaxed); + return GetReadView().LookupOne(hash); +} + +idx_t BloomFilter::LookupHashes(const Vector &hashes, SelectionVector &result, idx_t count) const { + return GetReadView().LookupHashes(hashes, result, count); +} - return (bf_entry & mask) == mask; +idx_t BloomFilter::LookupHashes(const Vector &hashes, const SelectionVector &sel, SelectionVector &result, + idx_t count) const { + return GetReadView().LookupHashes(hashes, sel, result, count); } BloomFilterFunctionData::BloomFilterFunctionData(shared_ptr filter_p, bool filters_null_values_p, const string &key_column_name_p, const LogicalType &key_type_p, - float selectivity_threshold_p, idx_t n_vectors_to_check_p) - : filter(std::move(filter_p)), filters_null_values(filters_null_values_p), key_column_name(key_column_name_p), - key_type(key_type_p), selectivity_threshold(selectivity_threshold_p), n_vectors_to_check(n_vectors_to_check_p) { + float selectivity_threshold_p, idx_t n_vectors_to_check_p, + BloomFilterReadLocality locality_p) + : filter(std::move(filter_p)), locality(locality_p), filters_null_values(filters_null_values_p), + key_column_name(key_column_name_p), key_type(key_type_p), selectivity_threshold(selectivity_threshold_p), + n_vectors_to_check(n_vectors_to_check_p) { } unique_ptr BloomFilterFunctionData::Copy() const { return make_uniq(filter, filters_null_values, key_column_name, key_type, - selectivity_threshold, n_vectors_to_check); + selectivity_threshold, n_vectors_to_check, locality); } bool BloomFilterFunctionData::Equals(const FunctionData &other_p) const { @@ -293,14 +371,15 @@ static idx_t SelectBloomFilter(Vector &input, const BloomFilterFunctionData &fun VectorOperations::Hash(input, hashes, count); auto validity = input.Validity(); auto &bloom_sel = validity.CannotHaveNull() ? result_sel : state.bloom_sel; + const auto view = GetBloomFilterReadView(*func_data.filter, func_data.locality); idx_t bloom_count; if (hashes.GetVectorType() == VectorType::CONSTANT_VECTOR) { - bloom_count = func_data.filter->LookupOne(*ConstantVector::GetData(hashes)) ? count : 0; + bloom_count = view.LookupOne(*ConstantVector::GetData(hashes)) ? count : 0; for (idx_t i = 0; i < bloom_count; i++) { bloom_sel.set_index(i, i); } } else { - bloom_count = func_data.filter->LookupHashes(hashes, bloom_sel, count); + bloom_count = view.LookupHashes(hashes, bloom_sel, count); } if (validity.CannotHaveNull()) { @@ -337,8 +416,9 @@ static idx_t SelectBloomFilter(Vector &input, const BloomFilterFunctionData &fun return result_count; } -static unique_ptr -BloomFilterInitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, FunctionData *bind_data) { +static unique_ptr BloomFilterInitLocalState(ExpressionState &state, + const BoundFunctionExpression &expr, + optional_ptr bind_data) { auto &data = bind_data->Cast(); if (!data.filter) { return nullptr; @@ -372,7 +452,7 @@ static idx_t BloomFilterSelect(DataChunk &args, ExpressionState &state, optional } template -static FilterPropagateResult TemplatedBloomFilterPrune(const BloomFilter &bf, const BaseStatistics &stats) { +static FilterPropagateResult TemplatedBloomFilterPrune(const BloomFilter::ReadView &bf, const BaseStatistics &stats) { if (!NumericStats::HasMinMax(stats)) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; } @@ -437,28 +517,29 @@ FilterPropagateResult BloomFilterScalarFun::FilterPrune(const FunctionStatistics return FilterPropagateResult::NO_PRUNING_POSSIBLE; } auto &stats = *column_stats; + const auto view = GetBloomFilterReadView(*data.filter, data.locality); switch (data.key_type.InternalType()) { case PhysicalType::UINT8: - return TemplatedBloomFilterPrune(*data.filter, stats); + return TemplatedBloomFilterPrune(view, stats); case PhysicalType::UINT16: - return TemplatedBloomFilterPrune(*data.filter, stats); + return TemplatedBloomFilterPrune(view, stats); case PhysicalType::UINT32: - return TemplatedBloomFilterPrune(*data.filter, stats); + return TemplatedBloomFilterPrune(view, stats); case PhysicalType::UINT64: - return TemplatedBloomFilterPrune(*data.filter, stats); + return TemplatedBloomFilterPrune(view, stats); case PhysicalType::UINT128: - return TemplatedBloomFilterPrune(*data.filter, stats); + return TemplatedBloomFilterPrune(view, stats); case PhysicalType::INT8: - return TemplatedBloomFilterPrune(*data.filter, stats); + return TemplatedBloomFilterPrune(view, stats); case PhysicalType::INT16: - return TemplatedBloomFilterPrune(*data.filter, stats); + return TemplatedBloomFilterPrune(view, stats); case PhysicalType::INT32: - return TemplatedBloomFilterPrune(*data.filter, stats); + return TemplatedBloomFilterPrune(view, stats); case PhysicalType::INT64: - return TemplatedBloomFilterPrune(*data.filter, stats); + return TemplatedBloomFilterPrune(view, stats); case PhysicalType::INT128: - return TemplatedBloomFilterPrune(*data.filter, stats); + return TemplatedBloomFilterPrune(view, stats); default: return FilterPropagateResult::NO_PRUNING_POSSIBLE; } diff --git a/src/duckdb/src/planner/filter/table_filter_functions.cpp b/src/duckdb/src/planner/filter/table_filter_functions.cpp index 8566b503d..9816ef10e 100644 --- a/src/duckdb/src/planner/filter/table_filter_functions.cpp +++ b/src/duckdb/src/planner/filter/table_filter_functions.cpp @@ -38,10 +38,12 @@ void GetThresholdAndVectorsToCheck(SelectivityOptionalFilterType type, float &se static constexpr float MIN_MAX_THRESHOLD = 0.9f; static constexpr float BF_THRESHOLD = 0.5f; static constexpr float PRF_THRESHOLD = 0.5f; + static constexpr float IN_THRESHOLD = 0.5f; static constexpr idx_t MIN_MAX_CHECK_N = 6; static constexpr idx_t BF_CHECK_N = 6; static constexpr idx_t PRF_CHECK_N = 6; + static constexpr idx_t IN_CHECK_N = 6; switch (type) { case SelectivityOptionalFilterType::MIN_MAX: @@ -56,6 +58,10 @@ void GetThresholdAndVectorsToCheck(SelectivityOptionalFilterType type, float &se selectivity_threshold = PRF_THRESHOLD; n_vectors_to_check = PRF_CHECK_N; return; + case SelectivityOptionalFilterType::IN_FILTER: + selectivity_threshold = IN_THRESHOLD; + n_vectors_to_check = IN_CHECK_N; + return; default: throw NotImplementedException("GetThresholdAndVectorsToCheck"); } @@ -110,7 +116,7 @@ unique_ptr CreateDynamicFilterExpression(shared_ptr bind_data, +void TableFilterFunctionSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { // Runtime state cannot be serialized - write nothing } diff --git a/src/duckdb/src/planner/filter/table_filter_optional_function.cpp b/src/duckdb/src/planner/filter/table_filter_optional_function.cpp index 4181ecfb6..870b38005 100644 --- a/src/duckdb/src/planner/filter/table_filter_optional_function.cpp +++ b/src/duckdb/src/planner/filter/table_filter_optional_function.cpp @@ -32,7 +32,7 @@ bool OptionalFilterFunctionData::Equals(const FunctionData &other_p) const { return child_filter_expr->Equals(*other.child_filter_expr); } -static void OptionalFilterSerialize(Serializer &serializer, const optional_ptr bind_data, +static void OptionalFilterSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { if (!bind_data) { return; diff --git a/src/duckdb/src/planner/filter/table_filter_prefix_range_function.cpp b/src/duckdb/src/planner/filter/table_filter_prefix_range_function.cpp index 429f40794..2a8fb7ae6 100644 --- a/src/duckdb/src/planner/filter/table_filter_prefix_range_function.cpp +++ b/src/duckdb/src/planner/filter/table_filter_prefix_range_function.cpp @@ -40,21 +40,30 @@ namespace duckdb { -AllocatedData AllocateBitmap(ClientContext &context, const idx_t word_count, uint64_t *&bitmap_begin) { - const idx_t size = word_count * sizeof(uint64_t); - BufferManager &buffer_manager = BufferManager::GetBufferManager(context); - auto buffer = buffer_manager.GetBufferAllocator().Allocate(64ULL + size); +static idx_t BitmapAllocationSize(idx_t word_count) { + const auto size = word_count * sizeof(uint64_t) + 64; + if (size < 64ULL * 1024 * 1024 || size > 4ULL * 1024 * 1024 * 1024) { + return size; + } + const auto rounded = NextPowerOfTwo(size); + // Reuse allocator size classes only when padding adds at most 1/16. + return rounded - size <= size / 16 ? rounded : size; +} + +static HugeAllocation AllocateBitmap(ClientContext &context, const idx_t word_count, uint64_t *&bitmap_begin) { + auto &allocator = BufferAllocator::Get(context); + auto buffer = allocator.AllocateHuge(BitmapAllocationSize(word_count)); bitmap_begin = reinterpret_cast((64ULL + reinterpret_cast(buffer.get())) & ~63ULL); std::fill_n(bitmap_begin, word_count, 0); return buffer; } struct PrefixRangeBitmapBuildState : public PrefixRangeFilter::BuildState { - explicit PrefixRangeBitmapBuildState(AllocatedData data_p, uint64_t *bitmap_p) + explicit PrefixRangeBitmapBuildState(HugeAllocation data_p, uint64_t *bitmap_p) : data(std::move(data_p)), bitmap(bitmap_p) { } - AllocatedData data; + HugeAllocation data; uint64_t *bitmap; }; @@ -73,7 +82,8 @@ class PrefixRangeBitmap { const idx_t buckets = UnsafeNumericCast((span >> shift) + 1); word_count = buckets == 0 ? 1 : (buckets + 63) >> WORD_SHIFT; - buf_ = AllocateBitmap(context, word_count, bitmap); + buf_.Reset(); + bitmap = nullptr; // Only mark initialized as true when local bitmaps are merged. initialized = false; @@ -81,7 +91,7 @@ class PrefixRangeBitmap { } unique_ptr InitializeBuildState(ClientContext &context) const { - D_ASSERT(bitmap); + D_ASSERT(word_count > 0); uint64_t *state_bitmap; auto state_data = AllocateBitmap(context, word_count, state_bitmap); return make_uniq(std::move(state_data), state_bitmap); @@ -113,16 +123,31 @@ class PrefixRangeBitmap { void MergeBuildState(PrefixRangeBitmapBuildState &state) { const auto last_word_mask = ~uint64_t(0) >> (WORD_MASK - UnsafeNumericCast((span >> shift) & WORD_MASK)); dense = true; - for (idx_t word_idx = 0; word_idx < word_count; word_idx++) { - bitmap[word_idx] |= state.bitmap[word_idx]; - const auto expected = word_idx + 1 == word_count ? last_word_mask : ~uint64_t(0); - dense &= bitmap[word_idx] == expected; + if (!bitmap) { + // Adopt the first completed lane instead of allocating and copying a second bitmap. + buf_ = std::move(state.data); + bitmap = state.bitmap; + // All bits are already present; one hole is enough to rule out a dense bitmap. + for (idx_t word_idx = 0; word_idx < word_count; word_idx++) { + const auto expected = word_idx + 1 == word_count ? last_word_mask : ~uint64_t(0); + if (bitmap[word_idx] != expected) { + dense = false; + break; + } + } + } else { + // Merge every word, even after finding a hole, so no keys from this lane are lost. + for (idx_t word_idx = 0; word_idx < word_count; word_idx++) { + bitmap[word_idx] |= state.bitmap[word_idx]; + const auto expected = word_idx + 1 == word_count ? last_word_mask : ~uint64_t(0); + dense &= bitmap[word_idx] == expected; + } } initialized = true; } idx_t GetBuildStateSize() const { - return word_count * sizeof(uint64_t) + 64; + return BitmapAllocationSize(word_count); } template @@ -366,7 +391,7 @@ class PrefixRangeBitmap { U span; idx_t shift; idx_t word_count; - AllocatedData buf_; + HugeAllocation buf_; uint64_t *bitmap; }; @@ -413,6 +438,7 @@ class NumericPrefixRangeFilter : public PrefixRangeFilter { public: void Initialize(ClientContext &context, idx_t number_of_rows, Value min_val, Value max_val, idx_t max_bits) override { + D_ASSERT(!IsPublished()); D_ASSERT(min_val <= max_val); D_ASSERT(number_of_rows > 0); const auto min = NumericConverter::Convert(min_val.GetValueUnsafe()); @@ -425,17 +451,20 @@ class NumericPrefixRangeFilter : public PrefixRangeFilter { } void InsertKeys(Vector &keys, BuildState &state) const override { + D_ASSERT(!IsPublished()); auto &bitmap_state = state.Cast(); bitmap.template InsertKeys, false>(keys, bitmap_state.bitmap); } void InsertKeysParallel(Vector &keys, BuildState &state) const override { + D_ASSERT(!IsPublished()); auto &bitmap_state = state.Cast(); bitmap.template InsertKeys, true>(keys, bitmap_state.bitmap); } - void MergeBuildState(BuildState &state) override { - bitmap.MergeBuildState(state.Cast()); + void MergeBuildState(unique_ptr state) override { + D_ASSERT(!IsPublished()); + bitmap.MergeBuildState(state->Cast()); } idx_t GetBuildStateSize() const override { @@ -487,6 +516,7 @@ class StringPrefixRangeFilter : public PrefixRangeFilter { public: void Initialize(ClientContext &context, idx_t number_of_rows, Value min_val, Value max_val, idx_t max_bits) override { + D_ASSERT(!IsPublished()); D_ASSERT(min_val <= max_val); D_ASSERT(number_of_rows > 0); const auto min = StringPrefixConverter::Convert(min_val.GetValueUnsafe()); @@ -500,17 +530,20 @@ class StringPrefixRangeFilter : public PrefixRangeFilter { } void InsertKeys(Vector &keys, BuildState &state) const override { + D_ASSERT(!IsPublished()); auto &bitmap_state = state.Cast(); bitmap.template InsertKeys(keys, bitmap_state.bitmap); } void InsertKeysParallel(Vector &keys, BuildState &state) const override { + D_ASSERT(!IsPublished()); auto &bitmap_state = state.Cast(); bitmap.template InsertKeys(keys, bitmap_state.bitmap); } - void MergeBuildState(BuildState &state) override { - bitmap.MergeBuildState(state.Cast()); + void MergeBuildState(unique_ptr state) override { + D_ASSERT(!IsPublished()); + bitmap.MergeBuildState(state->Cast()); } idx_t GetBuildStateSize() const override { @@ -722,8 +755,9 @@ static idx_t SelectPrefixRange(Vector &input, const PrefixRangeFunctionData &fun return result_count; } -static unique_ptr -PrefixRangeInitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, FunctionData *bind_data) { +static unique_ptr PrefixRangeInitLocalState(ExpressionState &state, + const BoundFunctionExpression &expr, + optional_ptr bind_data) { auto &data = bind_data->Cast(); if (!data.filter) { return nullptr; diff --git a/src/duckdb/src/planner/filter/table_filter_selectivity_optional_function.cpp b/src/duckdb/src/planner/filter/table_filter_selectivity_optional_function.cpp index ff1d635a1..269b8c0cb 100644 --- a/src/duckdb/src/planner/filter/table_filter_selectivity_optional_function.cpp +++ b/src/duckdb/src/planner/filter/table_filter_selectivity_optional_function.cpp @@ -82,7 +82,7 @@ bool SelectivityOptionalFilterFunctionData::Equals(const FunctionData &other_p) return child_filter_expr->Equals(*other.child_filter_expr); } -static void SelectivityOptionalFilterSerialize(Serializer &serializer, const optional_ptr bind_data, +static void SelectivityOptionalFilterSerialize(Serializer &serializer, const optional_ptr bind_data, const BoundScalarFunction &function) { if (!bind_data) { return; @@ -120,9 +120,9 @@ struct SelectivityOptionalFilterLocalState : public FunctionLocalState { ExpressionExecutor executor; }; -static unique_ptr SelectivityOptionalFilterInitLocalState(ExpressionState &state, - const BoundFunctionExpression &expr, - FunctionData *bind_data) { +static unique_ptr +SelectivityOptionalFilterInitLocalState(ExpressionState &state, const BoundFunctionExpression &expr, + optional_ptr bind_data) { auto &data = bind_data->Cast(); if (!data.child_filter_expr) { return nullptr; diff --git a/src/duckdb/src/planner/logical_operator.cpp b/src/duckdb/src/planner/logical_operator.cpp index 7a774d62e..8865cc7f8 100644 --- a/src/duckdb/src/planner/logical_operator.cpp +++ b/src/duckdb/src/planner/logical_operator.cpp @@ -112,6 +112,39 @@ bool LogicalOperator::HasSideEffects() const { return false; } +static bool ContainsDML(const LogicalOperator &op) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_INSERT: + case LogicalOperatorType::LOGICAL_UPDATE: + case LogicalOperatorType::LOGICAL_DELETE: + case LogicalOperatorType::LOGICAL_MERGE_INTO: + return true; + default: + break; + } + for (auto &child : op.children) { + if (ContainsDML(*child)) { + return true; + } + } + return false; +} + +// A top-level DML statement is not flagged. COPY TO does not invalidate table statistics. +bool LogicalOperator::CTEContainsDML() const { + if (type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + if (!children.empty() && ContainsDML(*children[0])) { + return true; + } + } + for (auto &child : children) { + if (child->CTEContainsDML()) { + return true; + } + } + return false; +} + bool LogicalOperator::HasVolatileExpressions() const { bool is_volatile = false; LogicalOperatorVisitor::EnumerateExpressions(*this, [&](const unique_ptr *expression) { diff --git a/src/duckdb/src/planner/operator/logical_aggregate.cpp b/src/duckdb/src/planner/operator/logical_aggregate.cpp index ce806a90e..c17091c56 100644 --- a/src/duckdb/src/planner/operator/logical_aggregate.cpp +++ b/src/duckdb/src/planner/operator/logical_aggregate.cpp @@ -1,7 +1,9 @@ #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/common/string_util.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" namespace duckdb { @@ -12,6 +14,54 @@ LogicalAggregate::LogicalAggregate(TableIndex group_index, TableIndex aggregate_ distinct_validity(TupleDataValidityType::CAN_HAVE_NULL_VALUES) { } +bool LogicalAggregate::KeysAreUnique(LogicalOperator &op, vector keys) { + reference current = op; + while (current.get().type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + auto &node = current.get(); + switch (node.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + // every key has to be a column the projection forwards + auto outputs = node.GetColumnBindings(); + for (auto &key : keys) { + auto entry = std::find(outputs.begin(), outputs.end(), key); + if (entry == outputs.end()) { + return false; + } + auto &expression = *node.expressions[NumericCast(entry - outputs.begin())]; + if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + expression.Cast().Depth() != 0) { + return false; + } + key = expression.Cast().Binding(); + } + break; + } + case LogicalOperatorType::LOGICAL_FILTER: + // removes rows, keeps the bindings + break; + default: + return false; + } + current = *node.children[0]; + } + auto &aggregate = current.get().Cast(); + if (!aggregate.grouping_functions.empty() || aggregate.grouping_sets.size() > 1) { + // several grouping sets emit one row per set, so the groups do not determine a unique row + return false; + } + if (aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() != aggregate.groups.size()) { + // a partial grouping set: rows are unique in its groups only once the others are known to be NULL + return false; + } + for (idx_t group = 0; group < aggregate.groups.size(); group++) { + ColumnBinding binding(aggregate.group_index, ProjectionIndex(group)); + if (std::find(keys.begin(), keys.end(), binding) == keys.end()) { + return false; + } + } + return true; +} + const Expression &LogicalAggregate::GetExpression(ColumnBinding binding) const { if (binding.table_index == group_index) { return *groups[binding.column_index]; @@ -98,6 +148,35 @@ vector LogicalAggregate::GetTableIndex() const { return result; } +bool LogicalAggregate::IgnoresDuplicates() const { + for (auto &group : groups) { + if (group->IsVolatile()) { + return false; + } + } + for (auto &expr : expressions) { + if (expr->GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE || expr->IsVolatile()) { + return false; + } + auto &aggregate = expr->Cast(); + if (aggregate.StateExportMode() == AggregateStateExportMode::STATE_EXPORT) { + // an exported state may hold more than the finalized value: an ordered aggregate buffers every input row + return false; + } + if (aggregate.IsDistinct()) { + continue; + } + // a function that is not distinct-dependent returns the same value over repeated rows; one that depends on + // the order of its input (first, last) may still pick its value from a different row + auto &function = aggregate.Function(); + if (function.GetDistinctDependent() != AggregateDistinctDependent::NOT_DISTINCT_DEPENDENT || + function.GetOrderDependent() != AggregateOrderDependent::NOT_ORDER_DEPENDENT) { + return false; + } + } + return true; +} + string LogicalAggregate::GetName() const { #ifdef DEBUG if (DBConfigOptions::debug_print_bindings) { diff --git a/src/duckdb/src/planner/operator/logical_get.cpp b/src/duckdb/src/planner/operator/logical_get.cpp index 2ca48ea25..944874246 100644 --- a/src/duckdb/src/planner/operator/logical_get.cpp +++ b/src/duckdb/src/planner/operator/logical_get.cpp @@ -67,7 +67,7 @@ static void MapLegacyTableFilterKeys(LogicalGet &get) { LogicalGet::LogicalGet() : LogicalOperator(LogicalOperatorType::LOGICAL_GET) { } -LogicalGet::LogicalGet(TableIndex table_index, BoundTableFunction function, unique_ptr bind_data, +LogicalGet::LogicalGet(TableIndex table_index, BoundTableFunction function, cow_ptr bind_data, vector returned_types, vector returned_names, virtual_column_map_t virtual_columns_p) : LogicalOperator(LogicalOperatorType::LOGICAL_GET), table_index(table_index), function(std::move(function)), @@ -328,7 +328,7 @@ void LogicalGet::SetScanOrder(unique_ptr options) { throw InternalException("LogicalGet::SetScanOrder called but function does not have scan order defined"); } row_group_order_options = make_uniq(*options); - function.set_scan_order(std::move(options), bind_data.get()); + function.set_scan_order(std::move(options), bind_data); } void LogicalGet::SetPartitionsToScan(vector partition_indices) { @@ -336,7 +336,7 @@ void LogicalGet::SetPartitionsToScan(vector partition_indices) { throw InternalException("LogicalGet::SetPartitionsToScan called but function is not defined"); } scan_partition_indices = partition_indices; - function.set_partitions_to_scan(std::move(partition_indices), bind_data.get()); + function.set_partitions_to_scan(std::move(partition_indices), bind_data); } void LogicalGet::Serialize(Serializer &serializer) const { diff --git a/src/duckdb/src/planner/operator/logical_set_operation.cpp b/src/duckdb/src/planner/operator/logical_set_operation.cpp index b321acf6e..b7dad596f 100644 --- a/src/duckdb/src/planner/operator/logical_set_operation.cpp +++ b/src/duckdb/src/planner/operator/logical_set_operation.cpp @@ -1,6 +1,16 @@ #include "duckdb/planner/operator/logical_set_operation.hpp" +#include "duckdb/function/builtin_function_lookup.hpp" +#include "duckdb/function/window/rows_functions.hpp" +#include "duckdb/function/window_function.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_window_expression.hpp" +#include "duckdb/planner/expression_binder.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_window.hpp" namespace duckdb { @@ -31,6 +41,108 @@ LogicalSetOperation::LogicalSetOperation(TableIndex table_index, idx_t column_co children.push_back(std::move(bottom)); } +vector LogicalSetOperation::GetComparisonTypes(ClientContext &context) { + D_ASSERT(type == LogicalOperatorType::LOGICAL_EXCEPT || type == LogicalOperatorType::LOGICAL_INTERSECT); + if (comparison_types.size() == column_count) { + return comparison_types; + } + ResolveOperatorTypes(); + auto &left_types = children[0]->types; + auto &right_types = children[1]->types; + D_ASSERT(left_types.size() == column_count && right_types.size() == column_count); + // the children have the same types (the binder casts them), but a collation can be on one of them only + vector result; + for (idx_t i = 0; i < column_count; i++) { + result.push_back(LogicalType::ForceMaxLogicalType(context, left_types[i], right_types[i])); + } + return result; +} + +vector LogicalSetOperation::GetComparisons(ClientContext &context) { + auto comparison_types = GetComparisonTypes(context); + D_ASSERT(comparison_types.size() == column_count); + auto left_bindings = children[0]->GetColumnBindings(); + auto right_bindings = children[1]->GetColumnBindings(); + vector result; + for (idx_t i = 0; i < column_count; i++) { + // both sides as the type they are compared as, which is also the type of the column of the set operation + JoinCondition condition(make_uniq(comparison_types[i], left_bindings[i]), + make_uniq(comparison_types[i], right_bindings[i]), + ExpressionType::COMPARE_NOT_DISTINCT_FROM); + if (i + correlated_column_count < column_count) { + ExpressionBinder::PushCollation(context, condition.LeftReference(), comparison_types[i]); + ExpressionBinder::PushCollation(context, condition.RightReference(), comparison_types[i]); + } + result.push_back(std::move(condition)); + } + return result; +} + +//! Numbers the rows that are equal in all columns, so that EXCEPT ALL and INTERSECT ALL match the n-th copies of a row +static unique_ptr AddRowNumber(Binder &binder, const vector &types, + idx_t correlated_column_count, unique_ptr child) { + auto &context = binder.context; + auto bindings = child->GetColumnBindings(); + auto row_number = GetBuiltinWindowFunction(context, RowNumberFun::Name, {})->Bind(context); + row_number->WindowStartMutable() = WindowBoundary::UNBOUNDED_PRECEDING; + row_number->WindowEndMutable() = WindowBoundary::UNBOUNDED_FOLLOWING; + for (idx_t i = 0; i < types.size(); i++) { + unique_ptr partition = make_uniq(types[i], bindings[i]); + if (i + correlated_column_count < types.size()) { + ExpressionBinder::PushCollation(context, partition, types[i]); + } + row_number->PartitionsMutable().push_back(std::move(partition)); + } + auto window = make_uniq(binder.GenerateTableIndex(), optional_idx()); + window->expressions.push_back(std::move(row_number)); + window->AddChild(std::move(child)); + return std::move(window); +} + +unique_ptr LogicalSetOperation::CreateJoin(Binder &binder, const vector &types, + TableIndex setop_index, LogicalOperatorType type, + bool setop_all, unique_ptr left, + unique_ptr right, + idx_t correlated_column_count) { + D_ASSERT(type == LogicalOperatorType::LOGICAL_EXCEPT || type == LogicalOperatorType::LOGICAL_INTERSECT); + D_ASSERT(correlated_column_count <= types.size()); + auto compared_types = types; + if (setop_all) { + left = AddRowNumber(binder, types, correlated_column_count, std::move(left)); + right = AddRowNumber(binder, types, correlated_column_count, std::move(right)); + compared_types.push_back(LogicalType::BIGINT); + } + auto left_bindings = left->GetColumnBindings(); + auto right_bindings = right->GetColumnBindings(); + D_ASSERT(left_bindings.size() == compared_types.size() && right_bindings.size() == compared_types.size()); + + // the join compares the columns with the collations of both children and treats NULLs as equal. The correlated + // columns and the row number are compared as they are + auto join_type = type == LogicalOperatorType::LOGICAL_EXCEPT ? JoinType::ANTI : JoinType::SEMI; + auto join = make_uniq(join_type); + for (idx_t i = 0; i < compared_types.size(); i++) { + auto &compared_type = compared_types[i]; + JoinCondition condition(make_uniq(compared_type, left_bindings[i]), + make_uniq(compared_type, right_bindings[i]), + ExpressionType::COMPARE_NOT_DISTINCT_FROM); + if (i + correlated_column_count < types.size()) { + ExpressionBinder::PushCollation(binder.context, condition.LeftReference(), compared_type); + ExpressionBinder::PushCollation(binder.context, condition.RightReference(), compared_type); + } + join->conditions.push_back(std::move(condition)); + } + join->AddChild(std::move(left)); + join->AddChild(std::move(right)); + + vector> select_list; + for (idx_t i = 0; i < types.size(); i++) { + select_list.push_back(make_uniq(types[i], left_bindings[i])); + } + auto projection = make_uniq(setop_index, std::move(select_list)); + projection->AddChild(std::move(join)); + return std::move(projection); +} + vector LogicalSetOperation::GetTableIndex() const { return vector {table_index}; } diff --git a/src/duckdb/src/planner/operator/logical_window.cpp b/src/duckdb/src/planner/operator/logical_window.cpp index fea06bada..bba35b825 100644 --- a/src/duckdb/src/planner/operator/logical_window.cpp +++ b/src/duckdb/src/planner/operator/logical_window.cpp @@ -24,6 +24,7 @@ vector LogicalWindow::GetTableIndex() const { } string LogicalWindow::GetName() const { + (void)DBConfigOptions::debug_print_bindings; #ifdef DEBUG if (DBConfigOptions::debug_print_bindings) { return LogicalOperator::GetName() + StringUtil::Format(" #%llu", window_index.index); diff --git a/src/duckdb/src/planner/planner.cpp b/src/duckdb/src/planner/planner.cpp index a8fbe9a1d..295081e26 100644 --- a/src/duckdb/src/planner/planner.cpp +++ b/src/duckdb/src/planner/planner.cpp @@ -380,7 +380,6 @@ void Planner::CreatePlan(unique_ptr statement) { case StatementType::TRANSACTION_STATEMENT: case StatementType::EXPLAIN_STATEMENT: case StatementType::VACUUM_STATEMENT: - case StatementType::RELATION_STATEMENT: case StatementType::CALL_STATEMENT: case StatementType::EXPORT_STATEMENT: case StatementType::PRAGMA_STATEMENT: diff --git a/src/duckdb/src/planner/sql_export/bound_expression_sql_exporter.cpp b/src/duckdb/src/planner/sql_export/bound_expression_sql_exporter.cpp index 0b2e7616b..6c208c98f 100644 --- a/src/duckdb/src/planner/sql_export/bound_expression_sql_exporter.cpp +++ b/src/duckdb/src/planner/sql_export/bound_expression_sql_exporter.cpp @@ -372,15 +372,6 @@ BoundExpressionSQLExportResult BoundExpressionSQLExportState::ExportCast(const B if (context.discard_optimizer_metadata && CMUtils::GetExpressionType(expression) == CMExpressionType::CAST) { return ExportChild(*expression.GetChildren()[0], path, 0); } - if (BoundCastExpression::IsDefaultCast(expression)) { - if (!context.client_context || - CastFunctionSet::Get(*context.client_context) - .CanOverrideDefaultCast(expression.GetChildren()[0]->GetReturnType(), expression.GetReturnType())) { - return BoundExpressionSQLExportResult::Failure({BoundExpressionSQLExportState::UnsupportedFeature( - path, "default_cast_binding", - "A default-only bound cast cannot be reconstructed through this SQL binding")}); - } - } auto child = ExportChild(*expression.GetChildren()[0], path, 0); if (child.HasError()) { return child; @@ -388,6 +379,7 @@ BoundExpressionSQLExportResult BoundExpressionSQLExportState::ExportCast(const B if (expression.GetReturnType().IsAggregateState()) { auto storage_type = expression.GetReturnType().WithAlias("").WithExtensionInfo(nullptr); auto &source_type = expression.GetChildren()[0]->GetReturnType(); + // the export reinterprets the storage value, which bypasses a registered cast to the aggregate state if (BoundCastExpression::IsTryCast(expression) || !context.client_context || CastFunctionSet::Get(*context.client_context) .CanOverrideDefaultCast(source_type, expression.GetReturnType()) || diff --git a/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp b/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp index 8db44462d..48e5b1d10 100644 --- a/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp +++ b/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp @@ -66,15 +66,6 @@ static BindingReplacementGraph CreateConstructedBindingReplacements(const vector return result; } -static unique_ptr CreateIdentityProjection(Binder &binder, unique_ptr child, - BindingReplacementGraph &replacements) { - auto projection = LogicalProjection::CreateIdentity(binder.GenerateTableIndex(), std::move(child)); - projection->ResolveOperatorTypes(); - auto bindings = projection->children[0]->GetColumnBindings(); - replacements = CreateConstructedBindingReplacements(bindings, projection->GetColumnBindings()); - return std::move(projection); -} - static idx_t RewriteDelimScanReferences(unique_ptr &op, TableIndex delim_scan_index) { if (op->type == LogicalOperatorType::LOGICAL_DELIM_JOIN) { if (!op->children.empty()) { @@ -958,6 +949,184 @@ static bool ReferencesDomain(Expression &expression, const GeneratedDomainRef &d ExpressionReferencesBinding(expression, domain.source_bindings); } +static bool DoesNotObserveKeys(const Expression &expression, const vector &keys) { + switch (expression.GetExpressionClass()) { + case ExpressionClass::BOUND_COLUMN_REF: { + auto &column = expression.Cast(); + return column.Depth() == 0 && !FindBindingIndex(keys, column.Binding()).IsValid(); + } + case ExpressionClass::BOUND_LAMBDA: + case ExpressionClass::BOUND_LAMBDA_REF: + case ExpressionClass::BOUND_SUBQUERY: + case ExpressionClass::BOUND_REF: + return false; + default: + break; + } + bool safe = true; + ExpressionIterator::EnumerateChildren(expression, + [&](const Expression &child) { safe &= DoesNotObserveKeys(child, keys); }); + return safe; +} + +//! A floating-point key may change representation only while used as a plain equality/group key. +static bool CanSubstituteFloatingKeys(const GeneratedDomainRef &domain, const vector &conditions, + LogicalOperator &target, + const vector, idx_t>> &path) { + if (!domain.filters.empty()) { + return false; + } + for (auto &condition : conditions) { + if (!IsEqualityJoinCondition(condition)) { + return false; + } + } + vector keys; + for (idx_t index = 0; index < domain.output_expressions.size(); index++) { + auto &expression = *domain.output_expressions[index]; + if (expression.GetReturnType().IsFloating()) { + keys.push_back(domain.output_bindings[index]); + } + } + if (keys.empty()) { + return false; + } + for (auto &expression : domain.output_expressions) { + ColumnBinding binding; + if (!GetBoundColumnRefBinding(*expression, binding)) { + return false; + } + } + auto published = target.GetColumnBindings(); + keys.erase(std::remove_if(keys.begin(), keys.end(), + [&](const ColumnBinding &key) { return !FindBindingIndex(published, key).IsValid(); }), + keys.end()); + // Only the candidate's layout is final; ancestor projection maps can still await binding repair. + for (auto entry = path.rbegin(); entry != path.rend(); ++entry) { + if (keys.empty()) { + return true; + } + auto &op = entry->first.get(); + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &expressions = op.type == LogicalOperatorType::LOGICAL_PROJECTION ? op.expressions + : op.Cast().groups; + auto outputs = op.GetColumnBindings(); + vector aliases; + for (idx_t index = 0; index < expressions.size(); index++) { + ColumnBinding binding; + if (GetBoundColumnRefBinding(*expressions[index], binding) && + FindBindingIndex(keys, binding).IsValid()) { + aliases.push_back(outputs[index]); + } else if (!DoesNotObserveKeys(*expressions[index], keys)) { + return false; + } + } + if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + auto &aggregate = op.Cast(); + if (!aggregate.grouping_functions.empty() || aggregate.grouping_sets.size() > 1 || + (aggregate.grouping_sets.size() == 1 && + aggregate.grouping_sets[0].size() != aggregate.groups.size())) { + return false; + } + for (auto &expression : aggregate.expressions) { + if (!DoesNotObserveKeys(*expression, keys)) { + return false; + } + } + } + keys = std::move(aliases); + break; + } + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { + auto &join = op.Cast(); + for (auto &condition : join.conditions) { + ColumnBinding left, right; + if (IsEqualityJoinCondition(condition) && GetBoundColumnRefBinding(condition.GetLHS(), left) && + GetBoundColumnRefBinding(condition.GetRHS(), right)) { + continue; + } + if (!condition.IsComparison() || !DoesNotObserveKeys(condition.GetLHS(), keys) || + !DoesNotObserveKeys(condition.GetRHS(), keys)) { + return false; + } + } + for (auto &expression : join.duplicate_eliminated_columns) { + if (!DoesNotObserveKeys(*expression, keys)) { + return false; + } + } + for (auto &expression : join.expressions) { + if (!DoesNotObserveKeys(*expression, keys)) { + return false; + } + } + if (IsSubqueryEvidenceSide(join, entry->second)) { + keys.clear(); + } + break; + } + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + for (auto &expression : op.expressions) { + if (!DoesNotObserveKeys(*expression, keys)) { + return false; + } + } + break; + default: + return false; + } + } + return keys.empty(); +} + +static bool CanEvaluateUnmatchedRows(const LogicalOperator &op, bool allow_aggregate = false) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + case LogicalOperatorType::LOGICAL_CTE_REF: + case LogicalOperatorType::LOGICAL_DUMMY_SCAN: + case LogicalOperatorType::LOGICAL_EMPTY_RESULT: + break; + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + if (!allow_aggregate) { + return false; + } + break; + case LogicalOperatorType::LOGICAL_GET: + if (!op.Cast().GetTable()) { + return false; + } + break; + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + if (op.Cast().join_type == JoinType::SINGLE) { + return false; + } + break; + default: + return false; + } + bool safe = true; + LogicalOperatorVisitor::EnumerateExpressions(op, [&](optional_ptr> expression) { + safe &= !ExpressionBarrier::Required(**expression) && !ExpressionBarrier::Contains(**expression); + ExpressionIterator::VisitExpression( + **expression, + [&](const BoundFunctionExpression &function) { safe &= !function.Function().RequiresOrderedExecution(); }); + }); + if (!safe) { + return false; + } + for (auto &child : op.children) { + if (!CanEvaluateUnmatchedRows(*child, allow_aggregate)) { + return false; + } + } + return true; +} + struct GeneratedDomainReplacement { BindingReplacementGraph bindings; vector> outputs; @@ -965,7 +1134,8 @@ struct GeneratedDomainReplacement { bool all_equality = true; // Each candidate is analyzed once; successful analysis consumes its copied filters. - bool Analyze(const vector &conditions, GeneratedDomainRef &domain, GeneratedDomainAction action) { + bool Analyze(const vector &conditions, GeneratedDomainRef &domain, GeneratedDomainAction action, + bool floating_keys_unobserved = false) { vector source_bindings; vector> source_expressions; vector covered_bindings; @@ -984,7 +1154,9 @@ struct GeneratedDomainReplacement { auto &domain_expression = *domain.output_expressions[domain_index]; auto &base_expression = left_index.IsValid() ? condition.GetRHS() : condition.GetLHS(); ColumnBinding base_binding; - if (!GetBoundColumnRefBinding(base_expression, base_binding) || + if ((!BoundComparisonExpression::EqualityPreservesValueRepresentation(domain_expression.GetReturnType()) && + !(floating_keys_unobserved && domain_expression.GetReturnType().IsFloating())) || + !GetBoundColumnRefBinding(base_expression, base_binding) || !bindings.TryAdd(ReplacementBinding(domain.output_bindings[domain_index], base_binding, domain_expression.GetReturnType()))) { return false; @@ -1147,6 +1319,7 @@ class GeneratedDedupRefEliminator { LogicalOperator &rewrite_root; bool preserve_evidence_side; bool preserve_nested_evidence_side; + vector, idx_t>> consumer_path; }; GeneratedDedupRefEliminator::GeneratedDedupRefEliminator(Binder &binder, unique_ptr &delim_join_op, @@ -1156,6 +1329,7 @@ GeneratedDedupRefEliminator::GeneratedDedupRefEliminator(Binder &binder, unique_ : binder(binder), delim_join_op(delim_join_op), delim_join(delim_join_op->Cast()), dedup_cte_index(dedup_cte_index), dedup_ref_count(dedup_ref_count), rewrite_root(rewrite_root), preserve_evidence_side(preserve_evidence_side), preserve_nested_evidence_side(preserve_nested_evidence_side) { + consumer_path.emplace_back(delim_join, 1); } static unique_ptr @@ -1241,8 +1415,11 @@ bool GeneratedDedupRefEliminator::RewriteSubtree(unique_ptr &op bool under_evidence_side) { if (op->type == LogicalOperatorType::LOGICAL_DELIM_JOIN) { if (!op->children.empty()) { - return RewriteSubtree(op->children[0], preserve_selected_domain, replacements, under_aggregate, - under_evidence_side); + consumer_path.emplace_back(*op, 0); + auto rewritten = RewriteSubtree(op->children[0], preserve_selected_domain, replacements, under_aggregate, + under_evidence_side); + consumer_path.pop_back(); + return rewritten; } return false; } @@ -1252,8 +1429,11 @@ bool GeneratedDedupRefEliminator::RewriteSubtree(unique_ptr &op for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { auto old_child_bindings = op->children[child_idx]->GetColumnBindings(); BindingReplacementGraph child_replacements; - if (RewriteSubtree(op->children[child_idx], preserve_selected_domain, child_replacements, child_under_aggregate, - under_evidence_side)) { + consumer_path.emplace_back(*op, child_idx); + auto child_rewritten = RewriteSubtree(op->children[child_idx], preserve_selected_domain, child_replacements, + child_under_aggregate, under_evidence_side); + consumer_path.pop_back(); + if (child_rewritten) { ColumnBindingRewrite::ApplyToChild(op, child_idx, std::move(old_child_bindings), child_replacements); replacements.Merge(child_replacements.ScopedToBoundary(op->children[child_idx]->GetColumnBindings())); rewritten = true; @@ -1444,11 +1624,24 @@ bool GeneratedDedupRefEliminator::RewriteJoin(unique_ptr &op, B auto domain = left_domain ? std::move(left_domain) : std::move(right_domain); vector conditions; vector consumed; + vector domain_filter_indices; if (filter) { filter->SplitPredicates(); consumed.resize(filter->expressions.size(), false); for (idx_t index = 0; index < filter->expressions.size(); index++) { auto &expression = *filter->expressions[index]; + column_binding_set_t bindings; + if (GetExpressionColumnBindings(expression, bindings) && !bindings.empty() && + ChildContainsBindings(*join_op->children[domain_side], bindings)) { + // Predicate motion and domain removal can expose expressions to additional rows. + if (domain_filter_indices.empty() && !CanEvaluateUnmatchedRows(*delim_join.children[1])) { + return false; + } + domain->filters.push_back(expression.Copy()); + domain_filter_indices.push_back(index); + consumed[index] = true; + continue; + } if (!BoundComparisonExpression::IsComparison(expression)) { continue; } @@ -1479,7 +1672,13 @@ bool GeneratedDedupRefEliminator::RewriteJoin(unique_ptr &op, B } } GeneratedDomainReplacement replacement; - if (!replacement.Analyze(conditions, *domain, action)) { + const auto floating_keys_unobserved = + CanSubstituteFloatingKeys(*domain, conditions, *op, consumer_path) && + (action == GeneratedDomainAction::PRESERVE || CanEvaluateUnmatchedRows(*delim_join.children[1], true)); + if (!replacement.Analyze(conditions, *domain, action, floating_keys_unobserved)) { + return false; + } + if (!domain_filter_indices.empty() && !replacement.all_equality) { return false; } if (!replacement.all_equality && @@ -1490,6 +1689,11 @@ bool GeneratedDedupRefEliminator::RewriteJoin(unique_ptr &op, B auto join = make_uniq(JoinType::INNER); join->conditions = std::move(conditions); join->children = std::move(join_op->children); + if (action == GeneratedDomainAction::PRESERVE) { + for (auto index : domain_filter_indices) { + AddFilterToOperator(join->children[domain_side], std::move(filter->expressions[index])); + } + } vector> remaining; for (idx_t index = 0; index < consumed.size(); index++) { if (!consumed[index]) { @@ -1835,44 +2039,7 @@ static bool SingleJoinRHSIsDeduplicated(LogicalComparisonJoin &join) { join_bindings.emplace_back(colref.Binding()); } - reference current_op = *join.children[1]; - while (current_op.get().type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { - if (current_op.get().children.size() != 1) { - return false; - } - - switch (current_op.get().type) { - case LogicalOperatorType::LOGICAL_PROJECTION: - if (!FindAndReplaceBindings(join_bindings, current_op.get().expressions, - current_op.get().GetColumnBindings())) { - return false; - } - break; - case LogicalOperatorType::LOGICAL_FILTER: - break; - default: - return false; - } - current_op = *current_op.get().children[0]; - } - - auto &aggr = current_op.get().Cast(); - if (!aggr.grouping_functions.empty()) { - return false; - } - if (aggr.grouping_sets.size() > 1) { - // multiple grouping sets emit one row per set, so the groups do not determine a unique row - return false; - } - - for (idx_t group_idx = 0; group_idx < aggr.groups.size(); group_idx++) { - if (std::find(join_bindings.begin(), join_bindings.end(), - ColumnBinding(aggr.group_index, ProjectionIndex(group_idx))) == join_bindings.end()) { - return false; - } - } - - return true; + return LogicalAggregate::KeysAreUnique(*join.children[1], std::move(join_bindings)); } static bool HasPartitionedRecursiveReferences(LogicalOperator &op, const LogicalRecursiveCTE &cte) { @@ -1918,11 +2085,17 @@ static bool HasPartitionedRecursiveKeys(LogicalRecursiveCTE &cte) { // Decorrelation partitions the RHS by its domain. Only retain this fact for repeatable, locally owned inputs. static bool CanRestrictCorrelationDomain(LogicalOperator &op, unordered_set &local_ctes) { switch (op.type) { - case LogicalOperatorType::LOGICAL_GET: - if (!op.Cast().GetTable()) { + case LogicalOperatorType::LOGICAL_GET: { + // a table in-out function without a final step turns each input row into rows of its own + auto &get = op.Cast(); + auto &function = get.function; + const bool row_by_row = function.in_out_function && !function.in_out_function_final && + function.stability != FunctionStability::VOLATILE; + if (!get.GetTable() && !row_by_row) { return false; } break; + } case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: { auto &cte = op.Cast(); if (!HasPartitionedRecursiveKeys(cte)) { @@ -1951,6 +2124,7 @@ static bool CanRestrictCorrelationDomain(LogicalOperator &op, unordered_setchildren.push_back(std::move(dedup_child)); auto dedup_cte_name = Identifier("__duckdb_delim_dedup_" + to_string(dedup_cte_index.index)); - BindingReplacementGraph dedup_output_replacements; - auto dedup_cte_child = CreateIdentityProjection(binder, std::move(plan), dedup_output_replacements); - output_replacements.Merge(dedup_output_replacements); + auto dedup_cte_child = std::move(plan); auto dedup_cte = make_uniq(dedup_cte_name, dedup_cte_index, dedup_types.size(), std::move(dedup), std::move(dedup_cte_child), CTEMaterialize::CTE_MATERIALIZE_DEFAULT); - BindingReplacementGraph cte_output_replacements; - auto cte_child = CreateIdentityProjection(binder, std::move(dedup_cte), cte_output_replacements); - output_replacements.Merge(cte_output_replacements); + auto cte_child = std::move(dedup_cte); auto cte = make_uniq(cte_name, cte_index, left_column_count, std::move(cte_source), std::move(cte_child), CTEMaterialize::CTE_MATERIALIZE_DEFAULT); if (can_restrict_input) { diff --git a/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp b/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp index 1b60f2b9e..2562e269a 100644 --- a/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp +++ b/src/duckdb/src/planner/subquery/flatten_dependent_join.cpp @@ -437,7 +437,7 @@ static unique_ptr CreateRowNumberWindow(Binder &binder, unique_pt TableIndex table_index, vector> partitions = {}, vector orders = {}) { - auto window = make_uniq(table_index); + auto window = make_uniq(table_index, optional_idx()); auto row_number = GetBuiltinWindowFunction(binder.context, RowNumberFun::Name, {})->Bind(binder.context); row_number->PartitionsMutable() = std::move(partitions); @@ -1479,7 +1479,16 @@ FlattenDependentJoins::UnnestingState FlattenDependentJoins::PushDownSetOperatio } #endif result.bindings = CreateContiguousState(ColumnBinding(setop.table_index, ProjectionIndex(setop.column_count))); + if (setop.comparison_types.size() == setop.column_count) { + for (auto &correlated_column : correlated_columns) { + setop.comparison_types.push_back(correlated_column.type); + } + } setop.column_count += correlated_columns.size(); + if (setop.type != LogicalOperatorType::LOGICAL_UNION) { + // EXCEPT / INTERSECT now run per value of the correlated columns, which they compare as they are + setop.correlated_column_count += correlated_columns.size(); + } return result; } diff --git a/src/duckdb/src/planner/subquery/has_volatile_expressions.cpp b/src/duckdb/src/planner/subquery/has_volatile_expressions.cpp new file mode 100644 index 000000000..a2b515871 --- /dev/null +++ b/src/duckdb/src/planner/subquery/has_volatile_expressions.cpp @@ -0,0 +1,52 @@ +#include "duckdb/planner/subquery/has_volatile_expressions.hpp" + +#include "duckdb/function/scalar/generic_functions.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/logical_operator.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" + +namespace duckdb { + +static bool IsVolatileIgnoringError(const Expression &expr) { + switch (expr.GetExpressionClass()) { + case ExpressionClass::BOUND_FUNCTION: { + auto &function = expr.Cast().Function(); + if (function.HasBindLambdaCallback() || + (function.GetStability() == FunctionStability::VOLATILE && !ErrorFun::IsError(function))) { + return expr.IsVolatile(); + } + break; + } + case ExpressionClass::BOUND_CASE: + case ExpressionClass::BOUND_CONJUNCTION: + case ExpressionClass::BOUND_OPERATOR: + break; + default: + return expr.IsVolatile(); + } + bool is_volatile = false; + ExpressionIterator::EnumerateChildren( + expr, [&](const Expression &child) { is_volatile = is_volatile || IsVolatileIgnoringError(child); }); + return is_volatile; +} + +bool HasVolatileExpressionsIgnoringError(const LogicalOperator &op) { + bool is_volatile = false; + LogicalOperatorVisitor::EnumerateExpressions(op, [&](const unique_ptr *expression) { + if (IsVolatileIgnoringError(**expression)) { + is_volatile = true; + } + }); + if (is_volatile) { + return true; + } + for (auto &child : op.children) { + if (child && HasVolatileExpressionsIgnoringError(*child)) { + return true; + } + } + return false; +} + +} // namespace duckdb diff --git a/src/duckdb/src/planner/subquery/pair_dependent_full_outer_join.cpp b/src/duckdb/src/planner/subquery/pair_dependent_full_outer_join.cpp index 0d6415473..2ef9a2113 100644 --- a/src/duckdb/src/planner/subquery/pair_dependent_full_outer_join.cpp +++ b/src/duckdb/src/planner/subquery/pair_dependent_full_outer_join.cpp @@ -92,7 +92,7 @@ static void CollectPairDependentBindings(Expression &expression, const unordered } static unique_ptr AddRowIdentity(Binder &binder, unique_ptr source) { - auto window = make_uniq(binder.GenerateTableIndex()); + auto window = make_uniq(binder.GenerateTableIndex(), optional_idx()); auto row_number = GetBuiltinWindowFunction(binder.context, RowNumberFun::Name, {})->Bind(binder.context); row_number->WindowStartMutable() = WindowBoundary::UNBOUNDED_PRECEDING; row_number->WindowEndMutable() = WindowBoundary::CURRENT_ROW_ROWS; diff --git a/src/duckdb/src/planner/table_filter_state.cpp b/src/duckdb/src/planner/table_filter_state.cpp index 2b04ab4e5..849771b6b 100644 --- a/src/duckdb/src/planner/table_filter_state.cpp +++ b/src/duckdb/src/planner/table_filter_state.cpp @@ -1,6 +1,7 @@ #include "duckdb/main/client_context.hpp" #include "duckdb/main/context.hpp" #include "duckdb/planner/table_filter_state.hpp" +#include "duckdb/common/algorithm.hpp" #include "duckdb/common/operator/comparison_operators.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/common/vector_operations/selection_helpers.hpp" @@ -9,12 +10,210 @@ #include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/filter/table_filter_functions.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/storage/table/column_segment.hpp" +#include "duckdb/common/shared_ptr_ipp.hpp" +#include "duckdb/optimizer/expression_heuristics.hpp" namespace duckdb { +class BooleanFilterCache final : public TableFilterCache { +public: + BooleanFilterCache(const SelectionVector &selected, idx_t selected_count, idx_t count) + : matches(make_unsafe_uniq_array(count)), match_count(selected_count), value_count(count) { + memset(matches.get(), 0, count * sizeof(bool)); + for (idx_t i = 0; i < selected_count; i++) { + matches[selected.get_index(i)] = true; + } + } + + bool CanSkipAllInternal() const override { + return match_count == 0; + } + +protected: + optional> GetPureMaskInternal() const override { + return array_ptr(matches.get(), value_count); + } + + bool CanAcceptAllInternal() const override { + return match_count == value_count; + } + + void FilterConstantInternal(idx_t value_index, idx_t &count) override { + if (count != 0 && !matches[value_index]) { + count = 0; + } + } + + void FilterInternal(const SelectionVector &values, SelectionVector &sel, idx_t &count) override { + if (count == 0 || match_count == value_count) { + return; + } + if (result.Capacity() < count) { + result.Initialize(count); + } + idx_t accepted = 0; + if (!sel.IsSet()) { + accepted = SelectionVector::SelectFromBoolean(matches.get(), &values, count, + array_ptr(result.data(), result.Capacity())); + } else { + for (idx_t i = 0; i < count; i++) { + const auto row = sel.get_index(i); + result.set_index(accepted, row); + accepted += matches[values.get_index(row)]; + } + } + if (accepted != count) { + sel.Initialize(result); + } + count = accepted; + } + + void FilterRunsInternal(const SelectionVector &values, array_ptr, SelectionVector &sel, + idx_t &count) override { + FilterInternal(values, sel, count); + } + +private: + unsafe_unique_array matches; + idx_t match_count; + idx_t value_count; + SelectionVector result; +}; + +static unique_ptr CreateBooleanCache(ExpressionFilterExecutor &executor, Vector &values, + idx_t count) { + SelectionVector selected; + auto selected_count = count; + executor.FilterSelection(selected, values, count, selected_count); + return make_uniq(selected, selected_count, count); +} + +TableFilterState::~TableFilterState() { + if (cache_identity) { + cache_identity->valid = false; + } +} + +bool TableFilterCache::IsValidFor(const TableFilterState &state) const { + return identity && identity->valid && identity == state.cache_identity; +} + +bool TableFilterCache::CanSkipAll() const { + return (!identity || identity->valid) && CanSkipAllInternal(); +} + +bool TableFilterCache::CanAcceptAll() const { + return (!identity || identity->valid) && CanAcceptAllInternal(); +} + +optional> TableFilterCache::GetPureMask() const { + if (identity && !identity->valid) { + throw InternalException("Filter cache outlived its filter state"); + } + return GetPureMaskInternal(); +} + +void TableFilterCache::Filter(const SelectionVector &values, SelectionVector &sel, idx_t &count) { + if (identity && !identity->valid) { + throw InternalException("Filter cache outlived its filter state"); + } + FilterInternal(values, sel, count); +} + +void TableFilterCache::FilterConstant(idx_t value_index, idx_t &count) { + if (identity && !identity->valid) { + throw InternalException("Filter cache outlived its filter state"); + } + FilterConstantInternal(value_index, count); +} + +void TableFilterCache::FilterRuns(const SelectionVector &values, array_ptr row_counts, + SelectionVector &sel, idx_t &count) { + if (identity && !identity->valid) { + throw InternalException("Filter cache outlived its filter state"); + } + FilterRunsInternal(values, row_counts, sel, count); +} + +unique_ptr ExpressionFilterExecutor::CreateCache(Vector &values, idx_t count) { + throw InternalException("Filter executor does not support cached evaluation"); +} + +unique_ptr TableFilterState::CreateCache(Vector &values, idx_t count) { + D_ASSERT(can_cache); + auto &state = Cast(); + unique_ptr result; + if (state.can_cache_result) { + SelectionVector selected; + auto selected_count = count; + ColumnSegment::FilterSelection(selected, values, *this, count, selected_count); + result = make_uniq(selected, selected_count, count); + } else { + result = state.fast_executor->CreateCache(values, count); + } + if (!cache_identity) { + cache_identity = make_shared_ptr(); + } + result->identity = cache_identity; + return result; +} + +struct FilterCacheProperties { + bool safe = true; + bool adaptive = false; +}; + +static FilterCacheProperties GetCacheProperties(const Expression &expression) { + FilterCacheProperties result; + if (expression.CanThrow() || expression.IsVolatile()) { + result.safe = false; + return result; + } + if (expression.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { + auto &function = expression.Cast(); + const auto &name = function.Function().GetName(); + if (name == DynamicFilterScalarFun::NAME) { + result.safe = false; + return result; + } + if (name == SelectivityOptionalFilterScalarFun::NAME) { + result.adaptive = true; + auto child = ExpressionFilter::GetOptionalFilterChild(expression); + if (child) { + const auto properties = GetCacheProperties(*child); + result.safe = properties.safe; + } + } + if (name == BloomFilterScalarFun::NAME || name == PrefixRangeScalarFun::NAME) { + if (!function.BindInfo()) { + result.safe = false; + return result; + } + if (name == BloomFilterScalarFun::NAME) { + auto &data = function.BindInfo()->Cast(); + result.safe = data.filter && data.filter->IsSealed() && data.filter->IsPublished(); + result.adaptive = data.n_vectors_to_check != 0; + } else { + auto &data = function.BindInfo()->Cast(); + result.safe = data.filter && data.filter->IsInitialized() && data.filter->IsPublished(); + result.adaptive = data.n_vectors_to_check != 0; + } + } + } + ExpressionIterator::EnumerateChildren(expression, [&](const Expression &child) { + const auto properties = GetCacheProperties(child); + result.safe = result.safe && properties.safe; + result.adaptive = result.adaptive || properties.adaptive; + }); + return result; +} + static unique_ptr TryCreateFastExecutor(const Expression &expression, bool inside_selectivity_optional); @@ -24,9 +223,11 @@ static void InitializeExecutor(Context &context, const Expression &expression, E } ExpressionFilterState::ExpressionFilterState(Context &context, const Expression &expression) { - can_throw = expression.CanThrow(); - fast_executor = TryCreateFastExecutor(expression, false); + fast_executor = ExpressionFilterExecutor::TryCreate(expression); InitializeExecutor(context, expression, *this); + const auto properties = GetCacheProperties(expression); + can_cache_result = properties.safe && !properties.adaptive; + can_cache = properties.safe && (can_cache_result || (fast_executor && fast_executor->CanCache())); } ExpressionFilterState::~ExpressionFilterState() { @@ -38,6 +239,16 @@ class ConjunctionAndFilterExecutor final : public ExpressionFilterExecutor { : children(std::move(children_p)) { } + bool CanCache() const override { + for (const auto &child : children) { + if (!child->CanCache()) { + return false; + } + } + return true; + } + unique_ptr CreateCache(Vector &values, idx_t count) override; + idx_t FilterSelection(SelectionVector &sel, Vector &vector, idx_t scan_count, idx_t &approved_tuple_count) override { for (auto &child : children) { @@ -55,6 +266,12 @@ class ConjunctionAndFilterExecutor final : public ExpressionFilterExecutor { class OptionalFilterExecutor final : public ExpressionFilterExecutor { public: + bool CanCache() const override { + return true; + } + unique_ptr CreateCache(Vector &values, idx_t count) override { + return CreateBooleanCache(*this, values, count); + } idx_t FilterSelection(SelectionVector &sel, Vector &vector, idx_t scan_count, idx_t &approved_tuple_count) override { return approved_tuple_count; @@ -132,6 +349,12 @@ class ConjunctionOrFilterExecutor final : public ExpressionFilterExecutor { class ComparisonFilterExecutor final : public ExpressionFilterExecutor { public: + bool CanCache() const override { + return true; + } + unique_ptr CreateCache(Vector &values, idx_t count) override { + return CreateBooleanCache(*this, values, count); + } ComparisonFilterExecutor(ExpressionType comparison_type_p, Value constant_p) : comparison_type(comparison_type_p), constant(std::move(constant_p)) { } @@ -270,6 +493,39 @@ class ComparisonFilterExecutor final : public ExpressionFilterExecutor { idx_t current_capacity = 0; }; +class InFilterExecutor final : public ExpressionFilterExecutor { +public: + explicit InFilterExecutor(vector constants) : executor(CreateComparisons(std::move(constants))) { + } + + bool CanCache() const override { + return true; + } + unique_ptr CreateCache(Vector &values, idx_t count) override { + return CreateBooleanCache(*this, values, count); + } + idx_t FilterSelection(SelectionVector &sel, Vector &vector, idx_t scan_count, + idx_t &approved_tuple_count) override { + return executor.FilterSelection(sel, vector, scan_count, approved_tuple_count); + } + +private: + static vector> CreateComparisons(vector constants) { + vector> children; + for (auto &constant : constants) { + children.push_back(make_uniq(ExpressionType::COMPARE_EQUAL, std::move(constant))); + } + return children; + } + + ConjunctionOrFilterExecutor executor; +}; + +static bool KeepOptionalSelection(const SelectivityOptionalFilterState::SelectivityStats &stats, idx_t accepted, + idx_t processed) { + return static_cast(accepted) < static_cast(processed) * stats.selectivity_threshold; +} + class SelectivityOptionalFilterExecutor final : public ExpressionFilterExecutor { public: SelectivityOptionalFilterExecutor(unique_ptr child_p, idx_t n_vectors_to_check, @@ -277,6 +533,11 @@ class SelectivityOptionalFilterExecutor final : public ExpressionFilterExecutor : child(std::move(child_p)), stats(n_vectors_to_check, selectivity_threshold) { } + bool CanCache() const override { + return child && child->CanCache(); + } + unique_ptr CreateCache(Vector &values, idx_t count) override; + idx_t FilterSelection(SelectionVector &sel, Vector &vector, idx_t scan_count, idx_t &approved_tuple_count) override { if (approved_tuple_count == 0) { @@ -290,8 +551,13 @@ class SelectivityOptionalFilterExecutor final : public ExpressionFilterExecutor return approved_tuple_count; } const auto before_count = approved_tuple_count; + const auto had_selection = sel.IsSet(); child->FilterSelection(sel, vector, scan_count, approved_tuple_count); stats.Update(approved_tuple_count, before_count); + if (!had_selection && !KeepOptionalSelection(stats, approved_tuple_count, before_count)) { + sel = SelectionVector(); + approved_tuple_count = before_count; + } return approved_tuple_count; } @@ -300,16 +566,168 @@ class SelectivityOptionalFilterExecutor final : public ExpressionFilterExecutor SelectivityOptionalFilterState::SelectivityStats stats; }; +class ConjunctionFilterCache final : public TableFilterCache { +public: + explicit ConjunctionFilterCache(vector> children_p) : children(std::move(children_p)) { + } + +protected: + bool CanAcceptAllInternal() const override { + for (const auto &child : children) { + if (!child->CanAcceptAll()) { + return false; + } + } + return true; + } + + void FilterConstantInternal(idx_t value_index, idx_t &count) override { + for (auto &child : children) { + if (count == 0) { + break; + } + child->FilterConstant(value_index, count); + } + } + + void FilterInternal(const SelectionVector &values, SelectionVector &sel, idx_t &count) override { + for (auto &child : children) { + if (count == 0) { + break; + } + child->Filter(values, sel, count); + } + } + + void FilterRunsInternal(const SelectionVector &values, array_ptr row_counts, SelectionVector &sel, + idx_t &count) override { + for (auto &child : children) { + if (count == 0) { + break; + } + child->FilterRuns(values, row_counts, sel, count); + } + } + +private: + vector> children; +}; + +static idx_t CountRunRows(array_ptr row_counts, const SelectionVector &sel, idx_t count) { + idx_t rows = 0; + for (idx_t i = 0; i < count; i++) { + rows += row_counts[sel.get_index(i)]; + } + return rows; +} + +class OptionalFilterCache final : public TableFilterCache { +public: + OptionalFilterCache(unique_ptr child_p, SelectivityOptionalFilterState::SelectivityStats &stats_p) + : child(std::move(child_p)), stats(stats_p) { + } + +protected: + bool CanAcceptAllInternal() const override { + return !stats.get().IsActive() || child->CanAcceptAll(); + } + + void FilterConstantInternal(idx_t value_index, idx_t &count) override { + if (count == 0) { + return; + } + if (!stats.get().IsActive()) { + stats.get().Update(0, 0); + return; + } + const auto before_count = count; + child->FilterConstant(value_index, count); + stats.get().Update(count, before_count); + if (!KeepOptionalSelection(stats.get(), count, before_count)) { + count = before_count; + } + } + + void FilterInternal(const SelectionVector &values, SelectionVector &sel, idx_t &count) override { + if (count == 0) { + return; + } + if (!stats.get().IsActive()) { + stats.get().Update(0, 0); + return; + } + const auto before_count = count; + const auto had_selection = sel.IsSet(); + child->Filter(values, sel, count); + stats.get().Update(count, before_count); + if (!had_selection && !KeepOptionalSelection(stats.get(), count, before_count)) { + sel = SelectionVector(); + count = before_count; + } + } + + void FilterRunsInternal(const SelectionVector &values, array_ptr row_counts, SelectionVector &sel, + idx_t &count) override { + if (!stats.get().IsActive()) { + for (idx_t i = 0; i < count; i++) { + if (row_counts[sel.get_index(i)] != 0) { + stats.get().Update(0, 0); + break; + } + } + return; + } + const auto before_rows = CountRunRows(row_counts, sel, count); + if (before_rows == 0) { + return; + } + const auto before_count = count; + const auto had_selection = sel.IsSet(); + child->FilterRuns(values, row_counts, sel, count); + const auto accepted_rows = count == before_count ? before_rows : CountRunRows(row_counts, sel, count); + stats.get().Update(accepted_rows, before_rows); + if (!had_selection && !KeepOptionalSelection(stats.get(), accepted_rows, before_rows)) { + sel = SelectionVector(); + count = before_count; + } + } + +private: + unique_ptr child; + reference stats; +}; + +unique_ptr ConjunctionAndFilterExecutor::CreateCache(Vector &values, idx_t count) { + vector> caches; + for (auto &child : children) { + caches.push_back(child->CreateCache(values, count)); + } + return make_uniq(std::move(caches)); +} + +unique_ptr SelectivityOptionalFilterExecutor::CreateCache(Vector &values, idx_t count) { + return make_uniq(child->CreateCache(values, count), stats); +} + class BloomFilterExecutor final : public ExpressionFilterExecutor { public: BloomFilterExecutor(const BloomFilterFunctionData &data, bool inside_selectivity_optional) - : filter(data.filter), filters_null_values(data.filters_null_values), hashes(LogicalType::HASH) { + : filter(data.filter), locality(data.locality), filters_null_values(data.filters_null_values), + hashes(LogicalType::HASH) { if (!inside_selectivity_optional && data.n_vectors_to_check != 0) { stats = make_uniq(data.n_vectors_to_check, data.selectivity_threshold); } } + bool CanCache() const override { + return !stats && filter && filter->IsSealed() && filter->IsPublished(); + } + unique_ptr CreateCache(Vector &values, idx_t count) override { + D_ASSERT(CanCache()); + return CreateBooleanCache(*this, values, count); + } + idx_t FilterSelection(SelectionVector &sel, Vector &vector, idx_t scan_count, idx_t &approved_tuple_count) override { if (approved_tuple_count == 0) { @@ -358,18 +776,19 @@ class BloomFilterExecutor final : public ExpressionFilterExecutor { private: idx_t ProbeBloomFilter(optional_ptr sel, idx_t approved_tuple_count) { + const auto view = GetBloomFilterReadView(*filter, locality); if (hashes.GetVectorType() == VectorType::CONSTANT_VECTOR) { const auto hash = *ConstantVector::GetData(hashes); - return filter->LookupOne(hash) ? approved_tuple_count : 0; + return view.LookupOne(hash) ? approved_tuple_count : 0; } if (hashes.GetVectorType() != VectorType::FLAT_VECTOR) { hashes.Flatten(); } D_ASSERT(hashes.GetVectorType() == VectorType::FLAT_VECTOR); if (sel) { - return filter->LookupHashes(hashes, *sel, bloom_sel, approved_tuple_count); + return view.LookupHashes(hashes, *sel, bloom_sel, approved_tuple_count); } - return filter->LookupHashes(hashes, bloom_sel, approved_tuple_count); + return view.LookupHashes(hashes, bloom_sel, approved_tuple_count); } idx_t AddNullsToBloomSelection(SelectionVector &sel, Vector &vector, idx_t bloom_count, @@ -438,6 +857,7 @@ class BloomFilterExecutor final : public ExpressionFilterExecutor { } shared_ptr filter; + BloomFilterReadLocality locality; bool filters_null_values; Vector hashes; SelectionVector bloom_sel; @@ -457,6 +877,14 @@ class PrefixRangeFilterExecutor final : public ExpressionFilterExecutor { } } + bool CanCache() const override { + return !stats && filter && filter->IsInitialized() && filter->IsPublished(); + } + unique_ptr CreateCache(Vector &values, idx_t count) override { + D_ASSERT(CanCache()); + return CreateBooleanCache(*this, values, count); + } + idx_t FilterSelection(SelectionVector &sel, Vector &vector, idx_t scan_count, idx_t &approved_tuple_count) override { if (approved_tuple_count == 0) { @@ -624,10 +1052,33 @@ static unique_ptr TryCreateComparisonExecutor(const Bo return make_uniq(comparison_type, constant->GetValue()); } +static unique_ptr TryCreateInExecutor(const BoundOperatorExpression &expr) { + auto &expressions = expr.GetChildren(); + if (expr.GetExpressionType() != ExpressionType::COMPARE_IN || expressions.size() < 2 || + !IsColumnReferenceExpression(*expressions[0])) { + return nullptr; + } + const auto type = expressions[0]->GetReturnType().InternalType(); + if (!IsSupportedComparisonType(type)) { + return nullptr; + } + vector constants; + for (idx_t i = 1; i < expressions.size(); i++) { + if (expressions[i]->GetExpressionClass() != ExpressionClass::BOUND_CONSTANT) { + return nullptr; + } + const auto &constant = expressions[i]->Cast().GetValue(); + if (constant.type().InternalType() != type) { + return nullptr; + } + constants.push_back(constant); + } + return make_uniq(std::move(constants)); +} + static unique_ptr TryCreateFunctionExecutor(const BoundFunctionExpression &func, bool inside_selectivity_optional) { - if (!inside_selectivity_optional && func.GetChildren().size() == 2 && - BoundComparisonExpression::IsComparison(func.GetExpressionType())) { + if (func.GetChildren().size() == 2 && BoundComparisonExpression::IsComparison(func.GetExpressionType())) { return TryCreateComparisonExecutor(func); } if (!IsColumnReferenceFunction(func)) { @@ -673,21 +1124,36 @@ static unique_ptr TryCreateFastExecutor(const Expressi switch (expression.GetExpressionClass()) { case ExpressionClass::BOUND_FUNCTION: return TryCreateFunctionExecutor(expression.Cast(), inside_selectivity_optional); + case ExpressionClass::BOUND_OPERATOR: + return TryCreateInExecutor(expression.Cast()); case ExpressionClass::BOUND_CONJUNCTION: { if (expression.GetExpressionType() != ExpressionType::CONJUNCTION_AND && expression.GetExpressionType() != ExpressionType::CONJUNCTION_OR) { return nullptr; } auto &conjunction = expression.Cast(); - vector> children; + struct FilterCost { + unique_ptr executor; + idx_t cost; + }; + vector filters; + const auto is_and = expression.GetExpressionType() == ExpressionType::CONJUNCTION_AND; for (auto &child_expr : conjunction.GetChildren()) { auto child_executor = TryCreateFastExecutor(*child_expr, inside_selectivity_optional); if (!child_executor) { return nullptr; } - children.push_back(std::move(child_executor)); + filters.push_back({std::move(child_executor), is_and ? ExpressionHeuristics::Cost(*child_expr) : 0}); + } + if (is_and) { + std::stable_sort(filters.begin(), filters.end(), + [](const FilterCost &left, const FilterCost &right) { return left.cost < right.cost; }); + } + vector> children; + for (auto &filter : filters) { + children.push_back(std::move(filter.executor)); } - if (expression.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + if (is_and) { return make_uniq(std::move(children)); } return make_uniq(std::move(children)); @@ -697,6 +1163,10 @@ static unique_ptr TryCreateFastExecutor(const Expressi } } +unique_ptr ExpressionFilterExecutor::TryCreate(const Expression &expression) { + return TryCreateFastExecutor(expression, false); +} + unique_ptr TableFilterState::Initialize(ClientContext &context, const TableFilter &filter) { auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter, "TableFilterState::Initialize"); return make_uniq(context.GetContext(), *expr_filter.expr); diff --git a/src/duckdb/src/storage/arena_allocator.cpp b/src/duckdb/src/storage/arena_allocator.cpp index f8aedc163..14ce09178 100644 --- a/src/duckdb/src/storage/arena_allocator.cpp +++ b/src/duckdb/src/storage/arena_allocator.cpp @@ -121,33 +121,12 @@ data_ptr_t ArenaAllocator::Reallocate(data_ptr_t pointer, idx_t old_size, idx_t return result; } -void ArenaAllocator::AlignNext() { - if (head && !ValueIsAligned(head->current_position)) { - // move the current position forward so that the next allocation is aligned - head->current_position = AlignValue(head->current_position); - } -} - -data_ptr_t ArenaAllocator::AllocateAligned(idx_t size) { - AlignNext(); - return Allocate(AlignValue(size)); -} - data_ptr_t ArenaAllocator::ReallocateAligned(data_ptr_t pointer, idx_t old_size, idx_t size) { AlignNext(); return Reallocate(pointer, old_size, AlignValue(size)); } -ArenaAllocator::Position ArenaAllocator::GetPosition() const { - Position result; - if (head) { - result.chunk = head.get(); - result.current_position = head->current_position; - } - return result; -} - -void ArenaAllocator::Rewind(const Position &position) { +void ArenaAllocator::RewindSlow(const Position &position) { if (!position.chunk) { // nothing was allocated when the position was taken FreeAll(); diff --git a/src/duckdb/src/storage/block_allocator.cpp b/src/duckdb/src/storage/block_allocator.cpp index 33feceee4..e2a79ab99 100644 --- a/src/duckdb/src/storage/block_allocator.cpp +++ b/src/duckdb/src/storage/block_allocator.cpp @@ -229,10 +229,6 @@ static idx_t AllocatorShardCount() { #endif } -static idx_t AllocatorLocalShard(const idx_t count) { - return count == 1 ? 0 : (TaskScheduler::GetEstimatedCPUId() / 4) % count; -} - struct BlockQueue { BlockQueue(idx_t blocks, idx_t shards) : blocks_per_shard(MaxValue(1, blocks / shards + (blocks % shards != 0))), @@ -350,8 +346,7 @@ class BlockAllocatorThreadLocalState { } // We have also run out of global blocks, use fallback allocator - return RetryAfterReclaiming( - *block_allocator, [&] { return block_allocator->allocator.AllocateData(block_allocator->block_size); }); + return block_allocator->AllocateFallbackData(block_allocator->block_size); } void Free(const data_ptr_t pointer) { @@ -373,9 +368,15 @@ class BlockAllocatorThreadLocalState { private: bool TryClear() DUCKDB_EXCLUDES(lifetime_state->lock) { + if (touched.empty() && untouched.empty()) { + // nothing to return, and the queues may not exist: a worker creates its state before the pool is ready + return true; + } if (lifetime_state) { annotated_lock_guard guard(lifetime_state->lock); if (lifetime_state->alive) { + // local blocks only come out of a ready pool, whose queues stay published until the allocator dies + D_ASSERT(block_allocator->IsInitialized()); TryReturnTouched(touched.size()); TryReturnBlocks(untouched, *block_allocator->untouched, untouched.size()); return touched.empty() && untouched.empty(); @@ -514,7 +515,32 @@ class BlockAllocatorThreadLocalState { #ifndef __MVS__ //! Whether this thread created its state. A bool needs no thread_local destructor, so reading it allocates nothing static thread_local bool thread_local_state_created = false; // NOLINT +//! The state of the worker thread running on this thread, if any. A pointer needs no thread_local destructor either +static thread_local BlockAllocatorThreadLocalState *worker_local_state = nullptr; // NOLINT +#endif + +BlockAllocatorWorkerState::BlockAllocatorWorkerState() { +} + +BlockAllocatorWorkerState::~BlockAllocatorWorkerState() { +#ifndef __MVS__ + if (state) { + worker_local_state = previous.get(); + } +#endif +} + +bool BlockAllocatorWorkerState::IsInitialized() const { + return state != nullptr; +} + +void BlockAllocatorWorkerState::Initialize(const BlockAllocator &block_allocator) { + state = make_uniq(block_allocator); +#ifndef __MVS__ + previous = worker_local_state; + worker_local_state = state.get(); #endif +} BlockAllocatorThreadLocalState &GetBlockAllocatorThreadLocalState(const BlockAllocator &block_allocator) { #ifdef __MVS__ @@ -524,6 +550,10 @@ BlockAllocatorThreadLocalState &GetBlockAllocatorThreadLocalState(const BlockAll (*local_state).TryInitialize(block_allocator); return *local_state; #else + if (worker_local_state) { + worker_local_state->TryInitialize(block_allocator); + return *worker_local_state; + } thread_local BlockAllocatorThreadLocalState local_state(block_allocator); thread_local_state_created = true; local_state.TryInitialize(block_allocator); @@ -537,7 +567,7 @@ static bool ThreadHasLocalState() { #ifdef __MVS__ return true; #else - return thread_local_state_created; + return worker_local_state || thread_local_state_created; #endif } @@ -551,11 +581,16 @@ class AllocationCache { // Retain at most 1 GiB per size class, or one larger allocation. static constexpr idx_t MAX_CACHED_BYTES_PER_BUCKET = 1024ULL * 1024 * 1024; + struct CachedAllocation { + data_ptr_t pointer = nullptr; + optional_idx home; + }; + struct alignas(64) Bucket { explicit Bucket(idx_t shard_count) : queues(shard_count) { } - ShardedAllocatorQueue queues; + ShardedAllocatorQueue queues; atomic last_return_ms {0}; // Keep queue metadata and the infrequently updated timestamp off the admission counter's cache line. alignas(64) atomic count {0}; @@ -575,33 +610,56 @@ class AllocationCache { return size >= (static_cast(1) << MIN_SHIFT) && size <= (static_cast(1) << MAX_SHIFT) && IsPowerOfTwo(size); } - data_ptr_t TryAllocate(idx_t size) { + idx_t GetShardCount() const { + return shard_count; + } + data_ptr_t Allocate(idx_t size, optional_idx &home) { + if (SupportsSize(size)) { + if (auto pointer = TryAllocate(size, home)) { + return pointer; + } + } + auto pointer = allocator.AllocateData(size); + home = LocalShard(); + return pointer; + } + data_ptr_t TryAllocate(idx_t size, optional_idx &home) { D_ASSERT(SupportsSize(size)); const auto shard = LocalShard(); auto &bucket = *buckets[CountZeros::Trailing(size) - MIN_SHIFT]; - data_ptr_t pointer; - if (bucket.queues.Get(shard).TryDequeue(pointer)) { + CachedAllocation allocation; + if (bucket.queues.Get(shard).TryDequeue(allocation)) { bucket.count.fetch_sub(1, std::memory_order_relaxed); - return pointer; + home = allocation.home; + return allocation.pointer; } // Share surplus buffers, leaving a few local spares without reserving the entire budget. const auto reserve = MinValue(MAX_LOCAL_SPARES, MAX_CACHED_BYTES_PER_BUCKET / size / (2 * shard_count)); - for (idx_t offset = 1; offset < shard_count; offset++) { - const auto peer = (shard + offset) % shard_count; - auto &queue = bucket.queues.Get(peer); - if ((reserve == 0 || queue.SizeApprox() > reserve) && queue.TryDequeue(pointer)) { - bucket.count.fetch_sub(1, std::memory_order_relaxed); - return pointer; + // Prefer neighbours in the same coarse half before borrowing from the other half. + const auto group = BlockAllocator::GetShardGroup(shard, shard_count); + for (idx_t pass = 0; pass < 2; pass++) { + for (idx_t offset = 1; offset < shard_count; offset++) { + const auto peer = (shard + offset) % shard_count; + if ((BlockAllocator::GetShardGroup(peer, shard_count) == group) != (pass == 0)) { + continue; + } + auto &queue = bucket.queues.Get(peer); + if ((reserve == 0 || queue.SizeApprox() > reserve) && queue.TryDequeue(allocation)) { + bucket.count.fetch_sub(1, std::memory_order_relaxed); + home = allocation.home; + return allocation.pointer; + } } } return nullptr; } - bool TryFree(data_ptr_t pointer, idx_t size) { + bool TryFree(data_ptr_t pointer, idx_t size, optional_idx home) { D_ASSERT(SupportsSize(size)); if (!pointer) { return false; } - const auto shard = LocalShard(); + // Raw-pointer callers cannot retain ownership across reuse; leave their home unknown. + const auto shard = home.IsValid() ? home.GetIndex() : LocalShard(); auto &bucket = *buckets[CountZeros::Trailing(size) - MIN_SHIFT]; const auto capacity = MaxValue(MAX_CACHED_BYTES_PER_BUCKET / size, 1); if (bucket.count.fetch_add(1, std::memory_order_relaxed) < capacity) { @@ -611,7 +669,7 @@ class AllocationCache { while (last_return < now && !bucket.last_return_ms.compare_exchange_weak(last_return, now, std::memory_order_relaxed)) { } - if (bucket.queues.Get(shard).Enqueue(pointer)) { + if (bucket.queues.Get(shard).Enqueue(CachedAllocation {pointer, home})) { return true; } } catch (...) { @@ -635,17 +693,17 @@ class AllocationCache { idx_t freed = 0; for (idx_t i = buckets.size(); i > 0 && freed < byte_limit; i--) { auto &bucket = *buckets[i - 1]; - const idx_t size = static_cast(1) << (MIN_SHIFT + i - 1); + const auto size = (static_cast(1) << (MIN_SHIFT + i - 1)); // A snapshot bounds the work even if producers continue returning buffers. auto remaining = Reclaimable(bucket, idle_before); for (idx_t shard = 0; shard < bucket.queues.Count(); shard++) { auto &queue = bucket.queues.Get(shard); - data_ptr_t pointer; + CachedAllocation allocation; while (remaining > 0 && freed < byte_limit && Reclaimable(bucket, idle_before) > 0) { - if (!queue.TryDequeue(pointer)) { + if (!queue.TryDequeue(allocation)) { break; } - allocator.FreeData(pointer, size); + allocator.FreeData(allocation.pointer, size); bucket.count.fetch_sub(1, std::memory_order_relaxed); freed += size; remaining--; @@ -665,7 +723,7 @@ class AllocationCache { private: idx_t LocalShard() const { - return AllocatorLocalShard(buckets[0]->queues.Count()); + return BlockAllocator::GetLocalShard(shard_count); } Allocator &allocator; @@ -841,8 +899,47 @@ idx_t BlockAllocator::DivBlockSize(const idx_t n) const { return n >> block_size_div_shift; } +idx_t BlockAllocator::GetLocalShard(idx_t shard_count) { + D_ASSERT(shard_count > 0); + return shard_count == 1 ? 0 : (TaskScheduler::GetEstimatedCPUId() / 4) % shard_count; +} + +idx_t BlockAllocator::GetShardGroup(idx_t shard, idx_t shard_count) { + D_ASSERT(shard < shard_count); + // Coarse halves share the allocator's CPU-order heuristic, not discovered NUMA nodes. + return shard * 2 / shard_count; +} + +idx_t BlockAllocator::GetLocalShardGroup(idx_t shard_count) { + return GetShardGroup(GetLocalShard(shard_count), shard_count); +} + idx_t BlockAllocator::GetLocalPoolShard() const { - return AllocatorLocalShard(touched->queues.Count()); + return GetLocalShard(GetPoolShardCount()); +} + +idx_t BlockAllocator::GetPoolShardCount() const { + return touched->queues.Count(); +} + +idx_t BlockAllocator::GetFallbackShardCount() const { + return allocation_cache->GetShardCount(); +} + +optional_idx BlockAllocator::GetAllocationShard(const_data_ptr_t pointer) const { + if (!IsInitialized()) { + return optional_idx(); + } + const auto address = reinterpret_cast(pointer); + const auto base = reinterpret_cast(pool_base); + if (address < base || address - base >= pool_size) { + return optional_idx(); + } + const auto block_id = NumericCast(DivBlockSize(address - base)); + if (IsGuardBlock(block_id)) { + return optional_idx(); + } + return touched->Home(block_id); } uint32_t BlockAllocator::GetBlockID(const data_ptr_t pointer) const { @@ -871,17 +968,16 @@ data_ptr_t BlockAllocator::GetPointer(const uint32_t block_id) const { data_ptr_t BlockAllocator::AllocateData(const idx_t size) const { if (size != block_size || !TryUsePool()) { - if (allocation_cache->SupportsSize(size)) { - auto pointer = allocation_cache->TryAllocate(size); - if (pointer) { - return pointer; - } - } - return RetryAfterReclaiming(*this, [&] { return allocator.AllocateData(size); }); + return AllocateFallbackData(size); } return GetBlockAllocatorThreadLocalState(*this).Allocate(); } +data_ptr_t BlockAllocator::AllocateFallbackData(const idx_t size) const { + optional_idx home; + return RetryAfterReclaiming(*this, [&] { return allocation_cache->Allocate(size, home); }); +} + idx_t BlockAllocator::GetCachedMemory() const { return GetCachedPoolMemory() + allocation_cache->GetCachedMemory(); } @@ -905,11 +1001,7 @@ void BlockAllocator::FreeData(const data_ptr_t pointer, const idx_t size) const return; } if (!IsInPool(pointer)) { - if (allocation_cache->SupportsSize(size) && allocation_cache->TryFree(pointer, size)) { - return; - } - allocator.FreeData(pointer, size); - estimated_unflushed_memory.fetch_add(size, std::memory_order_relaxed); + FreeFallbackData(pointer, size, optional_idx()); return; } D_ASSERT(size == block_size); @@ -924,6 +1016,14 @@ void BlockAllocator::FreeData(const data_ptr_t pointer, const idx_t size) const GetBlockAllocatorThreadLocalState(*this).Free(pointer); } +void BlockAllocator::FreeFallbackData(data_ptr_t pointer, idx_t size, optional_idx home) const { + if (allocation_cache->SupportsSize(size) && allocation_cache->TryFree(pointer, size, home)) { + return; + } + allocator.FreeData(pointer, size); + estimated_unflushed_memory.fetch_add(size, std::memory_order_relaxed); +} + data_ptr_t BlockAllocator::ReallocateData(const data_ptr_t pointer, const idx_t old_size, const idx_t new_size) const { if (old_size == new_size) { return pointer; @@ -977,14 +1077,21 @@ static void AdviseHugePages(data_ptr_t pointer, idx_t size) { #endif } -data_ptr_t BlockAllocator::AllocateHugeData(const idx_t size) const { - auto pointer = AllocateData(size); +data_ptr_t BlockAllocator::AllocateHugeData(const idx_t size, optional_idx &home) const { + home = optional_idx(); + auto pointer = size == block_size && TryUsePool() + ? AllocateData(size) + : RetryAfterReclaiming(*this, [&] { return allocation_cache->Allocate(size, home); }); AdviseHugePages(pointer, size); return pointer; } -void BlockAllocator::FreeHugeData(data_ptr_t pointer, const idx_t size) const { - FreeData(pointer, size); +void BlockAllocator::FreeHugeData(data_ptr_t pointer, const idx_t size, optional_idx home) const { + if (IsInPool(pointer)) { + FreeData(pointer, size); + } else { + FreeFallbackData(pointer, size, home); + } } bool BlockAllocator::SupportsFlush() const { diff --git a/src/duckdb/src/storage/checkpoint/table_data_writer.cpp b/src/duckdb/src/storage/checkpoint/table_data_writer.cpp index cbfbbf7fa..81d76639c 100644 --- a/src/duckdb/src/storage/checkpoint/table_data_writer.cpp +++ b/src/duckdb/src/storage/checkpoint/table_data_writer.cpp @@ -109,7 +109,7 @@ void SingleFileTableDataWriter::AddPendingPublication(unique_ptr checkpoint_context) : CheckpointWriter(db, context, checkpoint_context), - partial_block_manager(GetContext(), block_manager, PartialBlockType::FULL_CHECKPOINT), options(options_p) { + partial_block_manager(block_manager, PartialBlockType::FULL_CHECKPOINT), options(options_p) { } SingleFileCheckpointWriter::~SingleFileCheckpointWriter() { @@ -126,7 +128,7 @@ BlockManager &SingleFileCheckpointWriter::GetBlockManager() { } PartialBlockManager SingleFileCheckpointWriter::CreatePerIndexPartialBlockManager() { - return PartialBlockManager(GetContext(), GetBlockManager(), PartialBlockType::FULL_CHECKPOINT); + return PartialBlockManager(GetBlockManager(), PartialBlockType::FULL_CHECKPOINT); } MetadataWriter &SingleFileCheckpointWriter::GetMetadataWriter() { @@ -306,7 +308,7 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { }); serializer.End(); - partial_block_manager.FlushPartialBlocks(); + partial_block_manager.FlushPartialBlocks(GetContext()); for (auto &pending : pending_publications) { pending->Publish(); } @@ -334,7 +336,7 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { header.meta_block = meta_block.block_pointer; header.block_alloc_size = block_manager.GetBlockAllocSize(); header.vector_size = STANDARD_VECTOR_SIZE; - block_manager.WriteHeader(QueryContext(GetContext()), header); + block_manager.WriteHeader(QueryContext(GetContext()), header, options.visibility_bound); auto debug_verify_blocks = Settings::Get(db.GetDatabase()); if (debug_verify_blocks) { diff --git a/src/duckdb/src/storage/compression/bitpacking.cpp b/src/duckdb/src/storage/compression/bitpacking.cpp index 1dffb2f4f..de516c1e3 100644 --- a/src/duckdb/src/storage/compression/bitpacking.cpp +++ b/src/duckdb/src/storage/compression/bitpacking.cpp @@ -5,6 +5,7 @@ #include "duckdb/common/numeric_utils.hpp" #include "duckdb/common/optional.hpp" #include "duckdb/common/operator/subtract.hpp" +#include "duckdb/common/prefetch.hpp" #include "duckdb/common/vector.hpp" #include "duckdb/function/compression/compression.hpp" #include "duckdb/function/compression_function.hpp" @@ -28,6 +29,8 @@ constexpr const idx_t BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; static constexpr const idx_t BITPACKING_METADATA_GROUP_SIZE = STANDARD_VECTOR_SIZE > 512 ? STANDARD_VECTOR_SIZE : 2048; //! Scan tuning limit in values, independent of the on-disk algorithm group size. static constexpr idx_t BITPACKING_SCAN_BATCH_SIZE = 128; +static constexpr idx_t BITPACKING_PREFETCH_GROUPS = 8; +static constexpr idx_t BITPACKING_MAX_SCALAR_VALUES = 4; static_assert(BITPACKING_SCAN_BATCH_SIZE % BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE == 0, "Bitpacking scan batches must contain complete algorithm groups"); @@ -740,9 +743,55 @@ struct BitpackingScanState : public SegmentScanState { offset += advance_count; } + //! Read one unsigned FOR residual without materializing its algorithm group. + typename MakeUnsigned::type UnpackValue(idx_t row_offset) const { + using T_U = typename MakeUnsigned::type; + using T_WORD = typename MakeUnsigned::type; + constexpr idx_t WORD_BITS = sizeof(T_WORD) * 8; + D_ASSERT(metadata.mode == BitpackingMode::FOR); + D_ASSERT(row_offset < count); + if (width == 0) { + return T_U(0); + } + if (!payload) { + InternalException::Throw("Bitpacking algorithm group has no payload"); + } + const auto input = *payload; + const auto group_offset = + (row_offset / BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE) * algorithm_group_size; + Prefetch(group_offset, input.size(), BITPACKING_PREFETCH_GROUPS * algorithm_group_size, + [&](idx_t next_offset) { return input.data() + next_offset; }); + const auto bit_offset = row_offset * width; + auto word_offset = (bit_offset / WORD_BITS) * sizeof(T_WORD); + const auto shift = bit_offset % WORD_BITS; + T_U value = Load(input.SubArray(word_offset, sizeof(T_WORD)).data()) >> shift; + for (idx_t bits_read = WORD_BITS - shift; bits_read < width; bits_read += WORD_BITS) { + word_offset += sizeof(T_WORD); + value |= T_U(Load(input.SubArray(word_offset, sizeof(T_WORD)).data())) << bits_read; + } + const T_U mask = NumericLimits::Maximum() >> (sizeof(T) * 8 - width); + return value & mask; + } + //! Unpack complete groups, starting with the group containing offset. //! An unaligned offset only permits one group; its padding may extend beyond count. void UnpackAlgorithmGroups(unsafe_array_ptr target) const { + UnpackAlgorithmGroupsInternal(target); + } + + //! Decode FOR values or DELTA_FOR deltas, including their frame of reference. + void DecodeAlgorithmGroups(unsafe_array_ptr target) const { + if constexpr (sizeof(T) == sizeof(uint32_t) || sizeof(T) == sizeof(uint64_t)) { + UnpackAlgorithmGroupsInternal(target); + } else { + UnpackAlgorithmGroups(target); + ApplyFrameOfReference(target, frame_of_reference); + } + } + + private: + template + void UnpackAlgorithmGroupsInternal(unsafe_array_ptr target) const { D_ASSERT(!AtEnd()); D_ASSERT(metadata.mode == BitpackingMode::FOR || metadata.mode == BitpackingMode::DELTA_FOR); D_ASSERT(target.size() > 0); @@ -753,7 +802,7 @@ struct BitpackingScanState : public SegmentScanState { D_ASSERT(algorithm_group_index < algorithm_group_count); D_ASSERT(groups <= algorithm_group_count - algorithm_group_index); if (width == 0) { - std::fill(target.data(), target.data() + target.size(), T(0)); + std::fill(target.data(), target.data() + target.size(), APPLY_FRAME ? frame_of_reference : T(0)); return; } if (!payload) { @@ -761,9 +810,30 @@ struct BitpackingScanState : public SegmentScanState { } auto algorithm_group_offset = algorithm_group_index * algorithm_group_size; auto packed_groups = payload->SubArray(algorithm_group_offset, groups * algorithm_group_size); - // FOR residuals are non-negative, so they never need sign extension. - BitpackingPrimitives::UnPackBuffer(data_ptr_cast(target.data()), packed_groups.data(), target.size(), - width, true); + const auto group_payload = *payload; + const auto group_size = algorithm_group_size; + const auto bit_width = width; + auto prefetch = [&](idx_t input_offset) { + Prefetch(algorithm_group_offset + input_offset, group_payload.size(), + BITPACKING_PREFETCH_GROUPS * group_size, + [&](idx_t next_offset) { return group_payload.data() + next_offset; }); + }; + if constexpr (APPLY_FRAME) { + for (idx_t i = 0; i < groups; i++) { + prefetch(i * group_size); + } + BitpackingPrimitives::UnPackBufferWithFrame(data_ptr_cast(target.data()), packed_groups.data(), + target.size(), bit_width, frame_of_reference); + } else { + for (idx_t i = 0; i < groups; i++) { + auto input_offset = i * group_size; + prefetch(input_offset); + // FOR residuals are non-negative, so they never need sign extension. + BitpackingPrimitives::UnPackBlock( + data_ptr_cast(target.data() + i * BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE), + packed_groups.data() + input_offset, bit_width, true); + } + } } }; @@ -1112,15 +1182,15 @@ void BitpackingScanData(BitpackingScanState &scan_state, idx_t scan_count, T T *current_result_ptr = result_data + result_offset + scanned; if (offset_in_compression_group == 0 && to_scan >= BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE) { - // Decode complete algorithm groups together, then apply the frame once to the batch. + // Decode complete algorithm groups directly into the result. to_scan -= to_scan % BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; to_scan = MinValue(to_scan, BITPACKING_SCAN_BATCH_SIZE); - current_group.UnpackAlgorithmGroups(unsafe_array_ptr(current_result_ptr, to_scan)); + current_group.DecodeAlgorithmGroups(unsafe_array_ptr(current_result_ptr, to_scan)); } else { to_scan = MinValue(to_scan, BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE - offset_in_compression_group); // Decompress compression algorithm to buffer - current_group.UnpackAlgorithmGroups(unsafe_array_ptr( + current_group.DecodeAlgorithmGroups(unsafe_array_ptr( scan_state.decompression_buffer, BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE)); memcpy(current_result_ptr, scan_state.decompression_buffer + offset_in_compression_group, @@ -1129,15 +1199,11 @@ void BitpackingScanData(BitpackingScanState &scan_state, idx_t scan_count, T if (current_group.metadata.mode == BitpackingMode::DELTA_FOR) { unsafe_array_ptr current_results(reinterpret_cast(current_result_ptr), to_scan); - ApplyFrameOfReference(current_results, static_cast(current_group.frame_of_reference)); current_group.delta_offset = static_cast(DeltaDecode(current_results, static_cast(current_group.delta_offset))); if (scan_state.is_bool) { VerifyBooleanValues(current_result_ptr, to_scan); } - } else { - ApplyFrameOfReference(unsafe_array_ptr(current_result_ptr, to_scan), - current_group.frame_of_reference); } scanned += to_scan; @@ -1179,6 +1245,7 @@ static bool BitpackingSelectIsDense(BitpackingScanState &scan_state, idx_t ve scan_state.LoadGroup(scan_state.GetCurrentGroup().index + 1); } idx_t base = 0; + bool has_scalar_decoder = false; if (scan_state.HasCurrentGroup()) { auto ¤t = scan_state.GetCurrentGroup(); if (!current.AtEnd() && (current.metadata.mode == BitpackingMode::CONSTANT || @@ -1187,19 +1254,30 @@ static bool BitpackingSelectIsDense(BitpackingScanState &scan_state, idx_t ve return false; } base = current.offset % GROUP_SIZE; + has_scalar_decoder = current.metadata.mode == BitpackingMode::FOR; + } + if (sel_count > vector_count / 2) { + return true; } const idx_t total_groups = (base + vector_count + GROUP_SIZE - 1) / GROUP_SIZE; const idx_t dense_threshold = (total_groups + 1) / 2; - if (sel_count < dense_threshold) { + const idx_t min_rows_per_decoded_group = has_scalar_decoder ? BITPACKING_MAX_SCALAR_VALUES + 1 : 1; + if (sel_count / min_rows_per_decoded_group < dense_threshold) { return false; } - idx_t touched_groups = 0; + idx_t decoded_groups = 0; idx_t last_group = DConstants::INVALID_INDEX; for (idx_t i = 0; i < sel_count; i++) { const idx_t group = (base + sel.get_index(i)) / GROUP_SIZE; if (group != last_group) { last_group = group; - if (++touched_groups >= dense_threshold) { + // Groups served by scalar extraction do not require a full group decode. + if (has_scalar_decoder && + (sel_count - i <= BITPACKING_MAX_SCALAR_VALUES || + (base + sel.get_index(i + BITPACKING_MAX_SCALAR_VALUES)) / GROUP_SIZE != group)) { + continue; + } + if (++decoded_groups >= dense_threshold) { return true; } } @@ -1214,7 +1292,7 @@ void BitpackingSelect(ColumnSegment &segment, ColumnScanState &state, idx_t vect result.SetVectorType(VectorType::FLAT_VECTOR); T *result_data = FlatVector::GetDataMutable(result) + result_offset; - // selections touching most algorithm groups decode them anyway: scan the range and gather from it + // Scan dense selections and gather the selected rows. if (BitpackingSelectIsDense(scan_state, vector_count, sel, sel_count)) { auto scanned = scan_state.GetSelectBuffer(vector_count); BitpackingScanData(scan_state, vector_count, scanned, 0); @@ -1285,12 +1363,21 @@ void BitpackingSelect(ColumnSegment &segment, ColumnScanState &state, idx_t vect group.offset % BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; run_end = MinValue(run_end, pos + BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE - offset_in_algorithm_group); - group.UnpackAlgorithmGroups(unsafe_array_ptr(scan_state.decompression_buffer, - BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE)); - for (; i < sel_count && next_index(i) < run_end; i++) { - T_U value = static_cast( - scan_state.decompression_buffer[offset_in_algorithm_group + (sel.get_index(i) - pos)]); - result_data[i] = static_cast(value + static_cast(group.frame_of_reference)); + // Decode sparse selections directly and use the group decoder for denser selections. + if (i + BITPACKING_MAX_SCALAR_VALUES >= sel_count || + sel.get_index(i + BITPACKING_MAX_SCALAR_VALUES) >= run_end) { + for (; i < sel_count && next_index(i) < run_end; i++) { + const T_U value = group.UnpackValue(group.offset + sel.get_index(i) - pos); + result_data[i] = static_cast(value + static_cast(group.frame_of_reference)); + } + } else { + group.UnpackAlgorithmGroups(unsafe_array_ptr(scan_state.decompression_buffer, + BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE)); + for (; i < sel_count && next_index(i) < run_end; i++) { + T_U value = static_cast( + scan_state.decompression_buffer[offset_in_algorithm_group + (sel.get_index(i) - pos)]); + result_data[i] = static_cast(value + static_cast(group.frame_of_reference)); + } } break; } diff --git a/src/duckdb/src/storage/compression/dict_fsst.cpp b/src/duckdb/src/storage/compression/dict_fsst.cpp index 4c1e3dd67..697fbce9b 100644 --- a/src/duckdb/src/storage/compression/dict_fsst.cpp +++ b/src/duckdb/src/storage/compression/dict_fsst.cpp @@ -157,9 +157,12 @@ void DictFSSTSelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector D_ASSERT(sel_count == 0 || sel.get_index(sel_count - 1) < vector_count); auto &scan_state = state.scan_state->Cast(); if (scan_state.layout.mode != DictFSSTMode::FSST_ONLY && scan_type == ScanVectorType::SCAN_ENTIRE_VECTOR) { - // scan + slice, so that we can emit a dictionary vector - DictFSSTCompressionStorage::StringScan(segment, state, vector_count, result); - result.Slice(sel, sel_count); + if (sel_count <= vector_count / 64) { + scan_state.SelectToDictionaryVector(result, state.GetPositionInSegment(), vector_count, sel, sel_count); + } else { + DictFSSTCompressionStorage::StringScan(segment, state, vector_count, result); + result.Slice(sel, sel_count); + } return; } scan_state.Select(result, result_offset, state.GetPositionInSegment(), sel, sel_count, state.string_scan_type); @@ -175,62 +178,12 @@ static void DictFSSTFilter(ColumnSegment &segment, ColumnScanState &state, idx_t auto &scan_state = state.scan_state->Cast(); auto start = state.GetPositionInSegment(); if (scan_state.AllowDictionaryScan(vector_count)) { - // only pushdown filters on dictionaries - if (!scan_state.filter_result) { - // no filter result yet - apply filter to the dictionary - // initialize the filter result - setting everything to false - scan_state.filter_result = make_unsafe_uniq_array(scan_state.layout.dict_count); - - // Slot zero represents NULL and is not necessarily referenced by any row. - idx_t non_null_count = scan_state.layout.dict_count - 1; - Vector dict_data(scan_state.dictionary->data, /*offset=*/1, scan_state.layout.dict_count); - SelectionVector dict_sel; - idx_t filter_count = non_null_count; - ColumnSegment::FilterSelection(dict_sel, dict_data, filter_state, non_null_count, filter_count); - D_ASSERT(filter_count <= non_null_count); - - // now set all matching tuples to true - for (idx_t i = 0; i < filter_count; i++) { - auto idx = dict_sel.get_index(i) + 1; - D_ASSERT(idx < scan_state.layout.dict_count); - scan_state.filter_result[idx] = true; - } + if (!scan_state.filter_cache || !scan_state.filter_cache->IsValidFor(filter_state)) { + scan_state.filter_cache = + filter_state.CreateCache(scan_state.dictionary->data, scan_state.layout.dict_count); } - // Till now, we have a filter result for all non-NULL values. - auto &dict_sel = scan_state.GetSelVec(start, vector_count); - SelectionVector new_sel(sel_count); - idx_t approved_tuple_count = 0; - if (!sel.IsSet() && (scan_state.null_filter_result_initialized || !segment.GetStats().CanHaveNull())) { - approved_tuple_count = - SelectionVector::SelectFromBoolean(scan_state.filter_result.get(), &dict_sel, sel_count, - array_ptr(new_sel.data(), new_sel.Capacity())); - } else { - for (idx_t idx = 0; idx < sel_count; idx++) { - auto row_idx = sel.get_index(idx); - D_ASSERT(row_idx < vector_count); - auto dict_offset = dict_sel.get_index(row_idx); - // Evaluate NULL only when slot zero is referenced by an actual row. - if (dict_offset == 0 && !scan_state.null_filter_result_initialized) { - Vector null_data(scan_state.dictionary->data, /*offset=*/0, /*end=*/1); - SelectionVector null_sel; - idx_t null_filter_count = 1; - ColumnSegment::FilterSelection(null_sel, null_data, filter_state, 1, null_filter_count); - scan_state.filter_result[0] = null_filter_count == 1; - scan_state.null_filter_result_initialized = true; - } - // Check filter result for the value at the offset and assign selection vector. - if (!scan_state.filter_result[dict_offset]) { - // does not pass the filter - continue; - } - new_sel.set_index(approved_tuple_count++, row_idx); - } - } - if (approved_tuple_count < vector_count) { - sel.Initialize(new_sel); - } - sel_count = approved_tuple_count; - + const auto &dict_sel = scan_state.GetSelVec(start, vector_count); + scan_state.filter_cache->Filter(dict_sel, sel, sel_count); result.Dictionary(scan_state.dictionary, dict_sel, vector_count); return; } diff --git a/src/duckdb/src/storage/compression/dict_fsst/decompression.cpp b/src/duckdb/src/storage/compression/dict_fsst/decompression.cpp index 17b644903..f2b202e82 100644 --- a/src/duckdb/src/storage/compression/dict_fsst/decompression.cpp +++ b/src/duckdb/src/storage/compression/dict_fsst/decompression.cpp @@ -178,26 +178,17 @@ void CompressedStringScanState::LoadStringLengths() { } constexpr auto group_size = BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; string_lengths.resize(AlignValue(layout.dict_count)); + BitpackingPrimitives::UnPackBufferWithFrame(data_ptr_cast(string_lengths.data()), + layout.string_lengths.data(), string_lengths.size(), + layout.string_lengths_width, 0); // Both the entry count and each length fit in uint32_t, so their sum fits in uint64_t. uint64_t total_bytes = 0; - for (idx_t i = 0; i < layout.dict_count; i += group_size) { - BitpackingPrimitives::UnPackBlock( - data_ptr_cast(string_lengths.data() + i), - layout.string_lengths.data() + (i * layout.string_lengths_width) / 8, layout.string_lengths_width); - - // Validate only real entries, not the final group's padding. - const auto end = MinValue(i + group_size, layout.dict_count); - uint64_t group_bytes = 0; - for (idx_t j = i; j < end; j++) { - group_bytes += string_lengths[j]; - } - - // Each string offset sums earlier lengths, so bounding the total keeps all offsets in range. - total_bytes += group_bytes; - if (total_bytes > layout.dictionary.Size()) { - ThrowStringLengthsOutOfBounds(); - } + for (idx_t i = 0; i < layout.dict_count; i++) { + total_bytes += string_lengths[i]; + } + if (total_bytes > layout.dictionary.Size()) { + ThrowStringLengthsOutOfBounds(); } // Index 0 represents NULL, so its length must be 0 @@ -327,8 +318,8 @@ const SelectionVector &CompressedStringScanState::GetSelVec(idx_t start, idx_t s } sel_t *sel_vec_ptr = sel_vec->data(); - BitpackingPrimitives::UnPackBuffer(data_ptr_cast(sel_vec_ptr), indices.data(), decompress_count, - layout.dictionary_indices_width); + BitpackingPrimitives::UnPackBufferWithFrame(data_ptr_cast(sel_vec_ptr), indices.data(), decompress_count, + layout.dictionary_indices_width, 0); sel_vec->ShiftLeft(start_offset, scan_count); @@ -424,6 +415,37 @@ bool CompressedStringScanState::AllowDictionaryScan(idx_t scan_count) { return EnsureDictionary(); } +void CompressedStringScanState::SelectToDictionaryVector(Vector &result, idx_t start, idx_t vector_count, + const SelectionVector &sel, idx_t sel_count) { + D_ASSERT(layout.mode != DictFSSTMode::FSST_ONLY); + D_ASSERT(sel_count <= vector_count / 64); + EnsureDictionary(); + SelectionVector selected_indices(MaxValue(sel_count, 1)); + constexpr auto group_size = BitpackingPrimitives::BITPACKING_ALGORITHM_GROUP_SIZE; + uint32_t group[group_size]; + idx_t loaded_group = NumericLimits::Maximum(); + bool invalid_index = false; + for (idx_t i = 0; i < sel_count; i++) { + const auto row = start + sel.get_index(i); + const auto group_start = row - row % group_size; + if (group_start != loaded_group) { + const auto byte_offset = (group_start / group_size) * (group_size * layout.dictionary_indices_width / 8); + const auto byte_count = group_size * layout.dictionary_indices_width / 8; + auto bytes = layout.dictionary_indices.SubArray(byte_offset, byte_count); + BitpackingPrimitives::UnPackBlock(data_ptr_cast(group), bytes.data(), + layout.dictionary_indices_width); + loaded_group = group_start; + } + const auto index = group[row - group_start]; + invalid_index |= index >= layout.dict_count; + selected_indices.set_index(i, index); + } + if (invalid_index) { + ThrowDictionaryIndexOutOfBounds(); + } + result.Dictionary(dictionary, selected_indices, sel_count); +} + void CompressedStringScanState::ScanToDictionaryVector(ColumnSegment &segment, Vector &result, idx_t result_offset, idx_t start, idx_t scan_count) { D_ASSERT(scan_count == STANDARD_VECTOR_SIZE); diff --git a/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp b/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp index 70fa24ccf..33e2f4160 100644 --- a/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp +++ b/src/duckdb/src/storage/compression/fixed_size_uncompressed.cpp @@ -71,9 +71,11 @@ void UncompressedCompressState::CreateEmptySegment() { auto &state = compressed_segment->GetSegmentState()->Cast(); auto &storage_manager = checkpoint_data.GetStorageManager(); if (!storage_manager.InMemory()) { - auto &partial_block_manager = checkpoint_data.GetCheckpointState().GetPartialBlockManager(); + auto &checkpoint_state = checkpoint_data.GetCheckpointState(); + auto &partial_block_manager = checkpoint_state.GetPartialBlockManager(); state.block_manager = partial_block_manager.GetBlockManager(); - state.overflow_writer = make_uniq(partial_block_manager); + state.overflow_writer = + make_uniq(checkpoint_state.GetContext(), partial_block_manager); } } current_segment = std::move(compressed_segment); diff --git a/src/duckdb/src/storage/compression/numeric_constant.cpp b/src/duckdb/src/storage/compression/numeric_constant.cpp index 758defaad..a9dcd1a97 100644 --- a/src/duckdb/src/storage/compression/numeric_constant.cpp +++ b/src/duckdb/src/storage/compression/numeric_constant.cpp @@ -11,6 +11,7 @@ #include "duckdb/planner/table_filter.hpp" #include "duckdb/storage/segment/uncompressed.hpp" #include "duckdb/storage/table/column_segment.hpp" +#include "duckdb/storage/table/validity_column_data.hpp" #include "duckdb/storage/table/scan_state.hpp" #include "duckdb/planner/filter/expression_filter.hpp" @@ -173,10 +174,9 @@ unique_ptr ConstantInitScan(const QueryContext &context, Colum //===--------------------------------------------------------------------===// // Scan Partial //===--------------------------------------------------------------------===// -void ConstantFillFunctionValidity(ColumnSegment &segment, Vector &result, idx_t start_idx, idx_t count) { +void ConstantFillFunctionValidity(ColumnSegment &segment, ValidityMask &mask, idx_t start_idx, idx_t count) { const auto &stats = segment.GetStats(); if (stats.CanHaveNull()) { - auto &mask = FlatVector::ValidityMutable(result); for (idx_t i = 0; i < count; i++) { mask.SetInvalid(start_idx + i); } @@ -197,8 +197,8 @@ void ConstantFillFunction(ColumnSegment &segment, Vector &result, idx_t start_id } } -void ConstantScanPartialValidity(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, - idx_t result_offset) { +void ConstantScanValidity(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, ValidityMask &result, + idx_t result_offset, ScanVectorType) { ConstantFillFunctionValidity(segment, result, result_offset, scan_count); } @@ -211,19 +211,6 @@ void ConstantScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t s //===--------------------------------------------------------------------===// // Scan base data //===--------------------------------------------------------------------===// -void ConstantScanFunctionValidity(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result) { - const auto &stats = segment.GetStats(); - if (stats.CanHaveNull()) { - if (result.GetType().InternalType() == PhysicalType::STRUCT || - result.GetVectorType() == VectorType::CONSTANT_VECTOR) { - ConstantVector::SetNull(result, count_t(scan_count)); - } else { - result.Flatten(); - ConstantFillFunctionValidity(segment, result, 0, scan_count); - } - } -} - template void ConstantScanFunction(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result) { const auto &nstats = segment.GetStats(); @@ -237,14 +224,9 @@ void ConstantScanFunction(ColumnSegment &segment, ColumnScanState &state, idx_t //===--------------------------------------------------------------------===// // Select //===--------------------------------------------------------------------===// -void ConstantSelectValidity(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, Vector &result, - const SelectionVector &sel, idx_t sel_count, idx_t result_offset, - ScanVectorType scan_type) { - if (scan_type == ScanVectorType::SCAN_ENTIRE_VECTOR) { - ConstantScanFunctionValidity(segment, state, sel_count, result); - return; - } - ConstantScanPartialValidity(segment, state, sel_count, result, result_offset); +void ConstantSelectValidity(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, ValidityMask &result, + const SelectionVector &sel, idx_t sel_count, idx_t result_offset) { + ConstantFillFunctionValidity(segment, result, result_offset, sel_count); } template @@ -297,7 +279,7 @@ void ConstantFilterValidity(ColumnSegment &segment, ColumnScanState &state, idx_ return; } } - ConstantScanFunctionValidity(segment, state, vector_count, result); + ValidityColumnData::ScanValidity(segment, state, vector_count, result); } //===--------------------------------------------------------------------===// @@ -306,10 +288,12 @@ void ConstantFilterValidity(ColumnSegment &segment, ColumnScanState &state, idx_ CompressionFunction ConstantGetFunctionValidity(PhysicalType data_type) { D_ASSERT(data_type == PhysicalType::BIT); CompressionFunction result(CompressionType::COMPRESSION_CONSTANT, data_type, nullptr, nullptr, nullptr, nullptr, - nullptr, nullptr, ConstantInitScan, ConstantScanFunctionValidity, - ConstantScanPartialValidity, UncompressedFunctions::EmptySkip, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, ConstantSelectValidity, - ConstantFilterValidity); + nullptr, nullptr, ConstantInitScan, ValidityColumnData::ScanValidity, + ValidityColumnData::ScanPartialValidity, UncompressedFunctions::EmptySkip, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + ValidityColumnData::SelectValidity, ConstantFilterValidity); + result.scan_validity = ConstantScanValidity; + result.select_validity = ConstantSelectValidity; result.supports_null_block = true; return result; } diff --git a/src/duckdb/src/storage/compression/rle.cpp b/src/duckdb/src/storage/compression/rle.cpp index 4cb9c1efd..43a8fc963 100644 --- a/src/duckdb/src/storage/compression/rle.cpp +++ b/src/duckdb/src/storage/compression/rle.cpp @@ -419,6 +419,37 @@ struct RLEScanState : public SegmentScanState { return position_in_entry >= run_length; } + template + void VisitSelectedRows(idx_t vector_count, const SelectionVector &sel, idx_t sel_count, OP operation) { + auto run = GetCurrentRun(); + auto entry_index = entry_pos; + idx_t run_end = run.length - position_in_entry; + idx_t previous = 0; + for (idx_t i = 0; i < sel_count; i++) { + const auto row = sel.get_index(i); + if (row < previous || row >= vector_count) { + InternalException::Throw("Invalid row selection in RLE scan"); + } + while (row >= run_end) { + run = layout.GetValidatedRun(++entry_index); + run_end += run.length; + } + operation(row, entry_index, run.value); + previous = row; + } + entry_pos = entry_index; + position_in_entry = run.length - (run_end - previous); + SkipInternal(vector_count - previous); + } + + SelectionVector &GetSelectionBuffer(idx_t count) { + // A previous result may still reference the selected rows. + if (selected_rows.Capacity() < count || selected_rows.sel_data().use_count() > 1) { + selected_rows.Initialize(count); + } + return selected_rows; + } + BufferHandle handle; //! Segment row count loaded from the file and used to validate runs as they are reached. const idx_t segment_count; @@ -426,8 +457,11 @@ struct RLEScanState : public SegmentScanState { idx_t entry_pos; idx_t position_in_entry; //! If we are running a filter over the column - the runs that match the filter - unsafe_unique_array matching_runs; - idx_t matching_run_count = 0; + unique_ptr filter_cache; + SelectionVector run_indices; + SelectionVector selected_rows; + vector run_offsets; + vector run_row_counts; }; template @@ -498,17 +532,19 @@ void RLEScanPartialInternal(ColumnSegment &segment, ColumnScanState &state, idx_ auto result_data = FlatVector::GetDataMutable(result); const idx_t result_end = result_offset + scan_count; + auto entry_pos = scan_state.entry_pos; + auto position_in_entry = scan_state.position_in_entry; while (result_offset < result_end) { // An empty run writes nothing and advances below, so this loop need not skip it separately. - auto run = scan_state.layout.GetValidatedRun(scan_state.entry_pos); - auto run_count = run.length - scan_state.position_in_entry; + auto run = scan_state.layout.GetValidatedRun(entry_pos); + auto run_count = run.length - position_in_entry; idx_t remaining_scan_count = result_end - result_offset; T element = run.value; if (DUCKDB_UNLIKELY(run_count > remaining_scan_count)) { for (idx_t i = 0; i < remaining_scan_count; i++) { result_data[result_offset + i] = element; } - scan_state.position_in_entry += remaining_scan_count; + position_in_entry += remaining_scan_count; break; } @@ -517,8 +553,11 @@ void RLEScanPartialInternal(ColumnSegment &segment, ColumnScanState &state, idx_ } result_offset += run_count; - scan_state.ForwardToNextRun(); + entry_pos++; + position_in_entry = 0; } + scan_state.entry_pos = entry_pos; + scan_state.position_in_entry = position_in_entry; } template @@ -581,106 +620,138 @@ void RLESelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector_coun template void RLEFilter(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, Vector &result, SelectionVector &sel, idx_t &sel_count, const TableFilter &filter, TableFilterState &filter_state) { + D_ASSERT(sel_count <= vector_count); auto &scan_state = state.scan_state->Cast>(); - - if (!scan_state.matching_runs) { - // we haven't applied the filter yet - // apply the filter to all RLE values at once - auto total_run_count = scan_state.layout.ValidateAllRuns(); - auto run_values = scan_state.layout.GetRunValues(total_run_count); - auto data_pointer = const_cast(run_values.data()); - - // initialize the filter set to all false (all runs are filtered out) - scan_state.matching_runs = make_unsafe_uniq_array(total_run_count); - memset(scan_state.matching_runs.get(), 0, sizeof(bool) * total_run_count); - - // execute the filter over all runs at once - Vector run_vector(result.GetType(), data_ptr_cast(data_pointer), total_run_count); - - SelectionVector run_matches; - scan_state.matching_run_count = total_run_count; - ColumnSegment::FilterSelection(run_matches, run_vector, filter_state, total_run_count, - scan_state.matching_run_count); - - // for any runs that pass the filter - set the matches to true - for (idx_t i = 0; i < scan_state.matching_run_count; i++) { - auto idx = run_matches.get_index(i); - scan_state.matching_runs[idx] = true; - } + const auto run_count = scan_state.layout.ValidateAllRuns(); + if (sel_count == 0) { + scan_state.SkipInternal(vector_count); + return; + } + const auto run_values = scan_state.layout.GetRunValues(run_count); + if (!scan_state.filter_cache || !scan_state.filter_cache->IsValidFor(filter_state)) { + Vector values(result.GetType(), run_count); + memcpy(FlatVector::GetDataMutable(values), run_values.data(), run_count * sizeof(T)); + FlatVector::SetSize(values, count_t(run_count)); + scan_state.filter_cache = filter_state.CreateCache(values, run_count); } - if (scan_state.matching_run_count == 0) { - // early-out, no runs match the filter so the filter can never pass + if (scan_state.filter_cache->CanSkipAll()) { + scan_state.SkipInternal(vector_count); sel_count = 0; return; } - // scan (the subset of) the matching runs AND set the output selection vector with the rows that match - auto result_data = FlatVector::GetDataMutable(result); - result.SetVectorType(VectorType::FLAT_VECTOR); - - idx_t matching_count = 0; - SelectionVector matching_sel(sel_count); + if (scan_state.filter_cache->CanAcceptAll()) { + SelectionVector no_values; + scan_state.filter_cache->Filter(no_values, sel, sel_count); + RLEScan(segment, state, vector_count, result); + return; + } + const auto current_run = scan_state.GetCurrentRun(); + if (CanEmitConstantVector(scan_state.position_in_entry, current_run.length, vector_count)) { + scan_state.filter_cache->FilterConstant(scan_state.entry_pos, sel_count); + RLEScanConstant(scan_state, current_run, vector_count, result); + return; + } if (!sel.IsSet()) { - // no selection vector yet - fast path - // this is essentially the normal scan, but we apply the filter and fill the selection vector - idx_t result_offset = 0; - idx_t result_end = sel_count; - while (result_offset < result_end) { - auto run = scan_state.GetCurrentRun(); - auto run_count = run.length - scan_state.position_in_entry; - idx_t remaining_scan_count = result_end - result_offset; - // the run is scanned - scan it - T element = run.value; - if (DUCKDB_UNLIKELY(run_count > remaining_scan_count)) { - if (scan_state.matching_runs[scan_state.entry_pos]) { - for (idx_t i = 0; i < remaining_scan_count; i++) { - result_data[result_offset + i] = element; - matching_sel.set_index(matching_count++, result_offset + i); + if (const auto matches = scan_state.filter_cache->GetPureMask()) { + auto &selected_rows = scan_state.GetSelectionBuffer(sel_count); + result.SetVectorType(VectorType::FLAT_VECTOR); + auto writer = FlatVector::ScatterWriter(result); + idx_t offset = 0; + idx_t accepted_rows = 0; + while (offset < vector_count) { + const auto run = scan_state.GetCurrentRun(); + const auto count = MinValue(run.length - scan_state.position_in_entry, vector_count - offset); + if (offset < sel_count && (*matches)[scan_state.entry_pos]) { + const auto end = offset + MinValue(count, sel_count - offset); + for (idx_t row = offset; row < end; row++) { + writer[row] = run.value; + selected_rows.set_index(accepted_rows++, row); } } - scan_state.position_in_entry += remaining_scan_count; - break; - } - - if (scan_state.matching_runs[scan_state.entry_pos]) { - for (idx_t i = 0; i < run_count; i++) { - result_data[result_offset + i] = element; - matching_sel.set_index(matching_count++, result_offset + i); + offset += count; + scan_state.position_in_entry += count; + if (scan_state.ExhaustedRun(run.length)) { + scan_state.ForwardToNextRun(); } } - - result_offset += run_count; - scan_state.ForwardToNextRun(); + if (accepted_rows != sel_count) { + sel.Initialize(selected_rows); + } + sel_count = accepted_rows; + return; } - } else { - // we already have a selection applied - this is more complex since we need to merge it with our filter - // use a simpler (but slower) approach - idx_t prev_idx = 0; - for (idx_t i = 0; i < sel_count; i++) { - auto read_idx = sel.get_index(i); - if (read_idx < prev_idx) { - InternalException::Throw("Error in RLEFilter - selection vector indices are not ordered"); + if (scan_state.run_indices.Capacity() < vector_count) { + scan_state.run_indices.Initialize(vector_count); + } + scan_state.run_offsets.clear(); + scan_state.run_row_counts.clear(); + idx_t offset = 0; + while (offset < vector_count) { + const auto run = scan_state.GetCurrentRun(); + const auto count = MinValue(run.length - scan_state.position_in_entry, vector_count - offset); + if (offset < sel_count) { + scan_state.run_indices.set_index(scan_state.run_row_counts.size(), scan_state.entry_pos); + scan_state.run_offsets.push_back(offset); + scan_state.run_row_counts.push_back(MinValue(count, sel_count - offset)); + } + offset += count; + scan_state.position_in_entry += count; + if (scan_state.ExhaustedRun(run.length)) { + scan_state.ForwardToNextRun(); } - D_ASSERT(read_idx < vector_count); - // skip forward to the next index - scan_state.SkipInternal(read_idx - prev_idx); - prev_idx = read_idx; - auto run = scan_state.GetCurrentRun(); - if (!scan_state.matching_runs[scan_state.entry_pos]) { - // this run is filtered out - we don't need to scan it - continue; + } + SelectionVector selected_runs; + idx_t selected_run_count = scan_state.run_row_counts.size(); + scan_state.filter_cache->FilterRuns( + scan_state.run_indices, + array_ptr(scan_state.run_row_counts.data(), scan_state.run_row_counts.size()), selected_runs, + selected_run_count); + auto &selected_rows = scan_state.GetSelectionBuffer(sel_count); + result.SetVectorType(VectorType::FLAT_VECTOR); + auto writer = FlatVector::ScatterWriter(result); + idx_t accepted_rows = 0; + for (idx_t i = 0; i < selected_run_count; i++) { + const auto run = selected_runs.get_index(i); + const auto value = run_values[scan_state.run_indices.get_index(run)]; + const auto start = scan_state.run_offsets[run]; + const auto count = scan_state.run_row_counts[run]; + for (idx_t row = start; row < start + count; row++) { + writer[row] = value; + selected_rows.set_index(accepted_rows++, row); } - // the run is not filtered out - read the element - result_data[read_idx] = run.value; - matching_sel.set_index(matching_count++, read_idx); } - // skip the tail - scan_state.SkipInternal(vector_count - prev_idx); + if (accepted_rows != sel_count) { + sel.Initialize(selected_rows); + } + sel_count = accepted_rows; + return; } - - // set up the filter result - if (matching_count != sel_count) { - sel.Initialize(matching_sel); - sel_count = matching_count; + result.SetVectorType(VectorType::FLAT_VECTOR); + auto writer = FlatVector::ScatterWriter(result); + if (const auto matches = scan_state.filter_cache->GetPureMask()) { + auto &selected_rows = scan_state.GetSelectionBuffer(sel_count); + idx_t accepted_rows = 0; + scan_state.VisitSelectedRows(vector_count, sel, sel_count, [&](idx_t row, idx_t run, T value) { + if ((*matches)[run]) { + writer[row] = value; + selected_rows.set_index(accepted_rows++, row); + } + }); + if (accepted_rows != sel_count) { + sel.Initialize(selected_rows); + } + sel_count = accepted_rows; + return; + } + if (scan_state.run_indices.Capacity() < vector_count) { + scan_state.run_indices.Initialize(vector_count); + } + scan_state.VisitSelectedRows(vector_count, sel, sel_count, + [&](idx_t row, idx_t run, T) { scan_state.run_indices.set_index(row, run); }); + scan_state.filter_cache->Filter(scan_state.run_indices, sel, sel_count); + for (idx_t i = 0; i < sel_count; i++) { + const auto row = sel.get_index(i); + writer[row] = run_values[scan_state.run_indices.get_index(row)]; } } diff --git a/src/duckdb/src/storage/compression/roaring/common.cpp b/src/duckdb/src/storage/compression/roaring/common.cpp index c6045409a..6857ecf42 100644 --- a/src/duckdb/src/storage/compression/roaring/common.cpp +++ b/src/duckdb/src/storage/compression/roaring/common.cpp @@ -8,6 +8,7 @@ #include "duckdb/storage/storage_manager.hpp" #include "duckdb/storage/table/column_data_checkpointer.hpp" #include "duckdb/storage/table/column_segment.hpp" +#include "duckdb/storage/table/validity_column_data.hpp" #include "duckdb/storage/table/scan_state.hpp" #include "duckdb/storage/segment/uncompressed.hpp" #include "duckdb/common/bitpacking.hpp" @@ -234,11 +235,10 @@ void ExtractValidityMaskToData(const ValidityMask &validity, Vector &dst, idx_t } } -void RoaringScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, - idx_t result_offset) { +void RoaringScanValidity(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, ValidityMask &result_mask, + idx_t result_offset, ScanVectorType) { auto &scan_state = state.scan_state->Cast(); auto start = state.GetPositionInSegment(); - auto &result_mask = FlatVector::ValidityMutable(result); scan_state.ScanPartial(start, result_mask, result_offset, scan_count); } void RoaringScanPartialBoolean(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, @@ -250,11 +250,6 @@ void RoaringScanPartialBoolean(ColumnSegment &segment, ColumnScanState &state, i scan_state.ScanPartial(start, mask, 0, scan_count); ExtractValidityMaskToData(mask, result, result_offset, scan_count); } -void RoaringScan(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result) { - result.Flatten(); - RoaringScanPartial(segment, state, scan_count, result, 0); -} - void RoaringScanBoolean(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result) { auto &scan_state = state.scan_state->Cast(); auto start = state.GetPositionInSegment(); @@ -294,8 +289,8 @@ CompressionFunction GetCompressionFunction(PhysicalType data_type) { case PhysicalType::BIT: { analyze = roaring::RoaringAnalyze; compress = roaring::RoaringCompress; - scan = roaring::RoaringScan; - scan_partial = roaring::RoaringScanPartial; + scan = ValidityColumnData::ScanValidity; + scan_partial = ValidityColumnData::ScanPartialValidity; break; } case PhysicalType::BOOL: { @@ -312,6 +307,9 @@ CompressionFunction GetCompressionFunction(PhysicalType data_type) { roaring::RoaringFinalAnalyze, roaring::RoaringInitCompression, compress, roaring::RoaringFinalizeCompress, roaring::RoaringInitScan, scan, scan_partial, roaring::RoaringSkip, roaring::RoaringInitSegment); + if (data_type == PhysicalType::BIT) { + result.scan_validity = roaring::RoaringScanValidity; + } result.zero_initialize_segments = false; return result; } diff --git a/src/duckdb/src/storage/compression/roaring/scan.cpp b/src/duckdb/src/storage/compression/roaring/scan.cpp index 43f803e30..2fa9a8405 100644 --- a/src/duckdb/src/storage/compression/roaring/scan.cpp +++ b/src/duckdb/src/storage/compression/roaring/scan.cpp @@ -306,19 +306,17 @@ ContainerScanState &RoaringScanState::LoadContainer(idx_t container_index, idx_t auto word_count = container_size / ValidityMask::BITS_PER_VALUE + (container_size % ValidityMask::BITS_PER_VALUE != 0); auto bitset = reader.GetArray(0, word_count); - current_container = make_uniq(container_index, container_size, bitset); + InitializeContainer(bitset_state, container_index, container_size, bitset); } else if (metadata.IsRun()) { D_ASSERT(metadata.IsInverted()); auto number_of_runs = metadata.NumberOfRuns(); if (number_of_runs >= COMPRESSED_RUN_THRESHOLD) { auto segments = reader.ReadBytes(COMPRESSED_SEGMENT_COUNT); auto data = reader.ReadBytes(number_of_runs * 2); - current_container = make_uniq(container_index, container_size, - number_of_runs, segments, data); + InitializeContainer(compressed_run_state, container_index, container_size, number_of_runs, segments, data); } else { auto data = reader.GetArray(0, number_of_runs); - current_container = - make_uniq(container_index, container_size, number_of_runs, data); + InitializeContainer(uncompressed_run_state, container_index, container_size, number_of_runs, data); } } else { auto cardinality = metadata.Cardinality(); @@ -326,20 +324,18 @@ ContainerScanState &RoaringScanState::LoadContainer(idx_t container_index, idx_t auto segments = reader.ReadBytes(COMPRESSED_SEGMENT_COUNT); auto data = reader.ReadBytes(cardinality); if (metadata.IsInverted()) { - current_container = make_uniq>(container_index, container_size, - cardinality, segments, data); + InitializeContainer(compressed_null_state, container_index, container_size, cardinality, segments, + data); } else { - current_container = make_uniq>( - container_index, container_size, cardinality, segments, data); + InitializeContainer(compressed_non_null_state, container_index, container_size, cardinality, segments, + data); } } else { auto data = reader.GetArray(0, cardinality); if (metadata.IsInverted()) { - current_container = make_uniq>( - container_index, container_size, cardinality, data); + InitializeContainer(uncompressed_null_state, container_index, container_size, cardinality, data); } else { - current_container = make_uniq>( - container_index, container_size, cardinality, data); + InitializeContainer(uncompressed_non_null_state, container_index, container_size, cardinality, data); } } } diff --git a/src/duckdb/src/storage/compression/validity_uncompressed.cpp b/src/duckdb/src/storage/compression/validity_uncompressed.cpp index 0e00c1bb1..f395bc6d3 100644 --- a/src/duckdb/src/storage/compression/validity_uncompressed.cpp +++ b/src/duckdb/src/storage/compression/validity_uncompressed.cpp @@ -4,7 +4,7 @@ #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/compression/compression_segment_reader.hpp" #include "duckdb/storage/segment/uncompressed.hpp" -#include "duckdb/storage/table/column_data.hpp" +#include "duckdb/storage/table/validity_column_data.hpp" #include "duckdb/storage/table/column_segment.hpp" #include "duckdb/storage/table/scan_state.hpp" @@ -476,51 +476,31 @@ void ValidityUncompressed::AlignedScan(unsafe_array_ptr input, } } -void ValidityScanPartial(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, - idx_t result_offset) { - auto start = state.GetPositionInSegment(); +void ValidityScan(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, ValidityMask &result_mask, + idx_t result_offset, ScanVectorType scan_type) { if (scan_count == 0) { return; } + auto start = state.GetPositionInSegment(); D_ASSERT(start <= segment.count && scan_count <= segment.count - start); - - static_assert(sizeof(validity_t) == sizeof(uint64_t), "validity_t should be 64-bit"); auto &scan_state = state.scan_state->Cast(); - auto input_data = ValidityScanData(scan_state.reader, start, scan_count); D_ASSERT(scan_state.block_id == segment.GetBlockHandle()->BlockId()); - auto &result_mask = FlatVector::ValidityMutable(result); auto input_start = start % ValidityMask::BITS_PER_VALUE; - ValidityUncompressed::UnalignedScan(input_data, input_start + scan_count, input_start, result_mask, result_offset, - scan_count); -} - -void ValidityScan(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result) { - auto start = state.GetPositionInSegment(); - if (scan_count == 0) { - return; - } - D_ASSERT(start <= segment.count && scan_count <= segment.count - start); - - result.Flatten(); - if (start % ValidityMask::BITS_PER_VALUE == 0) { - auto &scan_state = state.scan_state->Cast(); - - auto input_data = ValidityScanData(scan_state.reader, start, scan_count); - D_ASSERT(scan_state.block_id == segment.GetBlockHandle()->BlockId()); - auto &result_mask = FlatVector::ValidityMutable(result); + if (scan_type == ScanVectorType::SCAN_ENTIRE_VECTOR && input_start == 0) { + D_ASSERT(result_offset == 0); ValidityUncompressed::AlignedScan(input_data, 0, result_mask, scan_count); } else { - // unaligned scan: fall back to scan_partial which does bitshift tricks - ValidityScanPartial(segment, state, scan_count, result, 0); + ValidityUncompressed::UnalignedScan(input_data, input_start + scan_count, input_start, result_mask, + result_offset, scan_count); } } //===--------------------------------------------------------------------===// // Select //===--------------------------------------------------------------------===// -void ValiditySelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, Vector &result, - const SelectionVector &sel, idx_t sel_count, idx_t result_offset, ScanVectorType) { +void ValiditySelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, ValidityMask &result_mask, + const SelectionVector &sel, idx_t sel_count, idx_t result_offset) { auto start = state.GetPositionInSegment(); if (sel_count == 0) { return; @@ -528,14 +508,9 @@ void ValiditySelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector D_ASSERT(start <= segment.count && vector_count <= segment.count - start); D_ASSERT(sel_count <= vector_count); - if (result_offset == 0) { - result.Flatten(); - } - auto &scan_state = state.scan_state->Cast(); auto input_data = ValidityScanData(scan_state.reader, start, vector_count); auto input_start = start % ValidityMask::BITS_PER_VALUE; - auto &result_mask = FlatVector::ValidityMutable(result); for (idx_t i = 0; i < sel_count; i++) { auto selected_index = sel.get_index(i); D_ASSERT(selected_index < vector_count); @@ -625,13 +600,15 @@ void ValidityRevertAppend(ColumnSegment &segment, idx_t new_count) { //===--------------------------------------------------------------------===// CompressionFunction ValidityUncompressed::GetFunction(PhysicalType data_type) { D_ASSERT(data_type == PhysicalType::BIT); - CompressionFunction result(CompressionType::COMPRESSION_UNCOMPRESSED, data_type, ValidityInitAnalyze, - ValidityAnalyze, ValidityFinalAnalyze, UncompressedFunctions::InitCompression, - UncompressedFunctions::Compress, UncompressedFunctions::FinalizeCompress, - ValidityInitScan, ValidityScan, ValidityScanPartial, UncompressedFunctions::EmptySkip, - ValidityInitSegment, ValidityInitAppend, ValidityAppend, ValidityFinalizeAppend, - ValidityRevertAppend); - result.select = ValiditySelect; + CompressionFunction result( + CompressionType::COMPRESSION_UNCOMPRESSED, data_type, ValidityInitAnalyze, ValidityAnalyze, + ValidityFinalAnalyze, UncompressedFunctions::InitCompression, UncompressedFunctions::Compress, + UncompressedFunctions::FinalizeCompress, ValidityInitScan, ValidityColumnData::ScanValidity, + ValidityColumnData::ScanPartialValidity, UncompressedFunctions::EmptySkip, ValidityInitSegment, + ValidityInitAppend, ValidityAppend, ValidityFinalizeAppend, ValidityRevertAppend); + result.scan_validity = ValidityScan; + result.select_validity = ValiditySelect; + result.select = ValidityColumnData::SelectValidity; result.zero_initialize_segments = false; return result; } diff --git a/src/duckdb/src/storage/compression/zstd.cpp b/src/duckdb/src/storage/compression/zstd.cpp index 6e954383c..3a5ff11c3 100644 --- a/src/duckdb/src/storage/compression/zstd.cpp +++ b/src/duckdb/src/storage/compression/zstd.cpp @@ -301,7 +301,7 @@ class ZSTDCompressionState : public CompressionState { buffer_collection.SetCurrentBuffer(buffer.slot); auto &buffer_handle = buffer_collection.BufferHandleMutable(); if (!buffer_handle.IsValid()) { - buffer_handle = buffer_manager.Allocate(partial_block_manager.GetQueryContext(), + buffer_handle = buffer_manager.Allocate(QueryContext(checkpoint_data.GetCheckpointState().GetContext()), MemoryTag::OVERFLOW_STRINGS, &block_manager); } return; @@ -477,7 +477,8 @@ class ZSTDCompressionState : public CompressionState { // Write the current page to disk auto &block_manager = partial_block_manager.GetBlockManager(); - block_manager.Write(partial_block_manager.GetQueryContext(), buffer.GetFileBuffer(), block_id); + block_manager.Write(QueryContext(checkpoint_data.GetCheckpointState().GetContext()), buffer.GetFileBuffer(), + block_id); } void FlushVector() { @@ -548,7 +549,8 @@ class ZSTDCompressionState : public CompressionState { auto &buffer_manager = BufferManager::GetBufferManager(checkpoint_data.GetDatabase()); buffer_collection.segment_handle = - buffer_manager.Pin(partial_block_manager.GetQueryContext(), buffer_collection.segment->GetBlockHandle()); + buffer_manager.Pin(QueryContext(checkpoint_data.GetCheckpointState().GetContext()), + buffer_collection.segment->GetBlockHandle()); } void FlushSegment() { diff --git a/src/duckdb/src/storage/data_table.cpp b/src/duckdb/src/storage/data_table.cpp index 74a34f64a..8533475b0 100644 --- a/src/duckdb/src/storage/data_table.cpp +++ b/src/duckdb/src/storage/data_table.cpp @@ -176,12 +176,12 @@ DataTable::DataTable(ClientContext &context, DataTable &parent, BoundConstraint } if (constraint.type != ConstraintType::UNIQUE) { - VerifyNewConstraint(local_storage, parent, constraint); + VerifyNewConstraint(context, local_storage, parent, constraint); } else if (constraint.Cast().is_primary_key) { // the key columns become NOT NULL: verify them under the append lock, including rows committed concurrently for (auto &key : constraint.Cast().keys) { BoundNotNullConstraint not_null(key); - VerifyNewConstraint(local_storage, parent, not_null); + VerifyNewConstraint(context, local_storage, parent, not_null); } } local_storage.MoveStorage(parent, *this); @@ -232,7 +232,7 @@ DataTable::DataTable(ClientContext &context, DataTable &parent, idx_t changed_id // re-verify any column constraint that the rewrite could have violated (e.g. NOT NULL) if (constraint_to_verify) { - VerifyNewConstraint(local_storage, *this, *constraint_to_verify); + VerifyNewConstraint(context, local_storage, *this, *constraint_to_verify); } } catch (...) { // nothing reached the catalog, so no undo entry will restore the parent @@ -326,9 +326,23 @@ void DataTable::InitializeParallelScan(ClientContext &context, ParallelTableScan optional_idx DataTable::NextParallelScan(ClientContext &context, ParallelTableScanState &state, TableScanState &scan_state, bool initialize_columns) { + return NextParallelScanInternal(context, state, scan_state, initialize_columns, nullptr); +} + +bool DataTable::NextParallelScanAssignment(ClientContext &context, ParallelTableScanState &state, + TableScanState &scan_state, TableScanAssignment &assignment) { + return NextParallelScanInternal(context, state, scan_state, false, assignment).IsValid(); +} + +optional_idx DataTable::NextParallelScanInternal(ClientContext &context, ParallelTableScanState &state, + TableScanState &scan_state, bool initialize_columns, + optional_ptr assignment) { const auto rows = row_groups->NextParallelScan(context, state.scan_state, scan_state.table_state, initialize_columns); if (rows.IsValid()) { + if (assignment) { + *assignment = TableScanAssignment(scan_state.table_state, TableScanSource::PERSISTENT); + } return rows; } if (state.scan_state.row_number_base.IsValid()) { @@ -336,8 +350,12 @@ optional_idx DataTable::NextParallelScan(ClientContext &context, ParallelTableSc scan_state.local_state.row_number_base = state.scan_state.row_number_base.GetIndex(); } auto &local_storage = LocalStorage::Get(context, db); - return local_storage.NextParallelScan(context, *this, state.local_state, scan_state.local_state, - initialize_columns); + const auto local_rows = + local_storage.NextParallelScan(context, *this, state.local_state, scan_state.local_state, initialize_columns); + if (local_rows.IsValid() && assignment) { + *assignment = TableScanAssignment(scan_state.local_state, TableScanSource::TRANSACTION_LOCAL); + } + return local_rows; } void DataTable::Scan(DuckTransaction &transaction, DataChunk &result, TableScanState &state) { @@ -526,7 +544,7 @@ void DataTable::Fetch(DuckTransaction &transaction, DataChunk &result, const vec D_ASSERT(result.size() == committed_count); // Fetch local rows into a separate chunk. - auto &allocator = Allocator::Get(local_storage.GetContext().GetDatabase()); + auto &allocator = Allocator::Get(db); DataChunk local_chunk; local_chunk.Initialize(allocator, result.GetTypes()); Vector local_row_ids(row_identifiers, local_sel, local_count); @@ -715,7 +733,7 @@ void DataTable::VerifyForeignKeyConstraint(optional_ptr stora // Local constraint verification. if (local_verification) { - auto &local_indexes = local_storage.GetIndexes(data_table); + auto &local_indexes = local_storage.GetIndexes(context.GetContext(), data_table); local_indexes.VerifyForeignKey(sibling_delete_indexes, dst_keys_ptr, dst_chunk, local_conflict_manager); local_error = IsForeignKeyConstraintError(local_conflict_manager, is_append, count); } @@ -741,7 +759,7 @@ void DataTable::VerifyForeignKeyConstraint(optional_ptr stora throw ConstraintException(message); } - auto &transact_index = local_storage.GetIndexes(data_table); + auto &transact_index = local_storage.GetIndexes(context.GetContext(), data_table); transaction_index_entry = transact_index.FindForeignKeyIndex(dst_keys_ptr, fk_type); if (local_error && global_error && is_append) { @@ -802,14 +820,14 @@ void DataTable::VerifyDeleteForeignKeyConstraint(optional_ptr VerifyForeignKeyConstraint(storage, bound_foreign_key, context, chunk, VerifyExistenceType::DELETE_FK); } -void DataTable::VerifyNewConstraint(LocalStorage &local_storage, DataTable &parent, const BoundConstraint &constraint) { +void DataTable::VerifyNewConstraint(ClientContext &context, LocalStorage &local_storage, DataTable &parent, + const BoundConstraint &constraint) { if (constraint.type != ConstraintType::NOT_NULL) { throw NotImplementedException("FIXME: ALTER COLUMN with such constraint is not supported yet"); } - parent.row_groups->VerifyNewConstraint(local_storage.GetContext(), local_storage.GetTransaction(), parent, - constraint); - local_storage.VerifyNewConstraint(parent, constraint); + parent.row_groups->VerifyNewConstraint(context.GetContext(), local_storage.GetTransaction(), parent, constraint); + local_storage.VerifyNewConstraint(context.GetContext(), parent, constraint); } void DataTable::VerifyAppendConstraints(ConstraintState &constraint_state, ClientContext &context, DataChunk &chunk, @@ -899,7 +917,7 @@ void DataTable::InitializeLocalAppend(LocalAppendState &state, DuckTableEntry &t GetTableName(), TableModification()); } auto &local_storage = LocalStorage::Get(context, db); - local_storage.InitializeAppend(state, *this, table); + local_storage.InitializeAppend(context.GetContext(), state, *this, table); state.constraint_state = InitializeConstraintState(table, bound_constraints); } @@ -914,7 +932,7 @@ void DataTable::InitializeLocalStorage(LocalAppendState &state, DuckTableEntry & // The transaction-local indexes are created with the local storage, and only for indexes that are bound info->BindIndexes(context); auto &local_storage = LocalStorage::Get(context, db); - local_storage.InitializeStorage(state, *this, table); + local_storage.InitializeStorage(context.GetContext(), state, *this, table); state.constraint_state = InitializeConstraintState(table, bound_constraints); } @@ -956,28 +974,28 @@ void DataTable::FinalizeLocalAppend(LocalAppendState &state) { PhysicalIndex DataTable::CreateOptimisticCollection(ClientContext &context, unique_ptr collection) { auto &local_storage = LocalStorage::Get(context, db); - return local_storage.CreateOptimisticCollection(*this, std::move(collection)); + return local_storage.CreateOptimisticCollection(context.GetContext(), *this, std::move(collection)); } OptimisticWriteCollection &DataTable::GetOptimisticCollection(ClientContext &context, const PhysicalIndex collection_index) { auto &local_storage = LocalStorage::Get(context, db); - return local_storage.GetOptimisticCollection(*this, collection_index); + return local_storage.GetOptimisticCollection(context.GetContext(), *this, collection_index); } void DataTable::ResetOptimisticCollection(ClientContext &context, const PhysicalIndex collection_index) { auto &local_storage = LocalStorage::Get(context, db); - local_storage.ResetOptimisticCollection(*this, collection_index); + local_storage.ResetOptimisticCollection(context.GetContext(), *this, collection_index); } OptimisticDataWriter &DataTable::GetOptimisticWriter(ClientContext &context) { auto &local_storage = LocalStorage::Get(context, db); - return local_storage.GetOptimisticWriter(*this); + return local_storage.GetOptimisticWriter(context.GetContext(), *this); } void DataTable::LocalMerge(ClientContext &context, DuckTableEntry &table_entry, OptimisticWriteCollection &collection) { auto &local_storage = LocalStorage::Get(context, db); - local_storage.LocalMerge(*this, table_entry, collection); + local_storage.LocalMerge(context.GetContext(), *this, table_entry, collection); } void DataTable::LocalWALAppend(DuckTableEntry &table, ClientContext &context, DataChunk &chunk, @@ -1383,7 +1401,7 @@ idx_t DataTable::Delete(TableDeleteState &state, ClientContext &context, DuckTab fetch_state); VerifyDeleteConstraints(storage, state, context, state.verify_chunk); } - delete_count += local_storage.Delete(*this, table_entry, offset_ids, current_count); + delete_count += local_storage.Delete(context.GetContext(), *this, table_entry, offset_ids, current_count); continue; } @@ -1510,15 +1528,20 @@ void DataTable::Update(TableUpdateState &state, ClientContext &context, DuckTabl VerifyUpdateConstraints(*state.constraint_state, context, updates, column_ids); // now perform the actual update - Vector max_row_id_vec(Value::BIGINT(MAX_ROW_ID), count_t(count)); Vector row_ids_slice(LogicalType::BIGINT); DataChunk updates_slice; updates_slice.InitializeEmpty(updates.GetTypes()); SelectionVector sel_local_update(count), sel_global_update(count); - auto n_local_update = VectorOperations::GreaterThanEquals(row_ids, max_row_id_vec, nullptr, count, - &sel_local_update, &sel_global_update); - auto n_global_update = count - n_local_update; + idx_t n_local_update = 0; + idx_t n_global_update = 0; + for (auto row_id : row_ids.Values()) { + if (row_id.GetValue() >= MAX_ROW_ID) { + sel_local_update.set_index(n_local_update++, row_id.GetIndex()); + } else { + sel_global_update.set_index(n_global_update++, row_id.GetIndex()); + } + } // row id > MAX_ROW_ID? transaction-local storage if (n_local_update > 0) { @@ -1692,6 +1715,20 @@ idx_t DataTable::GetRowGroupCount() const { return row_groups->GetRowGroupCount(); } +idx_t DataTable::GetRowGroupCountWithoutLoading() const { + return row_groups->GetRowGroupCountWithoutLoading(); +} + +idx_t DataTable::GetRowGroupCountWithoutLoading(ClientContext &context) { + auto &local_storage = LocalStorage::Get(context, db); + auto storage = local_storage.GetStorage(*this); + if (!storage) { + return GetRowGroupCountWithoutLoading(); + } + // transaction-local row groups are in memory: counting them loads nothing + return GetRowGroupCountWithoutLoading() + storage->GetCollection().GetRowGroupCount(); +} + idx_t DataTable::GetRowGroupCountWithLocalStorage(ClientContext &context) { auto &local_storage = LocalStorage::Get(context, db); auto storage = local_storage.GetStorage(*this); diff --git a/src/duckdb/src/storage/database_handle.cpp b/src/duckdb/src/storage/database_handle.cpp index dc5127b4d..3c69c3ab1 100644 --- a/src/duckdb/src/storage/database_handle.cpp +++ b/src/duckdb/src/storage/database_handle.cpp @@ -127,7 +127,9 @@ void DatabaseHandle::Read(QueryContext context, FileBuffer &block, uint64_t loca return; } // Serve fully-covered reads from the prefetched header (only the first few header reads qualify). - if (prefetched_header && location + block.AllocSize() <= prefetched_header->size()) { + // (the location is derived from a block id, so compare without adding to it: the sum can wrap) + if (prefetched_header && location <= prefetched_header->size() && + block.AllocSize() <= prefetched_header->size() - location) { block.ReadFromMemory(const_data_ptr_cast(prefetched_header->data()), location); return; } diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp index 597dd4e0c..017ccbc50 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp @@ -158,6 +158,10 @@ class FetchBlockTask : public BaseExecutorTask { } } + string TaskType() const override { + return "FetchBlockTask"; + } + private: CachingFileHandle &caching_file_handle; QueryContext context; @@ -182,6 +186,10 @@ class ReadRangeTask : public BaseExecutorTask { caching_file_handle.ReadAndRecord(context, buffer, nr_bytes, location); } + string TaskType() const override { + return "ReadRangeTask"; + } + private: CachingFileHandle &caching_file_handle; QueryContext context; @@ -209,12 +217,16 @@ CachingFileSystem CachingFileSystem::Get(ClientContext &context) { unique_ptr CachingFileSystem::OpenFile(const OpenFileInfo &path, const FileOpenFlags &flags, optional_ptr opener) { - return make_uniq(QueryContext(), *this, path, flags, opener); + return OpenFile(QueryContext(), path, flags, opener); } unique_ptr CachingFileSystem::OpenFile(QueryContext context, const OpenFileInfo &path, const FileOpenFlags &flags, optional_ptr opener) { - return make_uniq(context, *this, path, flags, opener); + auto handle = unique_ptr(new CachingFileHandle(context, *this, path, flags, opener)); + if (!handle->Initialize()) { + return nullptr; + } + return handle; } //===----------------------------------------------------------------------===// @@ -311,12 +323,13 @@ CachingFileHandle::CachingFileHandle(QueryContext context, CachingFileSystem &ca external_file_cache(caching_file_system_p.external_file_cache), path(path_p), flags(std::move(flags_p)), opener(opener_p), validate(ExternalFileCacheUtil::GetCacheValidationMode(path_p, context.GetContext(), caching_file_system_p.db)), - cached_file(nullptr), position(0) { - cached_file = external_file_cache.GetOrCreateCachedFile(path_p.path); + cached_file(external_file_cache.GetOrCreateCachedFile(path_p.path)), position(0) { +} + +bool CachingFileHandle::Initialize() { if (!external_file_cache.IsEnabled() || Validate()) { // If caching is disabled, or if we must validate cache entries, we always have to open the file - GetFileHandle(); - return; + return TryGetFileHandle() != nullptr; } // If we don't have any cached blocks, we must also open the file. bool needs_open = false; @@ -324,19 +337,28 @@ CachingFileHandle::CachingFileHandle(QueryContext context, CachingFileSystem &ca annotated_lock_guard guard(cached_file->map_lock); needs_open = cached_file->blocks.empty(); } - if (needs_open) { - GetFileHandle(); + if (needs_open && !TryGetFileHandle()) { + return false; } auto needs_full_download = StripForceFullDownloadIfPresent(); if (needs_full_download) { Read(GetFileSize(), 0); } + return true; } CachingFileHandle::~CachingFileHandle() { } shared_ptr CachingFileHandle::GetFileHandle() { + auto handle = TryGetFileHandle(); + if (!handle) { + throw IOException("Cannot open file \"%s\": file does not exist", path.path); + } + return handle; +} + +shared_ptr CachingFileHandle::TryGetFileHandle() { annotated_lock_guard guard(file_handle_mutex); if (file_handle) { return file_handle; @@ -347,6 +369,9 @@ shared_ptr CachingFileHandle::GetFileHandle() { // require explicit opt-in for concurrent pread-style access (e.g., HTTPFS). auto internal_flags = flags | FileFlags::FILE_FLAGS_PARALLEL_ACCESS; file_handle = file_system.OpenFile(path, internal_flags, opener); + if (!file_handle) { + return nullptr; + } // Snapshot the metadata with a single Stats call, avoiding repeated metadata lookups (e.g., fstat) validation_info = GetValidationInfo(file_system, *file_handle); diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp index b5df812f0..8be55c0db 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp @@ -139,6 +139,9 @@ unique_ptr CachingFileSystemWrapper::OpenFileExtended(const OpenFile if (ShouldUseCache(path.path)) { auto caching_handle = caching_file_system.OpenFile(path, flags, opener); + if (!caching_handle) { + return nullptr; + } return make_uniq(shared_from_this(), std::move(caching_handle), flags); } // Bypass cache, use underlying file system directly. diff --git a/src/duckdb/src/storage/index_entry.cpp b/src/duckdb/src/storage/index_entry.cpp index 487f27f96..509ccf301 100644 --- a/src/duckdb/src/storage/index_entry.cpp +++ b/src/duckdb/src/storage/index_entry.cpp @@ -524,7 +524,7 @@ IndexCheckpointResult IndexEntry::Checkpoint(TableIndexWriter &index_writer) { auto partial_block_manager = index_writer.CreatePerIndexPartialBlockManager(); auto checkpoint = owned_index->Checkpoint(partial_block_manager, storage_version); - partial_block_manager.FlushPartialBlocks(); + partial_block_manager.FlushPartialBlocks(index_writer.GetContext()); InstallShadowInternal(std::move(checkpoint.shadow_index)); return checkpoint; diff --git a/src/duckdb/src/storage/local_storage.cpp b/src/duckdb/src/storage/local_storage.cpp index 46cb248c8..815d583c9 100644 --- a/src/duckdb/src/storage/local_storage.cpp +++ b/src/duckdb/src/storage/local_storage.cpp @@ -22,11 +22,10 @@ namespace duckdb { LocalTableStorage::LocalTableStorage(Context &context, DataTable &table) - : context(context), table_ref(table), allocator(Allocator::Get(table.db)), deleted_rows(0), - optimistic_writer(context, table) { + : table_ref(table), allocator(Allocator::Get(table.db)), deleted_rows(0), optimistic_writer(table) { auto types = table.GetTypes(); auto data_table_info = table.GetDataTableInfo(); - row_groups = optimistic_writer.CreateCollection(table, types, OptimisticWritePartialManagers::GLOBAL); + row_groups = optimistic_writer.CreateCollection(context, table, types, OptimisticWritePartialManagers::GLOBAL); auto &collection = *row_groups->collection; collection.InitializeEmpty(); @@ -38,8 +37,8 @@ LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_data const idx_t alter_column_index, const LogicalType &target_type, const vector &bound_columns, Expression &cast_expr, TransactionData transaction) - : context(parent.context), table_ref(new_data_table), allocator(Allocator::Get(new_data_table.db)), - deleted_rows(parent.deleted_rows.load()), optimistic_collections(std::move(parent.optimistic_collections)), + : table_ref(new_data_table), allocator(Allocator::Get(new_data_table.db)), deleted_rows(parent.deleted_rows.load()), + optimistic_collections(std::move(parent.optimistic_collections)), optimistic_writer(new_data_table, parent.optimistic_writer) { // Alter the column type. auto &parent_collection = *parent.row_groups->collection; @@ -56,8 +55,8 @@ LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_data LocalTableStorage::LocalTableStorage(DataTable &new_data_table, LocalTableStorage &parent, const idx_t drop_column_index) - : context(parent.context), table_ref(new_data_table), allocator(Allocator::Get(new_data_table.db)), - deleted_rows(parent.deleted_rows.load()), optimistic_collections(std::move(parent.optimistic_collections)), + : table_ref(new_data_table), allocator(Allocator::Get(new_data_table.db)), deleted_rows(parent.deleted_rows.load()), + optimistic_collections(std::move(parent.optimistic_collections)), optimistic_writer(new_data_table, parent.optimistic_writer) { // Remove the column from the previous table storage. auto &parent_collection = *parent.row_groups->collection; @@ -73,8 +72,8 @@ LocalTableStorage::LocalTableStorage(DataTable &new_data_table, LocalTableStorag LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_dt, LocalTableStorage &parent, ColumnDefinition &new_column, ExpressionExecutor &default_executor) - : context(parent.context), table_ref(new_dt), allocator(Allocator::Get(new_dt.db)), - deleted_rows(parent.deleted_rows.load()), optimistic_collections(std::move(parent.optimistic_collections)), + : table_ref(new_dt), allocator(Allocator::Get(new_dt.db)), deleted_rows(parent.deleted_rows.load()), + optimistic_collections(std::move(parent.optimistic_collections)), optimistic_writer(new_dt, parent.optimistic_writer) { auto &parent_collection = *parent.row_groups->collection; auto new_collection = parent_collection.AddColumn(context, new_column, default_executor); @@ -126,22 +125,22 @@ idx_t LocalTableStorage::EstimatedSize() const { return data_size + append_indexes.GetInMemorySize(); } -void LocalTableStorage::WriteNewRowGroup(idx_t flushed_row_group_idx) { +void LocalTableStorage::WriteNewRowGroup(Context &context, idx_t flushed_row_group_idx) { if (deleted_rows != 0) { // we have deletes - we cannot merge row groups return; } - optimistic_writer.WriteNewRowGroup(*row_groups, flushed_row_group_idx); + optimistic_writer.WriteNewRowGroup(context, *row_groups, flushed_row_group_idx); } -void LocalTableStorage::FlushBlocks() { +void LocalTableStorage::FlushBlocks(Context &context) { auto &collection = *row_groups->collection; const idx_t row_group_size = collection.GetRowGroupSize(); if (collection.GetTotalRows() >= row_group_size) { // write any unflushed row groups - optimistic_writer.WriteUnflushedRowGroups(*row_groups); + optimistic_writer.WriteUnflushedRowGroups(context, *row_groups); } - optimistic_writer.FinalFlush(); + optimistic_writer.FinalFlush(context); } bool LocalTableStorage::WritesToDisk() const { @@ -386,8 +385,7 @@ void LocalTableManager::InsertEntry(DataTable &table, shared_ptrGetCollection().NextParallelScan(context, state, scan_state, initialize_columns); } -void LocalStorage::InitializeAppend(LocalAppendState &state, DataTable &table, DuckTableEntry &table_entry) { +void LocalStorage::InitializeAppend(Context &context, LocalAppendState &state, DataTable &table, + DuckTableEntry &table_entry) { + state.context = &context; state.storage = &table_manager.GetOrCreateStorage(context, table); state.storage->table_entry = &table_entry; state.storage->GetCollection().InitializeAppend(TransactionData(transaction), state.append_state); } -void LocalStorage::InitializeStorage(LocalAppendState &state, DataTable &table, DuckTableEntry &table_entry) { +void LocalStorage::InitializeStorage(Context &context, LocalAppendState &state, DataTable &table, + DuckTableEntry &table_entry) { + state.context = &context; state.storage = &table_manager.GetOrCreateStorage(context, table); state.storage->table_entry = &table_entry; } @@ -512,7 +514,7 @@ void LocalStorage::Append(LocalAppendState &state, DuckTableEntry &table_entry, // Check if we should pre-emptively flush blocks to disk. if (flushed_row_group_idx.IsValid()) { - storage->WriteNewRowGroup(flushed_row_group_idx.GetIndex()); + storage->WriteNewRowGroup(*state.context, flushed_row_group_idx.GetIndex()); } } @@ -520,7 +522,8 @@ void LocalStorage::FinalizeAppend(LocalAppendState &state) { state.storage->GetCollection().FinalizeAppend(state.append_state.transaction, state.append_state); } -void LocalStorage::LocalMerge(DataTable &table, DuckTableEntry &table_entry, OptimisticWriteCollection &collection) { +void LocalStorage::LocalMerge(Context &context, DataTable &table, DuckTableEntry &table_entry, + OptimisticWriteCollection &collection) { auto &storage = table_manager.GetOrCreateStorage(context, table); storage.table_entry = &table_entry; if (!storage.append_indexes.Empty()) { @@ -536,24 +539,24 @@ void LocalStorage::LocalMerge(DataTable &table, DuckTableEntry &table_entry, Opt target.MergeStorage(collection); } -PhysicalIndex LocalStorage::CreateOptimisticCollection(DataTable &table, +PhysicalIndex LocalStorage::CreateOptimisticCollection(Context &context, DataTable &table, unique_ptr collection) { auto &storage = table_manager.GetOrCreateStorage(context, table); return storage.CreateOptimisticCollection(std::move(collection)); } -OptimisticWriteCollection &LocalStorage::GetOptimisticCollection(DataTable &table, +OptimisticWriteCollection &LocalStorage::GetOptimisticCollection(Context &context, DataTable &table, const PhysicalIndex collection_index) { auto &storage = table_manager.GetOrCreateStorage(context, table); return storage.GetOptimisticCollection(collection_index); } -void LocalStorage::ResetOptimisticCollection(DataTable &table, const PhysicalIndex collection_index) { +void LocalStorage::ResetOptimisticCollection(Context &context, DataTable &table, const PhysicalIndex collection_index) { auto &storage = table_manager.GetOrCreateStorage(context, table); storage.ResetOptimisticCollection(collection_index); } -OptimisticDataWriter &LocalStorage::GetOptimisticWriter(DataTable &table) { +OptimisticDataWriter &LocalStorage::GetOptimisticWriter(Context &context, DataTable &table) { auto &storage = table_manager.GetOrCreateStorage(context, table); return storage.GetOptimisticWriter(); } @@ -570,7 +573,8 @@ idx_t LocalStorage::EstimatedSize() { return table_manager.EstimatedSize(); } -idx_t LocalStorage::Delete(DataTable &table, DuckTableEntry &table_entry, Vector &row_ids, idx_t count) { +idx_t LocalStorage::Delete(Context &context, DataTable &table, DuckTableEntry &table_entry, Vector &row_ids, + idx_t count) { auto storage = table_manager.GetStorage(table); D_ASSERT(storage); @@ -617,7 +621,8 @@ void LocalStorage::Update(DataTable &table, DuckTableEntry &table_entry, Vector storage->GetCollection().Update(TransactionData::Unversioned(), table_entry, ids, column_ids, updates); } -void LocalStorage::Flush(DataTable &table, LocalTableStorage &storage, optional_ptr commit_state) { +void LocalStorage::Flush(Context &context, DataTable &table, LocalTableStorage &storage, + optional_ptr commit_state) { if (storage.is_dropped) { storage.Rollback(); return; @@ -644,7 +649,7 @@ void LocalStorage::Flush(DataTable &table, LocalTableStorage &storage, optional_ // there are no optimistically written blocks to manage, and merging avoids re-appending // row by row. // first flush any outstanding blocks - storage.FlushBlocks(); + storage.FlushBlocks(context); // Append to the indexes. error = storage.AppendToIndexes(transaction, append_state); if (!error.HasError()) { @@ -690,12 +695,12 @@ void LocalStorage::Flush(DataTable &table, LocalTableStorage &storage, optional_ #endif } -void LocalStorage::FlushBulkAppendBlocksAndSync(AttachedDatabase &db) { +void LocalStorage::FlushBulkAppendBlocksAndSync(Context &context, AttachedDatabase &db) { bool requires_sync = false; for (auto &storage : table_manager.GetEntries()) { if (storage->IsBulkAppend()) { // Flush() is guaranteed to take the bulk path - the blocks will be used as written - storage->FlushBlocks(); + storage->FlushBlocks(context); requires_sync |= storage->HasFlushedRowGroups(); } } @@ -708,7 +713,7 @@ void LocalStorage::FlushBulkAppendBlocksAndSync(AttachedDatabase &db) { } } -void LocalStorage::Commit(optional_ptr commit_state) { +void LocalStorage::Commit(Context &context, optional_ptr commit_state) { // commit local storage // iterate over all entries in the table storage map and commit them // after this, the local storage is no longer required and can be cleared @@ -716,7 +721,7 @@ void LocalStorage::Commit(optional_ptr commit_state) { for (auto &entry : table_storage) { auto storage = entry.second.get(); D_ASSERT(RefersToSameObject(entry.first, storage->table_ref)); - Flush(storage->table_ref, *storage, commit_state); + Flush(context, storage->table_ref, *storage, commit_state); entry.second.reset(); } } @@ -821,7 +826,7 @@ bool LocalStorage::CanFetch(DataTable &table, const row_t row_id) { return storage->GetCollection().CanFetch(transaction, row_id); } -TableIndexList &LocalStorage::GetIndexes(DataTable &table) { +TableIndexList &LocalStorage::GetIndexes(Context &context, DataTable &table) { auto &storage = table_manager.GetOrCreateStorage(context, table); return storage.append_indexes; } @@ -830,7 +835,7 @@ optional_ptr LocalStorage::GetStorage(const DataTable &table) return table_manager.GetStorage(table); } -void LocalStorage::VerifyNewConstraint(DataTable &parent, const BoundConstraint &constraint) { +void LocalStorage::VerifyNewConstraint(Context &context, DataTable &parent, const BoundConstraint &constraint) { auto storage = table_manager.GetStorage(parent); if (!storage) { return; diff --git a/src/duckdb/src/storage/metadata/metadata_manager.cpp b/src/duckdb/src/storage/metadata/metadata_manager.cpp index 2e5128f6a..ac6ca4efe 100644 --- a/src/duckdb/src/storage/metadata/metadata_manager.cpp +++ b/src/duckdb/src/storage/metadata/metadata_manager.cpp @@ -338,6 +338,9 @@ void MetadataManager::Read(ReadStream &source) { auto block_count = source.Read(); for (idx_t i = 0; i < block_count; i++) { auto block = MetadataBlock::Read(source); + if (block.block_id < 0 || block.block_id >= MAXIMUM_BLOCK) { + throw DataCorruptionException("Corrupt database file: invalid metadata block id %lld", block.block_id); + } unique_lock guard(block_lock); auto entry = blocks.find(block.block_id); diff --git a/src/duckdb/src/storage/metadata/metadata_reader.cpp b/src/duckdb/src/storage/metadata/metadata_reader.cpp index e4a26cc4d..be0b771b3 100644 --- a/src/duckdb/src/storage/metadata/metadata_reader.cpp +++ b/src/duckdb/src/storage/metadata/metadata_reader.cpp @@ -7,7 +7,8 @@ namespace duckdb { MetadataReader::MetadataReader(MetadataManager &manager, MetaBlockPointer pointer, optional_ptr> read_pointers_p, BlockReaderType type) : manager(manager), type(type), next_pointer(pointer), has_next_block(true), read_pointers(read_pointers_p), - index(0), offset(0), next_offset(pointer.offset), capacity(0) { + index(0), offset(0), next_offset(pointer.offset), capacity(0), cycle_check_pointer(DConstants::INVALID_INDEX), + cycle_check_at(1), blocks_read(0) { } MetadataReader::MetadataReader(MetadataManager &manager, BlockPointer pointer) @@ -63,6 +64,7 @@ void MetadataReader::ReadNextBlock(QueryContext context) { if (!has_next_block) { throw IOException("No more data remaining in MetadataReader"); } + CheckForCycle(); if (read_pointers) { read_pointers->push_back(next_pointer); } @@ -87,6 +89,21 @@ void MetadataReader::ReadNextBlock(QueryContext context) { capacity = GetMetadataManager().GetMetadataBlockSize(); } +void MetadataReader::CheckForCycle() { + // the pointers to the next block are read from the file - a chain that points back into itself never ends + // we use Brent's algorithm to detect this: remember the block read at every power of two and compare against it + if (next_pointer.block_pointer == cycle_check_pointer) { + throw DataCorruptionException( + "Corrupt database file: metadata block chain contains a cycle (block id %lld, index %llu)", + next_pointer.GetBlockId(), next_pointer.GetBlockIndex()); + } + blocks_read++; + if (blocks_read == cycle_check_at) { + cycle_check_pointer = next_pointer.block_pointer; + cycle_check_at *= 2; + } +} + data_ptr_t MetadataReader::BasePtr() { return block.handle.GetDataMutable() + index * GetMetadataManager().GetMetadataBlockSize(); } diff --git a/src/duckdb/src/storage/object_cache.cpp b/src/duckdb/src/storage/object_cache.cpp index d5a27cc6d..867d4b101 100644 --- a/src/duckdb/src/storage/object_cache.cpp +++ b/src/duckdb/src/storage/object_cache.cpp @@ -10,6 +10,63 @@ ObjectCache &ObjectCache::GetObjectCache(ClientContext &context) { return context.db->GetObjectCache(); } +shared_ptr +ObjectCache::GetOrCreateObject(const string &key, const std::function()> &create) { + while (true) { + auto existing = GetObject(key); + if (existing) { + return existing; + } + shared_ptr creation; + bool is_creator = false; + { + const lock_guard guard(in_flight_lock); + auto &slot = in_flight_creations[key]; + if (!slot) { + slot = make_shared_ptr(); + is_creator = true; + } + creation = slot; + } + if (!is_creator) { + unique_lock guard(creation->lock); + creation->finished_cv.wait(guard, [&]() { return creation->finished; }); + // look up again: the creator may have failed, or the entry may already be gone + continue; + } + struct FinishOnExit { + ObjectCache &cache; + const string &key; + InFlightCreation &creation; + ~FinishOnExit() { + cache.FinishCreation(key, creation); + } + } finish_on_exit {*this, key, *creation}; + // a creation that finished between the lookup above and our registration + existing = GetObject(key); + if (existing) { + return existing; + } + auto created = create(); + if (!created) { + return nullptr; + } + return GetOrPut(key, std::move(created)); + } +} + +void ObjectCache::FinishCreation(const string &key, InFlightCreation &creation) { + { + const lock_guard guard(in_flight_lock); + in_flight_creations.erase(key); + } + { + const lock_guard guard(creation.lock); + creation.finished = true; + } + creation.finished_cv.notify_all(); +} + bool ObjectCache::EvictToMemoryLimit(idx_t memory_limit) { constexpr idx_t EVICTION_BATCH_SIZE = 16; while (true) { diff --git a/src/duckdb/src/storage/optimistic_data_writer.cpp b/src/duckdb/src/storage/optimistic_data_writer.cpp index 77464a9b8..9be3bb09f 100644 --- a/src/duckdb/src/storage/optimistic_data_writer.cpp +++ b/src/duckdb/src/storage/optimistic_data_writer.cpp @@ -14,15 +14,10 @@ namespace duckdb { OptimisticWriteCollection::~OptimisticWriteCollection() { } -OptimisticDataWriter::OptimisticDataWriter(ClientContext &context, DataTable &table) - : OptimisticDataWriter(context.GetContext(), table) { +OptimisticDataWriter::OptimisticDataWriter(DataTable &table) : table(table) { } -OptimisticDataWriter::OptimisticDataWriter(Context &context, DataTable &table) : context(context), table(table) { -} - -OptimisticDataWriter::OptimisticDataWriter(DataTable &table, OptimisticDataWriter &parent) - : context(parent.GetContext()), table(table) { +OptimisticDataWriter::OptimisticDataWriter(DataTable &table, OptimisticDataWriter &parent) : table(table) { if (parent.partial_manager) { parent.partial_manager->ClearBlocks(); } @@ -37,7 +32,7 @@ bool OptimisticDataWriter::CanWriteToDisk() const { return !table.IsTemporary() && !storage_manager.InMemory() && !attached.IsReadOnly(); } -bool OptimisticDataWriter::PrepareWrite() { +bool OptimisticDataWriter::PrepareWrite(Context &context) { // check if optimistic writing is enabled if (!Settings::Get(context)) { return false; @@ -50,12 +45,12 @@ bool OptimisticDataWriter::PrepareWrite() { // allocate the partial block-manager if none is allocated yet if (!partial_manager) { auto &block_manager = table.GetTableIOManager().GetBlockManagerForRowData(); - partial_manager = make_uniq(context, block_manager, PartialBlockType::APPEND_TO_TABLE); + partial_manager = make_uniq(block_manager, PartialBlockType::APPEND_TO_TABLE); } return true; } -unique_ptr OptimisticDataWriter::CreateCollection(DataTable &storage, +unique_ptr OptimisticDataWriter::CreateCollection(Context &context, DataTable &storage, const vector &insert_types, OptimisticWritePartialManagers type) { auto table_info = storage.GetDataTableInfo(); @@ -71,15 +66,16 @@ unique_ptr OptimisticDataWriter::CreateCollection(Dat for (idx_t i = 0; i < insert_types.size(); i++) { auto &block_manager = table.GetTableIOManager().GetBlockManagerForRowData(); result->partial_block_managers.push_back( - make_uniq(context, block_manager, PartialBlockType::APPEND_TO_TABLE)); + make_uniq(block_manager, PartialBlockType::APPEND_TO_TABLE)); } } return result; } -void OptimisticDataWriter::WriteNewRowGroup(OptimisticWriteCollection &row_groups, idx_t flushed_row_group_idx) { +void OptimisticDataWriter::WriteNewRowGroup(Context &context, OptimisticWriteCollection &row_groups, + idx_t flushed_row_group_idx) { // we finished writing a complete row group - if (!PrepareWrite()) { + if (!PrepareWrite(context)) { return; } @@ -113,7 +109,7 @@ void OptimisticDataWriter::WriteNewRowGroup(OptimisticWriteCollection &row_group to_flush.push_back(*row_groups.collection->GetRowGroup(segment_index)); segment_indexes.push_back(segment_index); } - FlushToDisk(row_groups, to_flush, segment_indexes); + FlushToDisk(context, row_groups, to_flush, segment_indexes); row_groups.FinalizeFlush(); } } @@ -131,14 +127,14 @@ void OptimisticWriteCollection::ResetCollectionAccounting() { flushed_row_groups.clear(); } -void OptimisticDataWriter::WriteUnflushedRowGroups(OptimisticWriteCollection &row_groups) { +void OptimisticDataWriter::WriteUnflushedRowGroups(Context &context, OptimisticWriteCollection &row_groups) { auto total_row_groups = row_groups.collection->GetRowGroupCount(); if (row_groups.flushed_row_groups.size() == total_row_groups && row_groups.partial_block_managers.empty()) { // everything is flushed already and there is nothing to merge - a repeated call ends up here return; } // we finished writing a complete row group - if (!PrepareWrite()) { + if (!PrepareWrite(context)) { return; } // add any incomplete row groups to the set of unflushed row groups @@ -159,11 +155,11 @@ void OptimisticDataWriter::WriteUnflushedRowGroups(OptimisticWriteCollection &ro segment_indexes.push_back(segment_index); } - FlushToDisk(row_groups, to_flush, segment_indexes); + FlushToDisk(context, row_groups, to_flush, segment_indexes); } for (auto &partial_manager : row_groups.partial_block_managers) { - Merge(partial_manager); + Merge(context, partial_manager); } row_groups.FinalizeFlush(); row_groups.partial_block_managers.clear(); @@ -191,7 +187,7 @@ void OptimisticWriteCollection::MergeStorage(OptimisticWriteCollection &merge_co collection->MergeStorage(merge_row_groups, nullptr, nullptr); } -void OptimisticDataWriter::FlushToDisk(OptimisticWriteCollection &collection, +void OptimisticDataWriter::FlushToDisk(Context &context, OptimisticWriteCollection &collection, const vector> &row_groups, const vector &segment_indexes) { //! The set of column compression types (if any) @@ -200,7 +196,7 @@ void OptimisticDataWriter::FlushToDisk(OptimisticWriteCollection &collection, for (auto &column : table.Columns()) { compression_types.push_back(column.CompressionType()); } - RowGroupWriteInfo info(*partial_manager, compression_types, collection.partial_block_managers); + RowGroupWriteInfo info(context, *partial_manager, compression_types, collection.partial_block_managers); auto result = RowGroup::WriteToDisk(info, row_groups); // move new (checkpointed) row groups to the row group collection for (idx_t i = 0; i < row_groups.size(); i++) { @@ -208,7 +204,7 @@ void OptimisticDataWriter::FlushToDisk(OptimisticWriteCollection &collection, } } -void OptimisticDataWriter::Merge(unique_ptr &other_manager) { +void OptimisticDataWriter::Merge(Context &context, unique_ptr &other_manager) { if (!other_manager) { return; } @@ -216,17 +212,17 @@ void OptimisticDataWriter::Merge(unique_ptr &other_manager) partial_manager = std::move(other_manager); return; } - partial_manager->Merge(*other_manager); + partial_manager->Merge(context, *other_manager); other_manager.reset(); } -void OptimisticDataWriter::Merge(OptimisticDataWriter &other) { - Merge(other.partial_manager); +void OptimisticDataWriter::Merge(Context &context, OptimisticDataWriter &other) { + Merge(context, other.partial_manager); } -void OptimisticDataWriter::FinalFlush() { +void OptimisticDataWriter::FinalFlush(Context &context) { if (partial_manager) { - partial_manager->FlushPartialBlocks(); + partial_manager->FlushPartialBlocks(context); partial_manager.reset(); } } diff --git a/src/duckdb/src/storage/partial_block_manager.cpp b/src/duckdb/src/storage/partial_block_manager.cpp index 4699acebd..7125a6891 100644 --- a/src/duckdb/src/storage/partial_block_manager.cpp +++ b/src/duckdb/src/storage/partial_block_manager.cpp @@ -242,11 +242,9 @@ void PartialBlock::Clear() { // PartialBlockManager //===--------------------------------------------------------------------===// -PartialBlockManager::PartialBlockManager(Context &context_p, BlockManager &block_manager, - PartialBlockType partial_block_type, optional_idx max_partial_block_size_p, - uint32_t max_use_count) - : context(context_p), block_manager(block_manager), partial_block_type(partial_block_type), - max_use_count(max_use_count) { +PartialBlockManager::PartialBlockManager(BlockManager &block_manager, PartialBlockType partial_block_type, + optional_idx max_partial_block_size_p, uint32_t max_use_count) + : block_manager(block_manager), partial_block_type(partial_block_type), max_use_count(max_use_count) { if (max_partial_block_size_p.IsValid()) { max_partial_block_size = NumericCast(max_partial_block_size_p.GetIndex()); } else { @@ -266,7 +264,7 @@ block_id_t PartialBlockManager::GetFreeBlockId() { } } -void PartialBlockManager::Merge(PartialBlockManager &other) { +void PartialBlockManager::Merge(Context &context, PartialBlockManager &other) { if (&other == this) { throw InternalException("Cannot merge into itself"); } @@ -281,16 +279,16 @@ void PartialBlockManager::Merge(PartialBlockManager &other) { auto used_space = NumericCast(block_manager.GetBlockSize() - other_offset); if (used_space > max_partial_block_size) { - RetainOrFlush(std::move(other_block)); + RetainOrFlush(context, std::move(other_block)); continue; } if (auto partial_block = TakePartialBlock(used_space)) { partial_block->Merge(*other_block); - RetainOrFlush(std::move(partial_block)); + RetainOrFlush(context, std::move(partial_block)); continue; } - RetainOrFlush(std::move(other_block)); + RetainOrFlush(context, std::move(other_block)); } other.partially_filled_blocks.clear(); @@ -300,9 +298,9 @@ void PartialBlockManager::ClearBlocks() { partially_filled_blocks.clear(); } -void PartialBlockManager::FlushPartialBlocks() { +void PartialBlockManager::FlushPartialBlocks(Context &context) { for (auto &e : partially_filled_blocks) { - e.second->Flush(GetQueryContext(), partial_block_type); + e.second->Flush(QueryContext(context), partial_block_type); } partially_filled_blocks.clear(); } @@ -360,33 +358,38 @@ unique_ptr PartialBlockManager::PruneFreeList() { return block; } -void PartialBlockManager::RetainOrFlush(unique_ptr partial_block) { +static QueryContext ToQueryContext(optional_ptr context) { + return context ? QueryContext(*context) : QueryContext(); +} + +void PartialBlockManager::RetainOrFlush(optional_ptr context, unique_ptr partial_block) { auto min_reusable_space = block_manager.GetBlockSize() - max_partial_block_size; auto available_space = partial_block->AvailableSpace(); if (partial_block->UseCount() >= max_use_count) { - partial_block->Flush(GetQueryContext(), partial_block_type); + partial_block->Flush(ToQueryContext(context), partial_block_type); return; } if (available_space < min_reusable_space) { - partial_block->Flush(GetQueryContext(), partial_block_type); + partial_block->Flush(ToQueryContext(context), partial_block_type); return; } partially_filled_blocks.insert(make_pair(partial_block->AvailableSpace(), std::move(partial_block))); if (auto pruned_block = PruneFreeList()) { - pruned_block->Flush(GetQueryContext(), partial_block_type); + pruned_block->Flush(ToQueryContext(context), partial_block_type); } } -optional PartialBlockManager::Write(BlockPackable &packable, BufferHandle &&source, uint32_t byte_size) { +optional PartialBlockManager::Write(Context &context, BlockPackable &packable, BufferHandle &&source, + uint32_t byte_size) { BufferHandle owned_source(std::move(source)); unique_lock lock(partial_block_lock); auto block = AcquirePartialBlock(byte_size); BlockPointer block_ptr = block->Store(packable, std::move(owned_source), byte_size); - RetainOrFlush(std::move(block)); + RetainOrFlush(context, std::move(block)); if (partial_block_type == PartialBlockType::FULL_CHECKPOINT) { D_ASSERT(block_ptr.IsValid()); @@ -396,13 +399,23 @@ optional PartialBlockManager::Write(BlockPackable &packable, Buffe return nullopt; } +optional PartialBlockManager::Write(Context &context, BlockPackable &packable, const BufferHandle &source, + uint32_t byte_size) { + return WriteCopy(context, packable, source, byte_size); +} + optional PartialBlockManager::Write(BlockPackable &packable, const BufferHandle &source, uint32_t byte_size) { + return WriteCopy(nullptr, packable, source, byte_size); +} + +optional PartialBlockManager::WriteCopy(optional_ptr context, BlockPackable &packable, + const BufferHandle &source, uint32_t byte_size) { unique_lock lock(partial_block_lock); auto block = AcquirePartialBlock(byte_size); BlockPointer block_ptr = block->Store(packable, source, byte_size); - RetainOrFlush(std::move(block)); + RetainOrFlush(context, std::move(block)); if (partial_block_type == PartialBlockType::FULL_CHECKPOINT) { D_ASSERT(block_ptr.IsValid()); @@ -416,8 +429,4 @@ BlockManager &PartialBlockManager::GetBlockManager() const { return block_manager; } -QueryContext PartialBlockManager::GetQueryContext() const { - return QueryContext(context); -} - } // namespace duckdb diff --git a/src/duckdb/src/storage/serialization/serialize_expression.cpp b/src/duckdb/src/storage/serialization/serialize_expression.cpp index a9cd9d476..4967a7f36 100644 --- a/src/duckdb/src/storage/serialization/serialize_expression.cpp +++ b/src/duckdb/src/storage/serialization/serialize_expression.cpp @@ -261,7 +261,7 @@ unique_ptr LegacyBoundBetweenExpression::Deserialize(Deserializer &d auto upper = deserializer.ReadPropertyWithDefault>(202, "upper"); auto lower_inclusive = deserializer.ReadPropertyWithDefault(203, "lower_inclusive"); auto upper_inclusive = deserializer.ReadPropertyWithDefault(204, "upper_inclusive"); - auto result = LegacyBoundBetweenExpression::DeserializeLegacyExpression(std::move(input), std::move(lower), std::move(upper), lower_inclusive, upper_inclusive); + auto result = LegacyBoundBetweenExpression::DeserializeLegacyExpression(deserializer.Get(), std::move(input), std::move(lower), std::move(upper), lower_inclusive, upper_inclusive); return result; } diff --git a/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp b/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp index d72b3e25b..083549e64 100644 --- a/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp +++ b/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp @@ -893,6 +893,8 @@ void LogicalSetOperation::Serialize(Serializer &serializer) const { serializer.WritePropertyWithDefault(201, "column_count", column_count); serializer.WritePropertyWithDefault(202, "setop_all", setop_all, true); serializer.WritePropertyWithDefault(203, "allow_out_of_order", allow_out_of_order, true); + serializer.WritePropertyWithDefault>(204, "comparison_types", comparison_types); + serializer.WritePropertyWithDefault(205, "correlated_column_count", correlated_column_count, 0); } unique_ptr LogicalSetOperation::Deserialize(Deserializer &deserializer) { @@ -901,6 +903,8 @@ unique_ptr LogicalSetOperation::Deserialize(Deserializer &deser auto setop_all = deserializer.ReadPropertyWithExplicitDefault(202, "setop_all", true); auto allow_out_of_order = deserializer.ReadPropertyWithExplicitDefault(203, "allow_out_of_order", true); auto result = duckdb::unique_ptr(new LogicalSetOperation(table_index, column_count, deserializer.Get(), setop_all, allow_out_of_order)); + deserializer.ReadPropertyWithDefault>(204, "comparison_types", result->comparison_types); + deserializer.ReadPropertyWithExplicitDefault(205, "correlated_column_count", result->correlated_column_count, 0); return std::move(result); } @@ -976,12 +980,15 @@ void LogicalWindow::Serialize(Serializer &serializer) const { LogicalOperator::Serialize(serializer); serializer.WritePropertyWithDefault(200, "window_index", window_index); serializer.WritePropertyWithDefault>>(201, "expressions", expressions); + serializer.WritePropertyWithDefault(202, "partition_limit", partition_limit, optional_idx()); } unique_ptr LogicalWindow::Deserialize(Deserializer &deserializer) { auto window_index = deserializer.ReadPropertyWithDefault(200, "window_index"); - auto result = duckdb::unique_ptr(new LogicalWindow(window_index)); - deserializer.ReadPropertyWithDefault>>(201, "expressions", result->expressions); + auto expressions = deserializer.ReadPropertyWithDefault>>(201, "expressions"); + auto partition_limit = deserializer.ReadPropertyWithExplicitDefault(202, "partition_limit", optional_idx()); + auto result = duckdb::unique_ptr(new LogicalWindow(window_index, partition_limit)); + result->expressions = std::move(expressions); return std::move(result); } diff --git a/src/duckdb/src/storage/single_file_block_manager.cpp b/src/duckdb/src/storage/single_file_block_manager.cpp index e28ca2b32..1a388e55b 100644 --- a/src/duckdb/src/storage/single_file_block_manager.cpp +++ b/src/duckdb/src/storage/single_file_block_manager.cpp @@ -926,7 +926,7 @@ block_id_t SingleFileBlockManager::GetFreeBlockIdInternal(FreeBlockType type) { } // add the entry to the list of newly used blocks if (type == FreeBlockType::NEWLY_USED_BLOCK) { - newly_used_blocks.insert(block_id); + newly_used_blocks[block_id] = MAX_TRANSACTION_ID; } if (BlockIsRegistered(block_id)) { throw InternalException("Free block %d is already registered", block_id); @@ -957,6 +957,17 @@ void SingleFileBlockManager::MarkBlockAsCheckpointed(block_id_t block_id) { newly_used_blocks.erase(block_id); } +void SingleFileBlockManager::MarkBlockAsCommitted(block_id_t block_id, transaction_t commit_id) { + lock_guard lock(single_file_block_lock); + auto entry = newly_used_blocks.find(block_id); + // optimistic writes keep their blocks newly used until their commit + if (entry == newly_used_blocks.end()) { + throw InternalException("MarkBlockAsCommitted called with block id %d that is not newly used", block_id); + } + D_ASSERT(entry->second == MAX_TRANSACTION_ID || entry->second == commit_id); + entry->second = commit_id; +} + void SingleFileBlockManager::MarkBlockAsUsed(block_id_t block_id) { lock_guard lock(single_file_block_lock); D_ASSERT(block_id >= 0); @@ -1004,7 +1015,7 @@ void SingleFileBlockManager::MarkBlockAsModified(block_id_t block_id) { throw InternalException("MarkBlockAsModified called with already freed block id %d", block_id); } auto newly_used_entry = newly_used_blocks.find(block_id); - if (newly_used_entry != newly_used_blocks.end()) { + if (newly_used_entry != newly_used_blocks.end() && newly_used_entry->second == MAX_TRANSACTION_ID) { // this block was newly used - and now we are labeling it as no longer being required // we can directly add it back to the free list newly_used_blocks.erase(block_id); @@ -1012,6 +1023,8 @@ void SingleFileBlockManager::MarkBlockAsModified(block_id_t block_id) { } else { // this block was used in storage, we cannot directly re-use it // add it to the modified blocks indicating it will be re-usable after the next checkpoint + // so is a committed newly used block, which the WAL of its commit refers to until a header includes it + newly_used_blocks.erase(block_id); modified_blocks.insert(block_id); } } @@ -1063,7 +1076,7 @@ void SingleFileBlockManager::VerifyBlocks(const unordered_map } } for (auto &newly_used_block : newly_used_blocks) { - referenced_blocks.insert(newly_used_block); + referenced_blocks.insert(newly_used_block.first); } for (auto &free_block : free_list) { referenced_blocks.insert(free_block); @@ -1108,7 +1121,7 @@ void SingleFileBlockManager::VerifyBlocks(const unordered_map if (!newly_used_blocks_str.empty()) { newly_used_blocks_str += ", "; } - newly_used_blocks_str += to_string(block); + newly_used_blocks_str += to_string(block.first); } throw InternalException( @@ -1174,7 +1187,13 @@ unique_ptr SingleFileBlockManager::CreateBlock(block_id_t block_id, FileB } idx_t SingleFileBlockManager::GetBlockLocation(block_id_t block_id) const { - return BLOCK_START + NumericCast(block_id) * GetBlockAllocSize(); + const auto block_index = NumericCast(block_id); + const auto block_alloc_size = GetBlockAllocSize(); + // block ids are read from the file: the location of a block (and its end) must not wrap around + if (block_index >= (NumericLimits::Maximum() - BLOCK_START) / block_alloc_size) { + throw DataCorruptionException("Corrupt database file: block id %lld is out of range", block_id); + } + return BLOCK_START + block_index * block_alloc_size; } void SingleFileBlockManager::ReadBlock(data_ptr_t internal_buffer, uint64_t block_size, bool skip_block_header) const { @@ -1340,7 +1359,7 @@ bool SingleFileBlockManager::AddFreeBlock(unique_lock &lock, block_id_t b lock.lock(); return false; } -void SingleFileBlockManager::WriteHeader(QueryContext context, DatabaseHeader header) { +void SingleFileBlockManager::WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound) { auto free_list_blocks = GetFreeListBlocks(); // now handle the free list @@ -1359,10 +1378,16 @@ void SingleFileBlockManager::WriteHeader(QueryContext context, DatabaseHeader he all_free_blocks.insert(block); } auto written_multi_use_blocks = multi_use_blocks; - // newly used blocks are still free blocks for this checkpoint - so add them to the free list that we write - for (auto &newly_used_block : newly_used_blocks) { - all_free_blocks.insert(newly_used_block); - written_multi_use_blocks.erase(newly_used_block); + for (auto entry = newly_used_blocks.begin(); entry != newly_used_blocks.end();) { + if (entry->second < bound) { + // committed before the bound: this checkpoint includes the block + entry = newly_used_blocks.erase(entry); + continue; + } + // newly used blocks are still free blocks for this checkpoint - so add them to the free list that we write + all_free_blocks.insert(entry->first); + written_multi_use_blocks.erase(entry->first); + entry++; } if (!free_list_blocks.empty()) { diff --git a/src/duckdb/src/storage/standard_buffer_manager.cpp b/src/duckdb/src/storage/standard_buffer_manager.cpp index c5dc70200..d89b0d708 100644 --- a/src/duckdb/src/storage/standard_buffer_manager.cpp +++ b/src/duckdb/src/storage/standard_buffer_manager.cpp @@ -871,22 +871,23 @@ HugeAllocation BufferAllocator::AllocateHuge(idx_t size) { D_ASSERT(size > 0); auto &data = GetPrivateData()->Cast(); auto reservation = data.Reserve(size); - auto pointer = BlockAllocator::Get(data.manager.GetDatabase()).AllocateHugeData(size); + optional_idx home; + auto pointer = BlockAllocator::Get(data.manager.GetDatabase()).AllocateHugeData(size, home); reservation.size = 0; - return HugeAllocation(*this, pointer, size); + return HugeAllocation(*this, pointer, size, home); } -void BufferAllocator::FreeHuge(data_ptr_t pointer, idx_t size) { +void BufferAllocator::FreeHuge(data_ptr_t pointer, idx_t size, optional_idx home) { auto &data = GetPrivateData()->Cast(); data.Release(size); - BlockAllocator::Get(data.manager.GetDatabase()).FreeHugeData(pointer, size); + BlockAllocator::Get(data.manager.GetDatabase()).FreeHugeData(pointer, size, home); } HugeAllocation::HugeAllocation() : allocator(nullptr), pointer(nullptr), allocated_size(0) { } -HugeAllocation::HugeAllocation(BufferAllocator &allocator, data_ptr_t pointer, idx_t allocated_size) - : allocator(allocator), pointer(pointer), allocated_size(allocated_size) { +HugeAllocation::HugeAllocation(BufferAllocator &allocator, data_ptr_t pointer, idx_t allocated_size, optional_idx home) + : allocator(allocator), pointer(pointer), allocated_size(allocated_size), allocation_shard(home) { D_ASSERT(pointer); } @@ -898,12 +899,14 @@ HugeAllocation::HugeAllocation(HugeAllocation &&other) noexcept : allocator(other.allocator), pointer(nullptr), allocated_size(0) { std::swap(pointer, other.pointer); std::swap(allocated_size, other.allocated_size); + std::swap(allocation_shard, other.allocation_shard); } HugeAllocation &HugeAllocation::operator=(HugeAllocation &&other) noexcept { std::swap(allocator, other.allocator); std::swap(pointer, other.pointer); std::swap(allocated_size, other.allocated_size); + std::swap(allocation_shard, other.allocation_shard); return *this; } @@ -912,9 +915,10 @@ void HugeAllocation::Reset() { return; } D_ASSERT(allocator); - allocator->FreeHuge(pointer, allocated_size); + allocator->FreeHuge(pointer, allocated_size, allocation_shard); pointer = nullptr; allocated_size = 0; + allocation_shard = optional_idx(); } BufferAllocator &BufferAllocator::Get(ClientContext &context) { diff --git a/src/duckdb/src/storage/statistics/base_statistics.cpp b/src/duckdb/src/storage/statistics/base_statistics.cpp index f1e25e0c1..611452c2e 100644 --- a/src/duckdb/src/storage/statistics/base_statistics.cpp +++ b/src/duckdb/src/storage/statistics/base_statistics.cpp @@ -74,7 +74,7 @@ StatisticsType BaseStatistics::GetStatsType(const LogicalType &type) { if (type.id() == LogicalTypeId::SQLNULL) { return StatisticsType::BASE_STATS; } - if (type.id() == LogicalTypeId::GEOMETRY) { + if (type.id() == LogicalTypeId::GEOMETRY || type.id() == LogicalTypeId::GEOGRAPHY) { return StatisticsType::GEOMETRY_STATS; } if (type.id() == LogicalTypeId::VARIANT) { @@ -710,6 +710,7 @@ BaseStatistics BaseStatistics::FromConstantType(const Value &input) { } else { VariantStats::SetUnshreddedStats( result, FromConstant(Value::STRUCT(unshredded_type, StructValue::GetChildren(input)))); + VariantStats::MarkAsNotShredded(result); } return result; } diff --git a/src/duckdb/src/storage/statistics/geometry_stats.cpp b/src/duckdb/src/storage/statistics/geometry_stats.cpp index bea8410e5..edd21d681 100644 --- a/src/duckdb/src/storage/statistics/geometry_stats.cpp +++ b/src/duckdb/src/storage/statistics/geometry_stats.cpp @@ -74,14 +74,16 @@ bool GeometryTypeSet::TryAdd(const string &type_name) { BaseStatistics GeometryStats::CreateUnknown(LogicalType type) { BaseStatistics result(std::move(type)); result.InitializeUnknown(); - GetDataUnsafe(result).SetUnknown(); + auto &data = GetDataUnsafe(result); + data.SetUnknown(); return result; } BaseStatistics GeometryStats::CreateEmpty(LogicalType type) { BaseStatistics result(std::move(type)); result.InitializeEmpty(); - GetDataUnsafe(result).SetEmpty(); + auto &data = GetDataUnsafe(result); + data.SetEmpty(); return result; } @@ -276,7 +278,7 @@ void GeometryStats::SetFromStruct(BaseStatistics &stats, StatsStructFields &fiel void GeometryStats::Update(BaseStatistics &stats, const string_t &value) { auto &data = GetDataUnsafe(stats); - data.Update(value); + data.Update(value, Geometry::GetModel(stats.GetType())); } void GeometryStats::Merge(BaseStatistics &stats, const BaseStatistics &other) { @@ -289,7 +291,7 @@ void GeometryStats::Merge(BaseStatistics &stats, const BaseStatistics &other) { auto &target = GetDataUnsafe(stats); auto &source = GetDataUnsafe(other); - target.Merge(source); + target.Merge(source, Geometry::GetModel(stats.GetType())); } void GeometryStats::Verify(const BaseStatistics &stats, const Vector &vector, const SelectionVector &sel, idx_t count) { diff --git a/src/duckdb/src/storage/storage_manager.cpp b/src/duckdb/src/storage/storage_manager.cpp index 2b8ee85d3..f1e34384e 100644 --- a/src/duckdb/src/storage/storage_manager.cpp +++ b/src/duckdb/src/storage/storage_manager.cpp @@ -380,6 +380,11 @@ string StorageManager::GetUnsupportedTypeReason(const LogicalType &logical_type) required, db.GetName(), current); } break; + case LogicalTypeId::GEOGRAPHY: + if (storage_version < Geometry::GEOGRAPHY_VERSION_ADDED) { + reason = unsupported("GEOGRAPHY columns", Geometry::GEOGRAPHY_VERSION_ADDED); + } + break; default: break; } @@ -831,7 +836,7 @@ class SingleFileStorageCommitState : public StorageCommitState { //! Revert the commit void RevertCommit() override; // Make the commit persistent - idx_t FlushCommit(bool sync_now) override; + idx_t FlushCommit(transaction_t commit_id, bool sync_now) override; void AddRowGroupData(DataTable &table, idx_t start_index, idx_t count, unique_ptr row_group_data) override; @@ -893,7 +898,7 @@ void SingleFileStorageCommitState::RevertCommit() { state = WALCommitState::TRUNCATED; } -idx_t SingleFileStorageCommitState::FlushCommit(bool sync_now) { +idx_t SingleFileStorageCommitState::FlushCommit(transaction_t commit_id, bool sync_now) { if (state != WALCommitState::IN_PROGRESS) { return 0; } @@ -918,6 +923,17 @@ idx_t SingleFileStorageCommitState::FlushCommit(bool sync_now) { wal_sync_offset = wal.FlushMarker(); } state = WALCommitState::FLUSHED; + // checkpoints whose bound is past the commit include the blocks of its optimistically written row groups + auto &block_manager = storage.GetBlockManager(); + for (auto &entry : optimistically_written_data) { + for (auto &rg_entry : entry.second) { + if (rg_entry.second.row_group_data) { + for (auto &block_id : rg_entry.second.row_group_data->GetBlockIds()) { + block_manager.MarkBlockAsCommitted(block_id, commit_id); + } + } + } + } return wal_sync_offset; } diff --git a/src/duckdb/src/storage/table/array_column_data.cpp b/src/duckdb/src/storage/table/array_column_data.cpp index e104b0213..195a221e7 100644 --- a/src/duckdb/src/storage/table/array_column_data.cpp +++ b/src/duckdb/src/storage/table/array_column_data.cpp @@ -305,9 +305,9 @@ void ArrayColumnData::SetChildData(shared_ptr child_column_p) { } struct ArrayColumnCheckpointState : public ColumnCheckpointState { - ArrayColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, + ArrayColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, Context &context, PartialBlockManager &partial_block_manager) - : ColumnCheckpointState(row_group, column_data, partial_block_manager) { + : ColumnCheckpointState(row_group, column_data, context, partial_block_manager) { global_stats = ArrayStats::CreateEmpty(column_data.type).ToUnique(); } @@ -347,16 +347,17 @@ struct ArrayColumnCheckpointState : public ColumnCheckpointState { } }; -unique_ptr ArrayColumnData::CreateCheckpointState(const RowGroup &row_group, +unique_ptr ArrayColumnData::CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) { - return make_uniq(row_group, *this, partial_block_manager); + return make_uniq(row_group, *this, context, partial_block_manager); } unique_ptr ArrayColumnData::Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &checkpoint_info, const BaseStatistics &old_stats) { auto &partial_block_manager = checkpoint_info.GetPartialBlockManager(); - auto checkpoint_state = make_uniq(row_group, *this, partial_block_manager); + auto &context = checkpoint_info.GetContext(); + auto checkpoint_state = make_uniq(row_group, *this, context, partial_block_manager); checkpoint_state->validity_state = validity->Checkpoint(row_group, checkpoint_info, old_stats); checkpoint_state->child_state = child_column->Checkpoint(row_group, checkpoint_info, ArrayStats::GetChildStats(old_stats)); diff --git a/src/duckdb/src/storage/table/column_checkpoint_state.cpp b/src/duckdb/src/storage/table/column_checkpoint_state.cpp index 8d20f6988..263a384e6 100644 --- a/src/duckdb/src/storage/table/column_checkpoint_state.cpp +++ b/src/duckdb/src/storage/table/column_checkpoint_state.cpp @@ -7,10 +7,10 @@ namespace duckdb { -ColumnCheckpointState::ColumnCheckpointState(const RowGroup &row_group, ColumnData &original_column, +ColumnCheckpointState::ColumnCheckpointState(const RowGroup &row_group, ColumnData &original_column, Context &context, PartialBlockManager &partial_block_manager) - : row_group(row_group), original_column(original_column), partial_block_manager(partial_block_manager), - original_column_mutable(original_column) { + : row_group(row_group), original_column(original_column), context(context), + partial_block_manager(partial_block_manager), original_column_mutable(original_column) { } ColumnCheckpointState::~ColumnCheckpointState() { @@ -74,7 +74,7 @@ void ColumnCheckpointState::FlushSegmentInternal(unique_ptr segme auto &buffer_manager = BufferManager::GetBufferManager(db); auto source = buffer_manager.Pin(segment->GetBlockHandle()); - if (auto new_block_ptr = partial_block_manager.Write(*segment, std::move(source), byte_size)) { + if (auto new_block_ptr = partial_block_manager.Write(context, *segment, std::move(source), byte_size)) { block_ptr = *new_block_ptr; }; } else { diff --git a/src/duckdb/src/storage/table/column_data.cpp b/src/duckdb/src/storage/table/column_data.cpp index 64872a439..f0f6b3a46 100644 --- a/src/duckdb/src/storage/table/column_data.cpp +++ b/src/duckdb/src/storage/table/column_data.cpp @@ -967,9 +967,9 @@ void ColumnData::VisitBlockIds(BlockIdVisitor &visitor) const { } } -unique_ptr ColumnData::CreateCheckpointState(const RowGroup &row_group, +unique_ptr ColumnData::CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) { - return make_uniq(row_group, *this, partial_block_manager); + return make_uniq(row_group, *this, context, partial_block_manager); } void ColumnData::CheckpointScan(ColumnSegment &segment, ColumnScanState &state, idx_t count, @@ -995,7 +995,8 @@ ColumnData::Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &checkpoi // scan the segments of the column data // set up the checkpoint state auto &partial_block_manager = checkpoint_info.GetPartialBlockManager(); - auto checkpoint_state = CreateCheckpointState(row_group, partial_block_manager); + auto &context = checkpoint_info.GetContext(); + auto checkpoint_state = CreateCheckpointState(row_group, context, partial_block_manager); checkpoint_state->global_stats = BaseStatistics::CreateEmpty(type).ToUnique(); if (!data.GetRootSegment()) { @@ -1148,7 +1149,7 @@ static PersistentColumnData GetPersistentColumnDataType(Deserializer &deserializ return result; } case ExtraPersistentColumnDataType::GEOMETRY: { - if (column_type.id() != LogicalTypeId::GEOMETRY) { + if (column_type.id() != LogicalTypeId::GEOMETRY && column_type.id() != LogicalTypeId::GEOGRAPHY) { throw DataCorruptionException("GEOMETRY column data found for a column of type %s", column_type); } const auto &geometry_data = extra_data->Cast(); @@ -1387,7 +1388,7 @@ unique_ptr ExtraPersistentColumnData::Deserialize(Des case ExtraPersistentColumnDataType::LIST: return ListPersistentColumnData::Deserialize(deserializer); default: - throw InternalException("Unknown PersistentColumnData type"); + throw DataCorruptionException("Column data with extra data of an unknown type"); } } @@ -1511,14 +1512,17 @@ void ColumnData::Verify(RowGroup &parent) { #ifdef DEBUG data.Verify(); + const auto is_geo_type = [](LogicalTypeId id) { + return id == LogicalTypeId::GEOMETRY || id == LogicalTypeId::GEOGRAPHY; + }; bool is_geometry_child_column = false; - if (type.id() == LogicalTypeId::GEOMETRY && this->parent && this->parent->type.id() == LogicalTypeId::GEOMETRY) { - // Geometry child column + if (is_geo_type(type.id()) && this->parent && is_geo_type(this->parent->type.id())) { + // Geometry/geography child column is_geometry_child_column = true; } if (type.InternalType() == PhysicalType::STRUCT || type.InternalType() == PhysicalType::ARRAY || - (type.id() == LogicalTypeId::GEOMETRY && !is_geometry_child_column)) { + (is_geo_type(type.id()) && !is_geometry_child_column)) { // structs and fixed size lists don't have segments D_ASSERT(!data.GetRootSegment()); return; @@ -1541,7 +1545,7 @@ void ColumnData::Verify(RowGroup &parent) { shared_ptr ColumnData::CreateColumn(BlockManager &block_manager, DataTableInfo &info, idx_t column_index, const LogicalType &type, ColumnDataType data_type, optional_ptr parent) { - if (type.id() == LogicalTypeId::GEOMETRY) { + if (type.id() == LogicalTypeId::GEOMETRY || type.id() == LogicalTypeId::GEOGRAPHY) { return make_shared_ptr(block_manager, info, column_index, type, data_type, parent); } if (type.id() == LogicalTypeId::VARIANT) { diff --git a/src/duckdb/src/storage/table/column_data_checkpointer.cpp b/src/duckdb/src/storage/table/column_data_checkpointer.cpp index fa7ef73bb..0055a2ca8 100644 --- a/src/duckdb/src/storage/table/column_data_checkpointer.cpp +++ b/src/duckdb/src/storage/table/column_data_checkpointer.cpp @@ -6,6 +6,7 @@ #include "duckdb/main/settings.hpp" #include "duckdb/logging/log_manager.hpp" #include "duckdb/parser/column_definition.hpp" +#include "duckdb/storage/partial_block_manager.hpp" #include "duckdb/storage/storage_manager.hpp" #include "duckdb/storage/table/data_table_info.hpp" #include "duckdb/storage/table/scan_state.hpp" @@ -422,6 +423,10 @@ void ColumnDataCheckpointer::Checkpoint() { if (!has_changes) { // Nothing has undergone any changes, no need to checkpoint // just move on to finalizing + if (checkpoint_info.GetPartialBlockManager().GetPartialBlockType() == PartialBlockType::APPEND_TO_TABLE) { + // an optimistic write: its blocks stay newly used until its commit + return; + } // mark block ids as checkpointed CheckpointBlockIdMarker marker(storage_manager.GetBlockManager()); for (idx_t i = 0; i < checkpoint_states.size(); i++) { diff --git a/src/duckdb/src/storage/table/column_segment.cpp b/src/duckdb/src/storage/table/column_segment.cpp index 0e0264935..b0fb07b61 100644 --- a/src/duckdb/src/storage/table/column_segment.cpp +++ b/src/duckdb/src/storage/table/column_segment.cpp @@ -31,7 +31,14 @@ unique_ptr ColumnSegment::CreatePersistentSegment(DatabaseInstanc shared_ptr block; auto &type = statistics.GetType(); - auto function = config.GetCompressionFunction(compression_type, type.InternalType()); + // the compression type is read from the file - it might not exist (for the type of this column) + auto compression_function = config.TryGetCompressionFunction(compression_type, type.InternalType()); + if (!compression_function) { + throw DataCorruptionException( + "Persistent segment has compression type %llu, which does not exist for physical type %s", + static_cast(compression_type), EnumUtil::ToString(type.InternalType())); + } + reference function(*compression_function); if (block_id == INVALID_BLOCK && !function.get().supports_null_block) { throw DataCorruptionException("Persistent %s segment is missing its data block", CompressionTypeToString(compression_type)); @@ -478,7 +485,7 @@ static idx_t ExecuteExpressionFilterSelection(SelectionVector &sel, Vector &vect chunk.data.emplace_back(Vector::Ref(vector)); chunk.SetChildCardinality(scan_count); SelectionVector identity_sel; - optional_ptr current_sel = sel.IsSet() ? &sel : nullptr; + optional_ptr current_sel = sel.IsSet() ? &sel : nullptr; if (!sel.IsSet() && (vector.GetType().IsNested() || approved_tuple_count != scan_count)) { identity_sel = SelectionVector::Incremental(approved_tuple_count); current_sel = &identity_sel; diff --git a/src/duckdb/src/storage/table/geo_column_data.cpp b/src/duckdb/src/storage/table/geo_column_data.cpp index 05343d7b0..e9554ced2 100644 --- a/src/duckdb/src/storage/table/geo_column_data.cpp +++ b/src/duckdb/src/storage/table/geo_column_data.cpp @@ -167,9 +167,9 @@ unique_ptr GeoColumnData::GetUpdateStatistics() { class GeoColumnCheckpointState final : public ColumnCheckpointState { public: - GeoColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, + GeoColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, Context &context, PartialBlockManager &partial_block_manager) - : ColumnCheckpointState(row_group, column_data, partial_block_manager) { + : ColumnCheckpointState(row_group, column_data, context, partial_block_manager) { // Make stats global_stats = GeometryStats::CreateEmpty(column_data.type).ToUnique(); @@ -231,9 +231,9 @@ class GeoColumnCheckpointState final : public ColumnCheckpointState { } }; -unique_ptr GeoColumnData::CreateCheckpointState(const RowGroup &row_group, +unique_ptr GeoColumnData::CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) { - return make_uniq(row_group, *this, partial_block_manager); + return make_uniq(row_group, *this, context, partial_block_manager); } static GeometryStorageType GetStorageType(GeometryType geom_type, VertexType vert_type) { @@ -328,14 +328,16 @@ static GeometryStorageType GetStorageType(GeometryType geom_type, VertexType ver unique_ptr GeoColumnData::Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info, const BaseStatistics &old_stats) { auto &partial_block_manager = info.GetPartialBlockManager(); - auto checkpoint_state = make_uniq(row_group, *this, partial_block_manager); + auto &context = info.GetContext(); + auto checkpoint_state = make_uniq(row_group, *this, context, partial_block_manager); // When the inner column is unshredded, the geometry old_stats are already correct. // When the inner column is shredded, the base_column has no stats of its own (it is parented to us). // Shredded columns are always re-written from scratch, and the stats are recomputes, do the empty stats of the // inner layout type is a correct default in these cases. unique_ptr shredded_stats; - if (base_column->GetType().id() != LogicalTypeId::GEOMETRY) { + const auto base_id = base_column->GetType().id(); + if (base_id != LogicalTypeId::GEOMETRY && base_id != LogicalTypeId::GEOGRAPHY) { shredded_stats = BaseStatistics::CreateEmpty(base_column->GetType()).ToUnique(); } auto &old_column_stats = shredded_stats ? *shredded_stats : old_stats; @@ -462,7 +464,12 @@ unique_ptr GeoColumnData::Checkpoint(const RowGroup &row_ // We cant specialize empty geometries, because we cant represent zero-vertex geometries in those layouts const auto has_empty = flags.HasEmptyGeometry() || flags.HasEmptyPart(); - if (has_mixed_type || has_only_geometry_collection || has_only_invalid || has_empty) { + // Only single-point GEOGRAPHY shreds: the shredded layouts keep per-ordinate vertex stats, which cannot + // represent the geodetic coverage extent zonemap pruning relies on (edge bulge, pole-enclosing rings, and + // the antimeridian-wrapped arc any multi-vertex row can span). A single point's extent is its coordinates. + const auto has_geodetic_extent = type.id() == LogicalTypeId::GEOGRAPHY && new_geom_type != GeometryType::POINT; + + if (has_mixed_type || has_only_geometry_collection || has_only_invalid || has_empty || has_geodetic_extent) { // Cant specialize, keep column checkpoint_state->inner_column = base_column; checkpoint_state->inner_column_state = @@ -670,6 +677,21 @@ void GeoColumnData::InterpretStats(const BaseStatistics &source, BaseStatistics extent.y_min = NumericStats::GetMin(vert_stats[1]); extent.y_max = NumericStats::GetMax(vert_stats[1]); + // For GEOGRAPHY, the per-ordinate min/max only covers the vertices. That is exact for single points, + // but any multi-vertex row has a wider coverage extent: its bounding arc may wrap the antimeridian + // (which a numeric X range cannot express), geodesic edges bulge poleward beyond their vertices, and + // rings can enclose a pole. None of that is reconstructible from per-ordinate stats, so widen X (and + // Y for layouts with edges) to the full globe. Checkpoint never shreds such columns (see + // has_geodetic_extent), so this is a defensive guard that keeps pruning sound should that ever change. + if (target.GetType().id() == LogicalTypeId::GEOGRAPHY && geom_type != GeometryType::POINT) { + extent.x_min = -180.0; + extent.x_max = 180.0; + if (geom_type != GeometryType::MULTIPOINT) { + extent.y_min = -90.0; + extent.y_max = 90.0; + } + } + switch (vert_type) { case VertexType::XYZ: extent.z_min = NumericStats::GetMin(vert_stats[2]); diff --git a/src/duckdb/src/storage/table/in_memory_checkpoint.cpp b/src/duckdb/src/storage/table/in_memory_checkpoint.cpp index 21081e7f6..90e0e2442 100644 --- a/src/duckdb/src/storage/table/in_memory_checkpoint.cpp +++ b/src/duckdb/src/storage/table/in_memory_checkpoint.cpp @@ -23,8 +23,8 @@ InMemoryCheckpointer::InMemoryCheckpointer(QueryContext context, AttachedDatabas StorageManager &storage_manager, CheckpointOptions options_p, optional_ptr checkpoint_context) : CheckpointWriter(db, context, checkpoint_context), - partial_block_manager(GetContext(), block_manager, PartialBlockType::IN_MEMORY_CHECKPOINT), - storage_manager(storage_manager), options(options_p) { + partial_block_manager(block_manager, PartialBlockType::IN_MEMORY_CHECKPOINT), storage_manager(storage_manager), + options(options_p) { } void InMemoryCheckpointer::CreateCheckpoint() { @@ -145,7 +145,7 @@ unique_ptr InMemoryTableDataWriter::GetTableIndexWriter(Storag void InMemoryTableDataWriter::FlushPartialBlocks() { // Finalize packed buffers before the checkpoint row groups become visible. - checkpoint_manager.GetPartialBlockManager().FlushPartialBlocks(); + checkpoint_manager.GetPartialBlockManager().FlushPartialBlocks(checkpoint_manager.GetContext()); } CheckpointOptions InMemoryTableDataWriter::GetCheckpointOptions() const { diff --git a/src/duckdb/src/storage/table/list_column_data.cpp b/src/duckdb/src/storage/table/list_column_data.cpp index 49b8f7824..c45faf971 100644 --- a/src/duckdb/src/storage/table/list_column_data.cpp +++ b/src/duckdb/src/storage/table/list_column_data.cpp @@ -429,9 +429,9 @@ void ListColumnData::SetChildData(shared_ptr child_column_p) { } struct ListColumnCheckpointState : public ColumnCheckpointState { - ListColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, + ListColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, Context &context, PartialBlockManager &partial_block_manager) - : ColumnCheckpointState(row_group, column_data, partial_block_manager) { + : ColumnCheckpointState(row_group, column_data, context, partial_block_manager) { global_stats = ListStats::CreateEmpty(column_data.type).ToUnique(); } @@ -480,9 +480,9 @@ struct ListColumnCheckpointState : public ColumnCheckpointState { } }; -unique_ptr ListColumnData::CreateCheckpointState(const RowGroup &row_group, +unique_ptr ListColumnData::CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) { - return make_uniq(row_group, *this, partial_block_manager); + return make_uniq(row_group, *this, context, partial_block_manager); } unique_ptr ListColumnData::Checkpoint(const RowGroup &row_group, diff --git a/src/duckdb/src/storage/table/row_group.cpp b/src/duckdb/src/storage/table/row_group.cpp index f39f12abc..0f74d7835 100644 --- a/src/duckdb/src/storage/table/row_group.cpp +++ b/src/duckdb/src/storage/table/row_group.cpp @@ -383,26 +383,13 @@ void CollectionScanState::Initialize(const QueryContext &context_p, const vector } bool RowGroup::InitializeScanInternal(CollectionScanState &state, SegmentNode &node, idx_t vector_offset) { - auto &filters = state.GetFilterInfo(); - if (!CheckZonemap(state.context.GetClientContext(), filters, node.GetRowStart())) { - return false; - } - if (!RefersToSameObject(node.GetNode(), *this)) { + auto payload = node.ReferenceNode(); + if (!RefersToSameObject(*payload, *this)) { throw InternalException("RowGroup::InitializeScan segment node mismatch"); } - D_ASSERT(state.prepared_vector.prepare_state == VectorPrepareState::NONE); - state.prepared_vector.Reset(); - state.assignment_io_registered = false; - state.SetRowGroup(node); - state.vector_index = vector_offset; auto row_start = node.GetRowStart(); - state.max_row_group_row = row_start > state.max_row ? 0 : MinValue(this->count, state.max_row - row_start); - if (state.max_row_group_row == 0) { - // exceeded row groups to scan - return false; - } - D_ASSERT(!state.column_scans.empty()); - return true; + const auto end_row = row_start > state.max_row ? 0 : MinValue(this->count, state.max_row - row_start); + return state.InitializeRowGroupScan(node, std::move(payload), vector_offset, end_row); } bool RowGroup::InitializeScanWithOffset(CollectionScanState &state, SegmentNode &node, idx_t vector_offset, @@ -848,33 +835,31 @@ bool RowGroup::CheckZonemapSegments(CollectionScanState &state) { } } -bool RowGroup::RegisterScanIO(CollectionScanState &state, idx_t start_row, idx_t end_row, - PrefetchState &prefetch_state) const { - if (!GetBlockManager().Prefetch()) { - return false; - } +void RowGroup::CollectScanBlocks(CollectionScanState &state, idx_t start_row, idx_t end_row, + PrefetchState &prefetch_state) const { const auto &column_ids = state.GetColumnIds(); for (idx_t i = 0; i < column_ids.size(); i++) { GetColumn(column_ids[i]).InitializePrefetch(prefetch_state, state.column_scans[i], start_row, end_row); } - return true; } void RowGroup::PrefetchScanIO(CollectionScanState &state, idx_t row_count) const { - PrefetchState prefetch_state; - const idx_t start_row = state.vector_index * STANDARD_VECTOR_SIZE; - if (!RegisterScanIO(state, start_row, start_row + row_count, prefetch_state)) { + if (!GetBlockManager().Prefetch()) { return; } + PrefetchState prefetch_state; + const idx_t start_row = state.vector_index * STANDARD_VECTOR_SIZE; + CollectScanBlocks(state, start_row, start_row + row_count, prefetch_state); GetBlockManager().buffer_manager.Prefetch(state.context, prefetch_state.blocks); } vector> RowGroup::CollectScanIOTasks(CollectionScanState &state, idx_t row_count) const { - PrefetchState prefetch_state; - const idx_t start_row = state.vector_index * STANDARD_VECTOR_SIZE; - if (!RegisterScanIO(state, start_row, start_row + row_count, prefetch_state)) { + if (!GetBlockManager().Prefetch()) { return vector>(); } + PrefetchState prefetch_state; + const idx_t start_row = state.vector_index * STANDARD_VECTOR_SIZE; + CollectScanBlocks(state, start_row, start_row + row_count, prefetch_state); return GetBlockManager().buffer_manager.CreatePrefetchTasks(state.context, prefetch_state.blocks); } @@ -883,6 +868,11 @@ vector> RowGroup::CollectAssignmentIOTasks(CollectionScanS return vector>(); } PrefetchState prefetch_state; + CollectAssignmentBlocks(state, prefetch_state); + return GetBlockManager().buffer_manager.CreatePrefetchTasks(state.context, prefetch_state.blocks); +} + +void RowGroup::CollectAssignmentBlocks(CollectionScanState &state, PrefetchState &prefetch_state) const { const auto &filters = state.GetFilterInfo().GetFilterList(); const idx_t end_row = state.max_row_group_row; idx_t row = state.vector_index * STANDARD_VECTOR_SIZE; @@ -914,10 +904,9 @@ vector> RowGroup::CollectAssignmentIOTasks(CollectionScanS D_ASSERT(accepted_end > row); const idx_t run_start = row - row % STANDARD_VECTOR_SIZE; const idx_t run_end = MinValue(AlignValue(accepted_end), end_row); - RegisterScanIO(state, run_start, run_end, prefetch_state); + CollectScanBlocks(state, run_start, run_end, prefetch_state); row = run_end; } - return GetBlockManager().buffer_manager.CreatePrefetchTasks(state.context, prefetch_state.blocks); } bool RowGroup::PrepareScan(ScanOptions options, CollectionScanState &state) { @@ -1019,8 +1008,8 @@ void RowGroup::ProcessPreparedScan(ScanOptions options, CollectionScanState &sta // partial scan: we have deletions or table filters idx_t approved_tuple_count = count; SelectionVector sel; - SelectionVector intersect_sel(STANDARD_VECTOR_SIZE); if (has_sample_selection && count != max_count) { + SelectionVector intersect_sel(STANDARD_VECTOR_SIZE); approved_tuple_count = IntersectSelections(state.valid_sel, count, sample_sel, sample_count, intersect_sel); if (approved_tuple_count == 0) { NextVector(state); @@ -1050,7 +1039,7 @@ void RowGroup::ProcessPreparedScan(ScanOptions options, CollectionScanState &sta auto &table_filter_state = *filter.filter_state; const auto scan_idx = filter.scan_column_index; - const auto column_idx = filter.table_column_index; + const auto &column_idx = filter.table_column_index; auto &result_vector = result.data[scan_idx]; if (approved_tuple_count == 0) { @@ -1394,6 +1383,7 @@ void RowGroup::Update(TransactionData transaction, DuckTableEntry &table_entry, WriteRows(transaction, table_entry, vector_idx, vector_start, ids + offset, count, UnsafeNumericCast(vector_start), true, written); } + lock_guard update_guard(update_lock); for (idx_t i = 0; i < column_ids.size(); i++) { auto column = column_ids[i]; auto &col_data = GetColumn(column.index); @@ -1467,14 +1457,15 @@ ColumnCheckpointInfo::ColumnCheckpointInfo(RowGroupWriteInfo &info, idx_t column : column_idx(column_idx), info(info) { } -RowGroupWriteInfo::RowGroupWriteInfo(PartialBlockManager &manager, const vector &compression_types, - CheckpointOptions options_p) - : manager(manager), compression_types(compression_types), options(options_p) { +RowGroupWriteInfo::RowGroupWriteInfo(Context &context, PartialBlockManager &manager, + const vector &compression_types, CheckpointOptions options_p) + : manager(manager), context(context), compression_types(compression_types), options(options_p) { } -RowGroupWriteInfo::RowGroupWriteInfo(PartialBlockManager &manager, const vector &compression_types, +RowGroupWriteInfo::RowGroupWriteInfo(Context &context, PartialBlockManager &manager, + const vector &compression_types, vector> &column_partial_block_managers_p) - : manager(manager), compression_types(compression_types), options(), + : manager(manager), context(context), compression_types(compression_types), options(), column_partial_block_managers(column_partial_block_managers_p) { } @@ -1485,6 +1476,10 @@ PartialBlockManager &RowGroupWriteInfo::GetPartialBlockManager(idx_t column_idx) return manager; } +Context &ColumnCheckpointInfo::GetContext() { + return info.context; +} + PartialBlockManager &ColumnCheckpointInfo::GetPartialBlockManager() { return info.GetPartialBlockManager(column_idx); } @@ -1730,7 +1725,8 @@ RowGroupWriteData RowGroup::WriteToDisk(RowGroupWriter &writer) { } } - RowGroupWriteInfo info(writer.GetPartialBlockManager(), compression_types, writer.GetCheckpointOptions()); + RowGroupWriteInfo info(writer.GetTableWriter().GetContext(), writer.GetPartialBlockManager(), compression_types, + writer.GetCheckpointOptions()); vector reused_columns; for (idx_t column_idx = 0; column_idx < GetColumnCount(); column_idx++) { diff --git a/src/duckdb/src/storage/table/row_group_collection.cpp b/src/duckdb/src/storage/table/row_group_collection.cpp index 51251c545..e88d3d074 100644 --- a/src/duckdb/src/storage/table/row_group_collection.cpp +++ b/src/duckdb/src/storage/table/row_group_collection.cpp @@ -112,6 +112,16 @@ void RowGroupSegmentTree::Initialize(PersistentTableData &data, optional_ptr> RowGroupSegmentTree::LoadSegment() const { if (current_row_group >= max_row_group) { reader.reset(); @@ -146,7 +156,8 @@ RowGroupCollection::RowGroupCollection(shared_ptr info_p, BlockMa // If the table contains shredded types (variant / geometry) then we can't append to an existing row group for (auto &type : types) { if (TypeVisitor::Contains(type, LogicalTypeId::VARIANT) || - TypeVisitor::Contains(type, LogicalTypeId::GEOMETRY)) { + TypeVisitor::Contains(type, LogicalTypeId::GEOMETRY) || + TypeVisitor::Contains(type, LogicalTypeId::GEOGRAPHY)) { row_group_append_mode = RowGroupAppendMode::REQUIRE_NEW; can_append_to_checkpointed_row_group = false; break; @@ -167,6 +178,11 @@ idx_t RowGroupCollection::GetRowGroupCount() const { return row_groups->GetSegmentCount(); } +idx_t RowGroupCollection::GetRowGroupCountWithoutLoading() const { + auto row_groups = GetRowGroups(); + return row_groups->GetRowGroupCountWithoutLoading(); +} + const vector &RowGroupCollection::GetTypes() const { return types; } @@ -1031,6 +1047,7 @@ void RowGroupCollection::Update(TransactionData transaction, DuckTableEntry &tab D_ASSERT(updates.size() >= 1); idx_t pos = 0; auto row_groups = GetRowGroups(); + vector> updated_row_groups; do { idx_t start = pos; auto row_group = NextUpdateRowGroup(*row_groups, ids, pos, updates.size()); @@ -1038,17 +1055,21 @@ void RowGroupCollection::Update(TransactionData transaction, DuckTableEntry &tab auto ¤t_row_group = row_group->GetNode(); current_row_group.Update(transaction, table_entry, updates, ids, start, pos - start, column_ids, row_group->GetRowStart()); + if (updated_row_groups.empty() || &updated_row_groups.back().get() != ¤t_row_group) { + updated_row_groups.push_back(current_row_group); + } + } while (pos < updates.size()); - auto l = stats.GetLock(); - for (idx_t i = 0; i < column_ids.size(); i++) { - auto column_id = column_ids[i]; + auto l = stats.GetLock(); + for (auto &row_group : updated_row_groups) { + for (auto &column_id : column_ids) { // Use EXPAND_BOUNDS here: the row group stats include original data already counted in collection stats, // so additive stats (like total_string_length) cannot be maintained correctly here. EXPAND_BOUNDS // correctly expands min/max bounds while invalidating total_string_length until the next checkpoint. - stats.MergeStats(*l, column_id.index, *current_row_group.GetStatistics(column_id.index), + stats.MergeStats(*l, column_id.index, *row_group.get().GetStatistics(column_id.index), StatsMergeType::EXPAND_BOUNDS); } - } while (pos < updates.size()); + } } void RowGroupCollection::RemoveFromIndexes(const QueryContext &context, TableIndexList &indexes, diff --git a/src/duckdb/src/storage/table/row_group_reorderer.cpp b/src/duckdb/src/storage/table/row_group_reorderer.cpp index 47bb46058..edeb03f2d 100644 --- a/src/duckdb/src/storage/table/row_group_reorderer.cpp +++ b/src/duckdb/src/storage/table/row_group_reorderer.cpp @@ -204,6 +204,25 @@ OffsetPruningResult FindOffsetPrunableChunks(It it, const End &end, const OrderB return {new_row_offset, pruned_row_group_count, 0}; } +//! Whether the first row_offset rows of a NULLS FIRST order contain every row that can be NULL +bool OffsetContainsAllNulls(vector &stats, const StorageIndex &storage_index, + const idx_t row_offset) { + idx_t maybe_null_rows = 0; + for (auto &partition_stats : stats) { + if (!partition_stats.partition_row_group) { + return false; + } + auto column_stats = partition_stats.partition_row_group->GetColumnStatistics(storage_index); + if (!column_stats || column_stats->CanHaveNull()) { + maybe_null_rows += partition_stats.count; + } + if (maybe_null_rows > row_offset) { + return false; + } + } + return true; +} + } // namespace RowGroupReorderer::RowGroupReorderer(const RowGroupOrderOptions &options_p, TransactionData transaction_p) @@ -266,12 +285,16 @@ Value RowGroupReorderer::RetrieveStat(const BaseStatistics &stats, OrderByStatis throw InternalException("Unsupported OrderByColumnType"); } -OffsetPruningResult RowGroupReorderer::GetOffsetAfterPruning(const OrderByStatistics order_by, - const OrderByColumnType column_type, - const OrderType order_type, - const OrderByNullType null_order, - const StorageIndex &storage_index, const idx_t row_offset, - vector &stats) { +OffsetPruningResult +RowGroupReorderer::GetOffsetAfterPruning(const OrderByStatistics order_by, const OrderByColumnType column_type, + const OrderType order_type, const OrderByNullType null_order, + const StorageIndex &storage_index, const idx_t row_offset, + vector &stats, const bool has_secondary_order) { + if (has_secondary_order && null_order == OrderByNullType::NULLS_FIRST && + !OffsetContainsAllNulls(stats, storage_index, row_offset)) { + // A secondary order sorts the NULLs of all row groups, so we cannot skip only a part of them + return {row_offset, 0, 0}; + } multimap ordered_row_groups; idx_t new_row_offset = row_offset; idx_t leading_null_group_offset = 0; diff --git a/src/duckdb/src/storage/table/row_id_column_data.cpp b/src/duckdb/src/storage/table/row_id_column_data.cpp index 75ac97037..bfb9f0e11 100644 --- a/src/duckdb/src/storage/table/row_id_column_data.cpp +++ b/src/duckdb/src/storage/table/row_id_column_data.cpp @@ -194,7 +194,7 @@ void RowIdColumnData::VisitBlockIds(BlockIdVisitor &visitor) const { throw InternalException("VisitBlockIds not supported for rowid"); } -unique_ptr RowIdColumnData::CreateCheckpointState(const RowGroup &row_group, +unique_ptr RowIdColumnData::CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) { throw InternalException("RowIdColumnData cannot be checkpointed"); } diff --git a/src/duckdb/src/storage/table/row_number_column_data.cpp b/src/duckdb/src/storage/table/row_number_column_data.cpp index 6d081eca7..678358464 100644 --- a/src/duckdb/src/storage/table/row_number_column_data.cpp +++ b/src/duckdb/src/storage/table/row_number_column_data.cpp @@ -113,7 +113,8 @@ void RowNumberColumnData::VisitBlockIds(BlockIdVisitor &visitor) const { } unique_ptr -RowNumberColumnData::CreateCheckpointState(const RowGroup &row_group, PartialBlockManager &partial_block_manager) { +RowNumberColumnData::CreateCheckpointState(const RowGroup &row_group, Context &context, + PartialBlockManager &partial_block_manager) { throw InternalException("RowNumberColumnData cannot be checkpointed"); } diff --git a/src/duckdb/src/storage/table/scan_state.cpp b/src/duckdb/src/storage/table/scan_state.cpp index 5ba7a5573..b5bbc087a 100644 --- a/src/duckdb/src/storage/table/scan_state.cpp +++ b/src/duckdb/src/storage/table/scan_state.cpp @@ -9,6 +9,11 @@ #include "duckdb/storage/table/row_group_collection.hpp" #include "duckdb/storage/table/row_group_segment_tree.hpp" #include "duckdb/common/numeric_utils.hpp" +#include "duckdb/common/array.hpp" +#include "duckdb/storage/block_allocator.hpp" +#include "duckdb/storage/buffer/block_handle.hpp" + +#include namespace duckdb { @@ -380,6 +385,142 @@ void CollectionScanState::InitializeColumnScans() { } } +bool CollectionScanState::InitializeRowGroupScan(SegmentNode &node, shared_ptr payload, + idx_t vector_offset, idx_t end_row) { + if (!payload->CheckZonemap(context.GetClientContext(), GetFilterInfo(), node.GetRowStart())) { + return false; + } + D_ASSERT(prepared_vector.prepare_state == VectorPrepareState::NONE); + prepared_vector.Reset(); + assignment_io_registered = false; + row_group = node; + pinned_row_group = std::move(payload); + vector_index = vector_offset; + max_row_group_row = end_row; + if (max_row_group_row == 0) { + return false; + } + D_ASSERT(!column_scans.empty()); + return true; +} + +RowGroupScanAssignment CollectionScanState::GetAssignment() const { + D_ASSERT(row_group); + D_ASSERT(prepared_vector.prepare_state == VectorPrepareState::NONE); + D_ASSERT(!assignment_io_registered); + RowGroupScanAssignment result; + result.context = context; + result.row_groups = row_groups; + result.row_group = row_group; + result.pinned_row_group = pinned_row_group; + result.vector_index = vector_index; + result.max_row_group_row = max_row_group_row; + return result; +} + +idx_t RowGroupScanAssignment::RowCount() const { + const auto start_row = vector_index * STANDARD_VECTOR_SIZE; + return max_row_group_row > start_row ? max_row_group_row - start_row : 0; +} + +TableScanAssignment::TableScanAssignment(const CollectionScanState &scan_state, TableScanSource source_p) + : row_group(scan_state.GetAssignment()), source(source_p) { +} + +bool CollectionScanState::SetAssignment(const RowGroupScanAssignment &assignment) { + D_ASSERT(assignment.row_group); + D_ASSERT(assignment.pinned_row_group); + ReleasePins(); + if (column_scans.empty()) { + Initialize(assignment.context, assignment.pinned_row_group->GetCollection().GetTypes()); + } + AssignSharedPointer(row_groups, assignment.row_groups); + auto node = assignment.row_group; + max_row = node->GetRowStart() + assignment.max_row_group_row; + if (!InitializeRowGroupScan(*node, assignment.pinned_row_group, assignment.vector_index, + assignment.max_row_group_row)) { + return false; + } + column_scans_pending = true; + InitializeColumnScans(); + return true; +} + +bool CollectionScanState::SupportsAssignmentBlockDiscovery(const vector &column_ids, + const vector &types) { + // Assignment discovery currently supports only flat, non-virtual columns. + for (const auto &column : column_ids) { + if (IsVirtualColumn(column.GetPrimaryIndex())) { + return false; + } + const auto &type = types[column.GetPrimaryIndex()]; + if (type.IsNested() || type.id() == LogicalTypeId::VARIANT || type.id() == LogicalTypeId::GEOMETRY) { + return false; + } + } + return true; +} + +void CollectionScanState::PrepareAssignmentBlocks(PrefetchState &blocks, vector> &tasks, + bool prefetch) { + D_ASSERT(GetRowGroup()); + D_ASSERT(SupportsAssignmentBlockDiscovery(GetColumnIds(), pinned_row_group->GetCollection().GetTypes())); + InitializeColumnScans(); + pinned_row_group->CollectAssignmentBlocks(*this, blocks); + if (prefetch) { + tasks = pinned_row_group->GetBlockManager().buffer_manager.CreatePrefetchTasks(context, blocks.blocks); + } +} + +optional_idx PrefetchState::GetCachedShard(BlockAllocator &allocator) { + array weights {}; + if (allocator.GetPoolShardCount() > weights.size()) { + return optional_idx(); + } + // Reuse the retained handles to count each allocation once without temporary hash storage. + std::sort(blocks.begin(), blocks.end(), + [](const shared_ptr &left, const shared_ptr &right) { + return left->BlockId() < right->BlockId(); + }); + block_id_t previous = INVALID_BLOCK; + optional_idx best; + idx_t best_weight = 0; + for (auto &block : blocks) { + if (block->BlockId() == previous) { + continue; + } + previous = block->BlockId(); + auto &memory = block->GetMemory(); + auto lock = memory.GetLock(); + if (memory.GetState() != BlockState::BLOCK_LOADED) { + continue; + } + auto shard = allocator.GetAllocationShard(memory.GetBuffer(lock)->InternalBuffer()); + if (!shard.IsValid()) { + continue; + } + const auto index = shard.GetIndex(); + D_ASSERT(index < weights.size()); + if (++weights[index] > best_weight) { + best = index; + best_weight = weights[index]; + } + } + return best; +} + +bool TableScanState::StartAssignment(const TableScanAssignment &assignment, bool prefetch_attempted) { + const auto local = assignment.source == TableScanSource::TRANSACTION_LOCAL; + auto &inactive = local ? table_state : local_state; + inactive.ReleasePins(); + auto &active = local ? local_state : table_state; + if (!active.SetAssignment(assignment.row_group)) { + return false; + } + active.assignment_io_registered = !local && prefetch_attempted; + return true; +} + void TableScanState::InitializeColumnScans() { table_state.InitializeColumnScans(); local_state.InitializeColumnScans(); diff --git a/src/duckdb/src/storage/table/standard_column_data.cpp b/src/duckdb/src/storage/table/standard_column_data.cpp index d9880aa76..c9170845b 100644 --- a/src/duckdb/src/storage/table/standard_column_data.cpp +++ b/src/duckdb/src/storage/table/standard_column_data.cpp @@ -88,17 +88,23 @@ void StandardColumnData::Filter(TransactionData transaction, idx_t vector_index, auto scan_type = GetVectorScanType(state, target_count, result); bool scan_entire_vector = scan_type == ScanVectorType::SCAN_ENTIRE_VECTOR; bool verify_fetch_row = state.scan_options && state.scan_options->force_fetch_row; - if (!has_filter || !validity_has_filter || !scan_entire_vector || verify_fetch_row || filter_state.can_throw) { - // we are not scanning an entire vector - this can have several causes (updates, etc) - // a filter that can throw is excluded as well: the compression-level filters evaluate it over the distinct - // values of the segment (e.g. the dictionary, or the RLE runs), which includes values of rows that another - // filter already removed - pushing the filter down there must not raise errors that would not occur otherwise + if (!has_filter || !validity_has_filter || !scan_entire_vector || verify_fetch_row || !filter_state.can_cache) { + // Cached evaluation requires safe predicates and complete value validity. + ColumnData::Filter(transaction, vector_index, state, result, sel, count, filter, filter_state); + return; + } + bool needs_row_validity = false; + if (!filter_includes_validity) { + lock_guard guard(stats_lock); + needs_row_validity = state.current->GetNode().GetStats().CanHaveNull(); + } + if (needs_row_validity) { ColumnData::Filter(transaction, vector_index, state, result, sel, count, filter, filter_state); return; } FilterVector(state, result, target_count, sel, count, filter, filter_state); if (!filter_includes_validity) { - validity->FilterVector(state.child_states[0], result, target_count, sel, count, filter, filter_state); + validity->ScanVector(state.child_states[0], result, target_count, scan_type); } else { validity->Skip(state.child_states[0], target_count); } @@ -231,9 +237,9 @@ ValidityColumnData &StandardColumnData::GetValidityData() { } struct StandardColumnCheckpointState : public ColumnCheckpointState { - StandardColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, + StandardColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, Context &context, PartialBlockManager &partial_block_manager) - : ColumnCheckpointState(row_group, column_data, partial_block_manager) { + : ColumnCheckpointState(row_group, column_data, context, partial_block_manager) { } unique_ptr validity_state; @@ -268,8 +274,9 @@ struct StandardColumnCheckpointState : public ColumnCheckpointState { }; unique_ptr -StandardColumnData::CreateCheckpointState(const RowGroup &row_group, PartialBlockManager &partial_block_manager) { - return make_uniq(row_group, *this, partial_block_manager); +StandardColumnData::CreateCheckpointState(const RowGroup &row_group, Context &context, + PartialBlockManager &partial_block_manager) { + return make_uniq(row_group, *this, context, partial_block_manager); } unique_ptr StandardColumnData::Checkpoint(const RowGroup &row_group, @@ -281,9 +288,10 @@ unique_ptr StandardColumnData::Checkpoint(const RowGroup // this is necessary for concurrent checkpointing as due to the partial block manager checkpointed data might be // flushed to disk by a different thread than the one that wrote it, causing a data race auto &partial_block_manager = checkpoint_info.GetPartialBlockManager(); - auto base_state = CreateCheckpointState(row_group, partial_block_manager); + auto &context = checkpoint_info.GetContext(); + auto base_state = CreateCheckpointState(row_group, context, partial_block_manager); base_state->global_stats = BaseStatistics::CreateEmpty(type).ToUnique(); - auto validity_state_p = validity->CreateCheckpointState(row_group, partial_block_manager); + auto validity_state_p = validity->CreateCheckpointState(row_group, context, partial_block_manager); validity_state_p->global_stats = BaseStatistics::CreateEmpty(validity->type).ToUnique(); auto &validity_state = *validity_state_p; diff --git a/src/duckdb/src/storage/table/struct_column_data.cpp b/src/duckdb/src/storage/table/struct_column_data.cpp index 44813294f..3e47b3bb7 100644 --- a/src/duckdb/src/storage/table/struct_column_data.cpp +++ b/src/duckdb/src/storage/table/struct_column_data.cpp @@ -1,4 +1,5 @@ #include "duckdb/storage/table/struct_column_data.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/storage/statistics/struct_stats.hpp" @@ -344,13 +345,14 @@ void StructColumnData::FetchRows(TransactionData transaction, ColumnFetchState & auto &child_type = StructType::GetChildTypes(type)[child_index].second; if (!child_storage_index.HasChildren() && child_storage_index.HasType() && child_storage_index.GetType() != child_type) { - auto context = transaction.transaction->context.lock(); + auto &cast_set = CastFunctionSet::Get(GetDatabase()); + auto cast_input = GetCastFunctionInput::Default(); for (idx_t idx = 0; idx < fetch_count; idx++) { const idx_t offset = offsets[sel.get_index(idx)]; Vector intermediate(child_type, 1); sub_column.FetchRows(transaction, state, child_storage_index, &offset, *FlatVector::IncrementalSelectionVector(), /*count=*/1, intermediate, 0); - auto fetched_row = intermediate.GetValue(0).CastAs(*context, result.GetType()); + auto fetched_row = intermediate.GetValue(0).CastAs(cast_set, cast_input, result.GetType()); result.SetValue(result_offset + idx, fetched_row); } return; @@ -416,9 +418,9 @@ const BaseStatistics &StructColumnData::GetChildStats(const ColumnData &child) c } struct StructColumnCheckpointState : public ColumnCheckpointState { - StructColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, + StructColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, Context &context, PartialBlockManager &partial_block_manager) - : ColumnCheckpointState(row_group, column_data, partial_block_manager) { + : ColumnCheckpointState(row_group, column_data, context, partial_block_manager) { global_stats = StructStats::CreateEmpty(column_data.type).ToUnique(); } @@ -463,16 +465,17 @@ struct StructColumnCheckpointState : public ColumnCheckpointState { } }; -unique_ptr StructColumnData::CreateCheckpointState(const RowGroup &row_group, +unique_ptr StructColumnData::CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) { - return make_uniq(row_group, *this, partial_block_manager); + return make_uniq(row_group, *this, context, partial_block_manager); } unique_ptr StructColumnData::Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &checkpoint_info, const BaseStatistics &old_stats) { auto &partial_block_manager = checkpoint_info.GetPartialBlockManager(); - auto checkpoint_state = make_uniq(row_group, *this, partial_block_manager); + auto &context = checkpoint_info.GetContext(); + auto checkpoint_state = make_uniq(row_group, *this, context, partial_block_manager); checkpoint_state->validity_state = validity->Checkpoint(row_group, checkpoint_info, old_stats); for (idx_t col_idx = 0; col_idx < sub_columns.size(); col_idx++) { diff --git a/src/duckdb/src/storage/table/validity_column_data.cpp b/src/duckdb/src/storage/table/validity_column_data.cpp index 6399ef004..0ca346de0 100644 --- a/src/duckdb/src/storage/table/validity_column_data.cpp +++ b/src/duckdb/src/storage/table/validity_column_data.cpp @@ -1,5 +1,6 @@ #include "duckdb/storage/table/validity_column_data.hpp" #include "duckdb/storage/table/column_checkpoint_state.hpp" +#include "duckdb/storage/table/scan_state.hpp" namespace duckdb { @@ -13,6 +14,51 @@ ValidityColumnData::ValidityColumnData(BlockManager &block_manager, DataTableInf : ValidityColumnData(block_manager, info, column_index, parent.GetDataType(), parent) { } +template +static void ScanValidityMask(ColumnSegment &segment, Vector &result, idx_t count, ScanVectorType scan_type, + SCAN &&scan) { + if (count == 0) { + return; + } + if (scan_type == ScanVectorType::SCAN_ENTIRE_VECTOR) { + if (segment.GetCompressionFunction().type == CompressionType::COMPRESSION_CONSTANT) { + if (!segment.GetStats().CanHaveNull()) { + return; + } + if (result.GetType().InternalType() == PhysicalType::STRUCT || + result.GetVectorType() == VectorType::CONSTANT_VECTOR) { + ConstantVector::SetNull(result, count_t(count)); + return; + } + } + result.Flatten(); + } + scan(FlatVector::ValidityMutable(result)); +} + +void ValidityColumnData::ScanValidity(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, + Vector &result) { + ScanValidityMask(segment, result, scan_count, ScanVectorType::SCAN_ENTIRE_VECTOR, [&](ValidityMask &mask) { + segment.GetCompressionFunction().scan_validity(segment, state, scan_count, mask, 0, + ScanVectorType::SCAN_ENTIRE_VECTOR); + }); +} + +void ValidityColumnData::ScanPartialValidity(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, + Vector &result, idx_t result_offset) { + segment.GetCompressionFunction().scan_validity(segment, state, scan_count, FlatVector::ValidityMutable(result), + result_offset, ScanVectorType::SCAN_FLAT_VECTOR); +} + +void ValidityColumnData::SelectValidity(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, + Vector &result, const SelectionVector &sel, idx_t sel_count, + idx_t result_offset, ScanVectorType scan_type) { + ScanValidityMask(segment, result, sel_count, scan_type, [&](ValidityMask &mask) { + segment.GetCompressionFunction().select_validity(segment, state, vector_count, mask, sel, sel_count, + result_offset); + }); +} + void ValidityColumnData::UpdateWithBase(TransactionData transaction, DuckTableEntry &table_entry, idx_t column_index, Vector &update_vector, row_t *row_ids, idx_t update_count, ColumnData &base, idx_t row_group_start) { @@ -39,9 +85,9 @@ void ValidityColumnData::AppendData(ColumnAppendState &state, UnifiedVectorForma } struct ValidityColumnCheckpointState : public ColumnCheckpointState { - ValidityColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, + ValidityColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, Context &context, PartialBlockManager &partial_block_manager) - : ColumnCheckpointState(row_group, column_data, partial_block_manager) { + : ColumnCheckpointState(row_group, column_data, context, partial_block_manager) { } public: @@ -53,8 +99,9 @@ struct ValidityColumnCheckpointState : public ColumnCheckpointState { }; unique_ptr -ValidityColumnData::CreateCheckpointState(const RowGroup &row_group, PartialBlockManager &partial_block_manager) { - return make_uniq(row_group, *this, partial_block_manager); +ValidityColumnData::CreateCheckpointState(const RowGroup &row_group, Context &context, + PartialBlockManager &partial_block_manager) { + return make_uniq(row_group, *this, context, partial_block_manager); } void ValidityColumnData::Verify(RowGroup &parent) { diff --git a/src/duckdb/src/storage/table/variant/variant_shredding.cpp b/src/duckdb/src/storage/table/variant/variant_shredding.cpp index 0d9e8fff1..a979eb448 100644 --- a/src/duckdb/src/storage/table/variant/variant_shredding.cpp +++ b/src/duckdb/src/storage/table/variant/variant_shredding.cpp @@ -75,6 +75,8 @@ struct VariantStatsVisitor { } static void VisitGeometry(const string_t &geom, VariantShreddingStats &stats, idx_t stats_column_index) { } + static void VisitGeography(const string_t &geog, VariantShreddingStats &stats, idx_t stats_column_index) { + } static void VisitBitstring(const string_t &bits, VariantShreddingStats &stats, idx_t stats_column_index) { } @@ -221,6 +223,8 @@ static unordered_set GetVariantType(const LogicalType &type) return {VariantLogicalType::BITSTRING}; case LogicalTypeId::GEOMETRY: return {VariantLogicalType::GEOMETRY}; + case LogicalTypeId::GEOGRAPHY: + return {VariantLogicalType::GEOGRAPHY}; default: throw BinderException("Type '%s' can't be translated to a VARIANT type", type.ToString()); } @@ -387,6 +391,8 @@ static LogicalType ProduceShreddedType(VariantLogicalType type_id) { return LogicalTypeId::BIT; case VariantLogicalType::GEOMETRY: return LogicalTypeId::GEOMETRY; + case VariantLogicalType::GEOGRAPHY: + return LogicalTypeId::GEOGRAPHY; case VariantLogicalType::OBJECT: case VariantLogicalType::ARRAY: throw InternalException("Already handled above"); diff --git a/src/duckdb/src/storage/table/variant_column_data.cpp b/src/duckdb/src/storage/table/variant_column_data.cpp index e59695a34..495b15251 100644 --- a/src/duckdb/src/storage/table/variant_column_data.cpp +++ b/src/duckdb/src/storage/table/variant_column_data.cpp @@ -6,12 +6,15 @@ #include "duckdb/common/serializer/deserializer.hpp" #include "duckdb/common/type_visitor.hpp" #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/geometry.hpp" #include "duckdb/common/types/variant_iterator.hpp" #include "duckdb/function/variant/variant_shredding.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/main/attached_database.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/storage/statistics/struct_stats.hpp" #include "duckdb/storage/statistics/variant_stats.hpp" +#include "duckdb/storage/storage_manager.hpp" #include "duckdb/storage/table/append_state.hpp" #include "duckdb/storage/table/column_checkpoint_state.hpp" #include "duckdb/storage/table/data_table_info.hpp" @@ -563,8 +566,9 @@ void VariantColumnData::FetchRows(TransactionData transaction, ColumnFetchState } //! Need to perform the cast here as well - auto context = transaction.transaction->context.lock(); - auto fetched_row = extracted_variant.GetValue(0).CastAs(*context, result.GetType()); + auto &cast_set = CastFunctionSet::Get(GetDatabase()); + auto cast_input = GetCastFunctionInput::Default(); + auto fetched_row = extracted_variant.GetValue(0).CastAs(cast_set, cast_input, result.GetType()); result.SetValue(result_idx, fetched_row); } } @@ -596,9 +600,9 @@ void VariantColumnData::SetChildData(vector> child_data) } struct VariantColumnCheckpointState : public ColumnCheckpointState { - VariantColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, + VariantColumnCheckpointState(const RowGroup &row_group, ColumnData &column_data, Context &context, PartialBlockManager &partial_block_manager) - : ColumnCheckpointState(row_group, column_data, partial_block_manager) { + : ColumnCheckpointState(row_group, column_data, context, partial_block_manager) { global_stats = VariantStats::CreateEmpty(column_data.type).ToUnique(); } @@ -608,6 +612,10 @@ struct VariantColumnCheckpointState : public ColumnCheckpointState { vector> child_states; public: + bool IsShredded() const { + return child_states.size() == 2; + } + shared_ptr CreateEmptyColumnData() override { return make_shared_ptr(original_column.GetBlockManager(), original_column.GetTableInfo(), original_column.column_index, original_column.type, @@ -633,15 +641,17 @@ struct VariantColumnCheckpointState : public ColumnCheckpointState { D_ASSERT(global_stats); global_stats->Merge(*validity_state->GetStatistics()); VariantStats::SetUnshreddedStats(*global_stats, child_states[0]->GetStatistics()); - if (child_states.size() == 2) { + if (IsShredded()) { VariantStats::SetShreddedStats(*global_stats, child_states[1]->GetStatistics()); + } else { + VariantStats::MarkAsNotShredded(*global_stats); } return std::move(global_stats); } PersistentColumnData ToPersistentData() override { PersistentColumnData data(original_column.type); - if (child_states.size() == 2) { + if (IsShredded()) { //! Use the type of the column data we used to create the Checkpoint //! This will either be a pointer to shredded_data[1] if we decided to shred //! Or to the existing shredded column data if we didn't decide to reshred @@ -656,9 +666,9 @@ struct VariantColumnCheckpointState : public ColumnCheckpointState { } }; -unique_ptr VariantColumnData::CreateCheckpointState(const RowGroup &row_group, +unique_ptr VariantColumnData::CreateCheckpointState(const RowGroup &row_group, Context &context, PartialBlockManager &partial_block_manager) { - return make_uniq(row_group, *this, partial_block_manager); + return make_uniq(row_group, *this, context, partial_block_manager); } static void AppendShredded(Vector &input, Vector &append_vector, idx_t count, VariantShreddedAppendInput &append_data) { @@ -790,7 +800,8 @@ unique_ptr VariantColumnData::Checkpoint(const RowGroup & ColumnCheckpointInfo &checkpoint_info, const BaseStatistics &old_stats) { auto &partial_block_manager = checkpoint_info.GetPartialBlockManager(); - auto checkpoint_state = make_uniq(row_group, *this, partial_block_manager); + auto &context = checkpoint_info.GetContext(); + auto checkpoint_state = make_uniq(row_group, *this, context, partial_block_manager); checkpoint_state->validity_state = validity->Checkpoint(row_group, checkpoint_info, old_stats); auto &table_info = row_group.GetTableInfo(); @@ -824,6 +835,11 @@ unique_ptr VariantColumnData::Checkpoint(const RowGroup & //! We couldn't determine a shredding type from the data should_shred = false; } + if (TypeVisitor::Contains(shredded_type, LogicalTypeId::GEOGRAPHY) && + db.GetStorageManager().GetStorageVersion() < Geometry::GEOGRAPHY_VERSION_ADDED) { + //! GEOGRAPHY cannot be written to the storage versions that predate it + should_shred = false; + } } if (!should_shred) { @@ -913,6 +929,7 @@ void VariantColumnData::InitializeColumn(PersistentColumnData &column_data, Base } else { auto &unshredded_stats = VariantStats::GetUnshreddedStats(target_stats); sub_columns[0]->InitializeColumn(column_data.child_columns[1], unshredded_stats); + VariantStats::MarkAsNotShredded(target_stats); } this->count = validity->count.load(); } diff --git a/src/duckdb/src/storage/wal_replay.cpp b/src/duckdb/src/storage/wal_replay.cpp index 582dccfb5..e165398b8 100644 --- a/src/duckdb/src/storage/wal_replay.cpp +++ b/src/duckdb/src/storage/wal_replay.cpp @@ -489,7 +489,7 @@ unique_ptr WriteAheadLogReplayer::ReplayLog(unique_ptr WriteAheadLogReplayer::ReplayLog(unique_ptr().new_column.Type().HasPhysicalType()) { + throw DataCorruptionException("Corrupt WAL file: add column entry with a type that no column can have"); + } + if (table_info.alter_table_type == AlterTableType::ADD_FIELD && + !table_info.Cast().new_field.Type().HasPhysicalType()) { + throw DataCorruptionException("Corrupt WAL file: add field entry with a type that no column can have"); + } } alter_info.bind_mode = AlterBindMode::SKIP_BINDING; if (!alter_info.IsAddUniqueConstraint()) { @@ -1171,8 +1180,7 @@ void WriteAheadLogDeserializer::ReplayDropTrigger() { return; } if (table_name.empty()) { - throw InternalException("WAL replay: DROP TRIGGER entry has an empty table name for trigger %s", - info.GetQualifiedName().Name()); + throw DataCorruptionException("Corrupt WAL file: drop trigger entry is missing its base table"); } // the trigger lives in the same (possibly nested) schema as its base table auto &table = diff --git a/src/duckdb/src/storage/write_ahead_log.cpp b/src/duckdb/src/storage/write_ahead_log.cpp index e18f765e9..dace5860f 100644 --- a/src/duckdb/src/storage/write_ahead_log.cpp +++ b/src/duckdb/src/storage/write_ahead_log.cpp @@ -494,12 +494,6 @@ void WriteAheadLog::WriteRowGroupData(const PersistentCollectionData &data) { WriteAheadLogSerializer serializer(*this, WALType::ROW_GROUP_DATA); serializer.WriteProperty(101, "row_group_data", data); serializer.End(); - - // mark written blocks as checkpointed - auto &block_manager = GetDatabase().GetStorageManager().GetBlockManager(); - for (auto &block_id : data.GetBlockIds()) { - block_manager.MarkBlockAsCheckpointed(block_id); - } } void WriteAheadLog::WriteDelete(DataChunk &chunk) { diff --git a/src/duckdb/src/transaction/commit_state.cpp b/src/duckdb/src/transaction/commit_state.cpp index 7537081cd..bf872d292 100644 --- a/src/duckdb/src/transaction/commit_state.cpp +++ b/src/duckdb/src/transaction/commit_state.cpp @@ -136,8 +136,7 @@ void IndexDataRemover::Flush(DataTable &table, row_t *row_numbers, idx_t count) CommitState::CommitState(DuckTransaction &transaction_p, transaction_t commit_id, ActiveTransactionState transaction_state, CommitMode commit_mode) : transaction(transaction_p), commit_id(commit_id), - index_data_remover(transaction, *transaction.context.lock(), - GetIndexRemovalType(transaction_state, commit_mode)) { + index_data_remover(transaction, QueryContext(), GetIndexRemovalType(transaction_state, commit_mode)) { D_ASSERT(commit_mode != CommitMode::COMMIT || IsCommitted(commit_id)); } diff --git a/src/duckdb/src/transaction/duck_transaction.cpp b/src/duckdb/src/transaction/duck_transaction.cpp index 1c2d2197e..e3587e7e4 100644 --- a/src/duckdb/src/transaction/duck_transaction.cpp +++ b/src/duckdb/src/transaction/duck_transaction.cpp @@ -3,6 +3,7 @@ #include "duckdb/transaction/commit_state.hpp" #include "duckdb/transaction/duck_transaction_manager.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/main/valid_checker.hpp" #include "duckdb/catalog/catalog_entry/duck_table_entry.hpp" @@ -18,6 +19,7 @@ #include "duckdb/transaction/update_info.hpp" #include "duckdb/transaction/local_storage.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/main/database.hpp" #include "duckdb/storage/table/column_data.hpp" #include "duckdb/main/client_data.hpp" #include "duckdb/main/query_profiler.hpp" @@ -35,11 +37,11 @@ TransactionData::TransactionData(transaction_t transaction_id_p, VisibilityBound : transaction(nullptr), view(transaction_id_p, visibility_bound_p) { } -DuckTransaction::DuckTransaction(DuckTransactionManager &manager, ClientContext &context_p, transaction_t start_time, +DuckTransaction::DuckTransaction(DuckTransactionManager &manager, Context &context, transaction_t start_time, SnapshotView view_p, idx_t catalog_version_p) - : Transaction(manager, context_p), start_time(start_time), view(view_p), commit_id(0), - catalog_version(catalog_version_p), awaiting_cleanup(false), undo_buffer(*this, context_p), - storage(make_uniq(context_p.GetContext(), *this)) { + : Transaction(manager, context), start_time(start_time), view(view_p), commit_id(0), + catalog_version(catalog_version_p), awaiting_cleanup(false), undo_buffer(*this, context.GetDatabase()), + storage(make_uniq(*this)) { D_ASSERT(IsCommitted(start_time) && !IsCommitted(view.transaction_id)); } @@ -202,13 +204,13 @@ bool DuckTransaction::ShouldWriteToWAL(AttachedDatabase &db) { return true; } -ErrorData DuckTransaction::PreFlushOptimisticBlocks(AttachedDatabase &db) noexcept { +ErrorData DuckTransaction::PreFlushOptimisticBlocks(ClientContext &context, AttachedDatabase &db) noexcept { ErrorData error; if (!ShouldWriteToWAL(db)) { return error; } try { - storage->FlushBulkAppendBlocksAndSync(db); + storage->FlushBulkAppendBlocksAndSync(context.GetContext(), db); } catch (std::exception &ex) { // fail the commit: the flush machinery cannot safely be re-run after an error, and a failed // fsync must not be retried (the retry can succeed without the data being durable) @@ -236,7 +238,7 @@ ErrorData DuckTransaction::AppendLocalStorage(ClientContext &context, AttachedDa } auto &profiler = QueryProfiler::Get(context.GetContext()); auto commit_timer = profiler.StartTimer(); - storage->Commit(commit_state.get()); + storage->Commit(context.GetContext(), commit_state.get()); commit_timer.EndTimer(); } catch (std::exception &ex) { // Call RevertCommit() outside this try-catch as it itself may throw @@ -273,7 +275,7 @@ ErrorData DuckTransaction::WriteToWAL(ClientContext &context, AttachedDatabase & return error_data; } -ErrorData DuckTransaction::Commit(AttachedDatabase &db, CommitInfo &commit_info, +ErrorData DuckTransaction::Commit(ClientContext &context, AttachedDatabase &db, CommitInfo &commit_info, unique_ptr commit_state) noexcept { this->commit_id = commit_info.commit_id; if (!ChangesMade()) { @@ -292,7 +294,7 @@ ErrorData DuckTransaction::Commit(AttachedDatabase &db, CommitInfo &commit_info, ErrorData error_data; try { - storage->Commit(commit_state.get()); + storage->Commit(context.GetContext(), commit_state.get()); undo_buffer.Commit(iterator_state, commit_info); if (!db.IsSystem() && !db.IsTemporary() && Settings::Get(db.GetDatabase())) { throw InvalidInputException("Forced commit failure (debug_force_commit_failure)"); @@ -302,7 +304,7 @@ ErrorData DuckTransaction::Commit(AttachedDatabase &db, CommitInfo &commit_info, // transaction there is nothing to share the sync with, so sync now under the transaction lock; // otherwise only write the marker and sync once the locks are released bool sync_now = commit_info.active_transactions == ActiveTransactionState::NO_OTHER_TRANSACTIONS; - commit_info.wal_sync_offset = commit_state->FlushCommit(sync_now); + commit_info.wal_sync_offset = commit_state->FlushCommit(commit_info.commit_id, sync_now); } drop_state.FinalizeCommit(); return ErrorData(); diff --git a/src/duckdb/src/transaction/duck_transaction_manager.cpp b/src/duckdb/src/transaction/duck_transaction_manager.cpp index 7a3efb701..706c70211 100644 --- a/src/duckdb/src/transaction/duck_transaction_manager.cpp +++ b/src/duckdb/src/transaction/duck_transaction_manager.cpp @@ -77,9 +77,8 @@ DuckTransactionManager &DuckTransactionManager::Get(AttachedDatabase &db) { return reinterpret_cast(transaction_manager); } -Transaction &DuckTransactionManager::StartTransaction(ClientContext &context) { +Transaction &DuckTransactionManager::StartTransaction(Context &context, MetaTransaction &meta_transaction) { // obtain the transaction lock during this function - auto &meta_transaction = MetaTransaction::Get(context); unique_lock start_lock(start_transaction_lock, std::defer_lock); if (!meta_transaction.IsReadOnly()) { start_lock.lock(); @@ -250,7 +249,7 @@ void DuckTransactionManager::Checkpoint(ClientContext &context, bool force) { lock_guard start_lock(start_transaction_lock); // wait until any active transactions are finished while (!lock) { - context.InterruptCheck(); + context.FastInterruptCheck(); lock = checkpoint_lock.TryGetExclusiveLock(); } } @@ -351,7 +350,7 @@ void DuckTransactionManager::CleanupTransactions() { ErrorData DuckTransactionManager::CommitTransaction(ClientContext &context, Transaction &transaction_p) { auto &transaction = transaction_p.Cast(); // flush the transaction-local blocks of bulk appends before taking any commit locks (see PreFlushOptimisticBlocks) - ErrorData error = transaction.PreFlushOptimisticBlocks(db); + ErrorData error = transaction.PreFlushOptimisticBlocks(context, db); unique_lock t_lock(transaction_lock); if (!db.IsSystem() && !db.IsTemporary()) { if (transaction.ChangesMade()) { @@ -448,7 +447,7 @@ ErrorData DuckTransactionManager::CommitTransaction(ClientContext &context, Tran } else { info.active_transactions = ActiveTransactionState::NO_OTHER_TRANSACTIONS; } - error = transaction.Commit(db, info, std::move(commit_state)); + error = transaction.Commit(context, db, info, std::move(commit_state)); } if (error.HasError()) { @@ -591,7 +590,7 @@ ErrorData DuckTransactionManager::CommitTransaction(ClientContext &context, Tran return error; } -void DuckTransactionManager::RollbackTransaction(Transaction &transaction_p) { +void DuckTransactionManager::RollbackTransaction(ClientContext &, Transaction &transaction_p) { auto &transaction = transaction_p.Cast(); DUCKDB_LOG(db.GetDatabase(), TransactionLogType, db, "Rollback", transaction.GetTransactionId()); diff --git a/src/duckdb/src/transaction/meta_transaction.cpp b/src/duckdb/src/transaction/meta_transaction.cpp index 42b31ecda..84c3d7118 100644 --- a/src/duckdb/src/transaction/meta_transaction.cpp +++ b/src/duckdb/src/transaction/meta_transaction.cpp @@ -10,11 +10,9 @@ namespace duckdb { -MetaTransaction::MetaTransaction(ClientContext &context_p, timestamp_t start_timestamp_p, - transaction_t transaction_id_p) - : context(context_p), start_timestamp(start_timestamp_p), global_transaction_id(transaction_id_p), - transaction_validity(*context_p.db), active_query(MAXIMUM_QUERY_ID), modified_database(nullptr), - is_read_only(false) { +MetaTransaction::MetaTransaction(DatabaseInstance &db, timestamp_t start_timestamp_p, transaction_t transaction_id_p) + : start_timestamp(start_timestamp_p), global_transaction_id(transaction_id_p), transaction_validity(db), + modified_database(nullptr), is_read_only(false) { } MetaTransaction::~MetaTransaction() = default; @@ -29,7 +27,7 @@ ValidChecker &ValidChecker::Get(MetaTransaction &transaction) { Transaction &Transaction::Get(ClientContext &context, AttachedDatabase &db) { auto &meta_transaction = MetaTransaction::Get(context); - return meta_transaction.GetTransaction(db); + return meta_transaction.GetTransaction(context, db); } optional_ptr Transaction::TryGet(ClientContext &context, AttachedDatabase &db) { @@ -57,15 +55,14 @@ optional_ptr MetaTransaction::TryGetTransaction(AttachedDatabase &d } } -Transaction &MetaTransaction::GetTransaction(AttachedDatabase &db) { +Transaction &MetaTransaction::GetTransaction(ClientContext &context, AttachedDatabase &db) { if (ValidChecker::IsInvalidated(db)) { throw IOException("%s", ValidChecker::InvalidatedMessage(db)); } lock_guard guard(lock); auto entry = transactions.find(db); if (entry == transactions.end()) { - auto &new_transaction = db.GetTransactionManager().StartTransaction(context); - new_transaction.active_query = active_query.load(); + auto &new_transaction = db.GetTransactionManager().StartTransaction(context.GetContext(), *this); #ifdef DEBUG VerifyAllTransactionsUnique(db, all_transactions); #endif @@ -80,7 +77,6 @@ Transaction &MetaTransaction::GetTransaction(AttachedDatabase &db) { return new_transaction; } else { - D_ASSERT(entry->second.transaction.active_query == active_query); return entry->second.transaction; } } @@ -116,7 +112,7 @@ Transaction &Transaction::Get(ClientContext &context, Catalog &catalog) { return Transaction::Get(context, catalog.GetAttached()); } -ErrorData MetaTransaction::Commit() { +ErrorData MetaTransaction::Commit(ClientContext &context) { ErrorData error; #ifdef DEBUG reference_set_t committed_tx; @@ -153,7 +149,7 @@ ErrorData MetaTransaction::Commit() { transaction_ref.state = error.HasError() ? TransactionState::ROLLED_BACK : TransactionState::COMMITTED; } else { // Rollback due to previous error. - transaction_manager.RollbackTransaction(transaction); + transaction_manager.RollbackTransaction(context, transaction); transaction_ref.state = TransactionState::ROLLED_BACK; } } catch (std::exception &ex) { @@ -164,7 +160,7 @@ ErrorData MetaTransaction::Commit() { return error; } -void MetaTransaction::Rollback() { +void MetaTransaction::Rollback(ClientContext &context) { // Rollback all transactions in reverse order. ErrorData error; for (idx_t i = all_transactions.size(); i > 0; i--) { @@ -182,7 +178,7 @@ void MetaTransaction::Rollback() { } try { auto &transaction = transaction_ref.transaction; - transaction_manager.RollbackTransaction(transaction); + transaction_manager.RollbackTransaction(context, transaction); } catch (std::exception &ex) { error.Merge(db.ScopeFatalError(ErrorData(ex))); } @@ -193,7 +189,7 @@ void MetaTransaction::Rollback() { } } -void MetaTransaction::Finalize() { +void MetaTransaction::Finalize(ClientContext &context) { // Try to checkpoint any attached databases potentially still held by this transaction. for (auto &database : referenced_databases) { // If the use count is down to one, then we already detached the database. @@ -202,18 +198,6 @@ void MetaTransaction::Finalize() { } } -idx_t MetaTransaction::GetActiveQuery() { - return active_query; -} - -void MetaTransaction::SetActiveQuery(transaction_t query_number) { - lock_guard guard(lock); - active_query = query_number; - for (auto &entry : transactions) { - entry.second.transaction.active_query = query_number; - } -} - optional_ptr MetaTransaction::GetReferencedDatabase(const Identifier &name) { lock_guard guard(referenced_database_lock); auto entry = used_databases.find(name); @@ -256,13 +240,14 @@ AttachedDatabase &MetaTransaction::UseDatabase(shared_ptr &dat return db_ref; } -void MetaTransaction::ModifyDatabase(AttachedDatabase &db, DatabaseModificationType modification) { +void MetaTransaction::ModifyDatabase(ClientContext &context, AttachedDatabase &db, + DatabaseModificationType modification) { // 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", db.GetName()); } - auto &transaction = GetTransaction(db); + auto &transaction = GetTransaction(context, db); if (transaction.IsReadOnly()) { transaction.SetReadWrite(); } diff --git a/src/duckdb/src/transaction/rollback_state.cpp b/src/duckdb/src/transaction/rollback_state.cpp index 58015d41b..93c0541eb 100644 --- a/src/duckdb/src/transaction/rollback_state.cpp +++ b/src/duckdb/src/transaction/rollback_state.cpp @@ -61,6 +61,9 @@ void RollbackState::RollbackEntry(UndoFlags type, data_ptr_t data) { if (deleter) { db_manager.AddPendingTeardown(std::move(deleter)); } + // the last release closes it, which may be the MetaTransaction finalizing later + attached_db->MarkDetached(DatabaseCloseAction::SKIP_CHECKPOINT); + AttachedDatabase::InvokeCloseIfLastReference(attached_db, DatabaseCloseAction::SKIP_CHECKPOINT); } break; } diff --git a/src/duckdb/src/transaction/transaction.cpp b/src/duckdb/src/transaction/transaction.cpp index 2cc292d83..275fcf94c 100644 --- a/src/duckdb/src/transaction/transaction.cpp +++ b/src/duckdb/src/transaction/transaction.cpp @@ -2,11 +2,11 @@ #include "duckdb/transaction/meta_transaction.hpp" #include "duckdb/transaction/transaction_manager.hpp" #include "duckdb/main/client_context.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { -Transaction::Transaction(TransactionManager &manager_p, ClientContext &context_p) - : manager(manager_p), context(context_p.shared_from_this()), active_query(MAXIMUM_QUERY_ID), is_read_only(true) { +Transaction::Transaction(TransactionManager &manager_p, Context &) : manager(manager_p), is_read_only(true) { } Transaction::~Transaction() { diff --git a/src/duckdb/src/transaction/transaction_context.cpp b/src/duckdb/src/transaction/transaction_context.cpp index 18717adc8..fbbff31a0 100644 --- a/src/duckdb/src/transaction/transaction_context.cpp +++ b/src/duckdb/src/transaction/transaction_context.cpp @@ -19,19 +19,6 @@ TransactionContext::TransactionContext(ClientContext &context) } TransactionContext::~TransactionContext() { - if (current_transaction) { - try { - Rollback(nullptr); - } catch (std::exception &ex) { - // a destructor cannot throw, and building the error message allocates - try { - ErrorData data(ex); - DUCKDB_LOG_ERROR(context, "TransactionContext::~TransactionContext()\t\t" + data.Message()); - } catch (...) { // NOLINT - } - } catch (...) { // NOLINT - } - } } void TransactionContext::BeginTransaction() { @@ -40,7 +27,7 @@ void TransactionContext::BeginTransaction() { } auto start_timestamp = Timestamp::GetCurrentTimestamp(); auto global_transaction_id = context.db->GetDatabaseManager().GetNewTransactionNumber(); - current_transaction = make_uniq(context, start_timestamp, global_transaction_id); + current_transaction = make_uniq(*context.db, start_timestamp, global_transaction_id); // Notify any registered state of transaction begin for (auto &state : context.GetContext().GetRegisteredState().States()) { @@ -67,7 +54,7 @@ void TransactionContext::Commit() { autocheckpoint_error = ErrorData(); auto transaction = std::move(current_transaction); ClearTransaction(); - auto error = transaction->Commit(); + auto error = transaction->Commit(context); // Notify any registered state of transaction commit if (error.HasError()) { for (auto const &s : context.GetContext().GetRegisteredState().States()) { @@ -82,7 +69,7 @@ void TransactionContext::Commit() { for (auto &state : context.GetContext().GetRegisteredState().States()) { state->TransactionCommit(*transaction, context); } - transaction->Finalize(); + transaction->Finalize(context); if (autocheckpoint_error.HasError()) { auto err = std::move(autocheckpoint_error); autocheckpoint_error = ErrorData(); @@ -110,7 +97,7 @@ void TransactionContext::Rollback(optional_ptr error) { ErrorData rollback_error; try { - transaction->Rollback(); + transaction->Rollback(context); } catch (std::exception &ex) { rollback_error = ErrorData(ex); } @@ -127,19 +114,20 @@ void TransactionContext::Rollback(optional_ptr error) { if (rollback_error.HasError()) { rollback_error.Throw(); } - transaction->Finalize(); + transaction->Finalize(context); } void TransactionContext::ClearTransaction() { SetAutoCommit(true); current_transaction = nullptr; + active_query_id = MAXIMUM_QUERY_ID; } idx_t TransactionContext::GetActiveQuery() { if (!current_transaction) { throw InternalException("GetActiveQuery called without active transaction"); } - return current_transaction->GetActiveQuery(); + return active_query_id; } void TransactionContext::ResetActiveQuery() { @@ -152,7 +140,7 @@ void TransactionContext::SetActiveQuery(transaction_t query_number) { if (!current_transaction) { throw InternalException("SetActiveQuery called without active transaction"); } - current_transaction->SetActiveQuery(query_number); + active_query_id = query_number; } } // namespace duckdb diff --git a/src/duckdb/src/transaction/undo_buffer.cpp b/src/duckdb/src/transaction/undo_buffer.cpp index 6d2aaf6ee..fe20a9345 100644 --- a/src/duckdb/src/transaction/undo_buffer.cpp +++ b/src/duckdb/src/transaction/undo_buffer.cpp @@ -21,8 +21,8 @@ namespace duckdb { constexpr uint32_t UNDO_ENTRY_HEADER_SIZE = sizeof(UndoFlags) + sizeof(uint32_t); -UndoBuffer::UndoBuffer(DuckTransaction &transaction_p, ClientContext &context_p) - : transaction(transaction_p), allocator(DatabaseInstance::GetDatabase(context_p).GetBufferManager(), true) { +UndoBuffer::UndoBuffer(DuckTransaction &transaction_p, DatabaseInstance &db) + : transaction(transaction_p), allocator(db.GetBufferManager(), true) { } UndoBufferReference UndoBuffer::CreateEntry(UndoFlags type, idx_t len) { diff --git a/src/duckdb/third_party/fastpforlib/bitpacking.cpp b/src/duckdb/third_party/fastpforlib/bitpacking.cpp index 91388868e..35fd2740a 100644 --- a/src/duckdb/third_party/fastpforlib/bitpacking.cpp +++ b/src/duckdb/third_party/fastpforlib/bitpacking.cpp @@ -2,6 +2,9 @@ #include #include +#include +#include +#include namespace duckdb_fastpforlib { namespace internal { @@ -171,16 +174,15 @@ struct Unroller16 { template struct Unroller { - static void Unpack(const uint32_t *__restrict &in, uint32_t *__restrict out) { - unpack_single_out(in, out + OINDEX); - - Unroller::Unpack(in, out); - } - - static void Unpack(const uint32_t *__restrict &in, uint64_t *__restrict out) { - unpack_single_out(in, out + OINDEX); - - Unroller::Unpack(in, out); + template + static void Unpack(const uint32_t *__restrict &in, T *__restrict out, T frame = T(0)) { + T value; + unpack_single_out(in, &value); + if constexpr (APPLY_FRAME) { + value += frame; + } + out[OINDEX] = value; + Unroller::template Unpack(in, out, frame); } static void Pack(const uint32_t *__restrict in, uint32_t *__restrict out) { @@ -200,16 +202,17 @@ template struct Unroller { enum { SHIFT = (DELTA * 31) % 32 }; - static void Unpack(const uint32_t *__restrict in, uint32_t *__restrict out) { - out[31] = (*in) >> SHIFT; - } - - static void Unpack(const uint32_t *__restrict in, uint64_t *__restrict out) { - out[31] = (*in) >> SHIFT; - if (DELTA > 32) { + template + static void Unpack(const uint32_t *__restrict in, T *__restrict out, T frame) { + T value = (*in) >> SHIFT; + if constexpr (sizeof(T) > sizeof(uint32_t) && DELTA > 32) { ++in; - out[31] |= static_cast(*in) << (32 - SHIFT); + value |= T(*in) << (32 - SHIFT); + } + if constexpr (APPLY_FRAME) { + value += frame; } + out[31] = value; } static void Pack(const uint32_t *__restrict in, uint32_t *__restrict out) { @@ -1280,5 +1283,54 @@ void __fastpack64(const uint64_t *__restrict in, uint32_t *__restrict out) { out[2 * i + 1] = in[i] >> 32; } } + +template +static void UnpackGroupsWithFrame(const uint32_t *__restrict input, T *__restrict output, T frame, size_t groups) { + for (size_t group = 0; group < groups; group++) { + if constexpr (WIDTH == 0) { + for (size_t i = 0; i < 32; i++) { + output[i] = APPLY_FRAME ? frame : T(0); + } + } else if constexpr (WIDTH == 32) { + for (size_t i = 0; i < 32; i++) { + output[i] = T(input[i]) + (APPLY_FRAME ? frame : T(0)); + } + } else if constexpr (WIDTH == 64) { + for (size_t i = 0; i < 32; i++) { + output[i] = (T(input[2 * i]) | (T(input[2 * i + 1]) << 32)) + (APPLY_FRAME ? frame : T(0)); + } + } else { + auto current = input; + Unroller::template Unpack(current, output, frame); + } + if constexpr (WIDTH != 0) { + input += WIDTH; + } + output += 32; + } +} + +template +static void UnpackWithFrame(const uint32_t *__restrict input, T *__restrict output, uint32_t width, T frame, size_t groups, + std::index_sequence) { + using unpack_function_t = void (*)(const uint32_t *, T *, T, size_t); + static constexpr unpack_function_t no_frame_functions[] = {UnpackGroupsWithFrame...}; + static constexpr unpack_function_t frame_functions[] = {UnpackGroupsWithFrame...}; + if (width >= sizeof...(WIDTH)) { + throw std::logic_error("Invalid bit width for bitpacking"); + } + const auto function = frame == 0 ? no_frame_functions[width] : frame_functions[width]; + function(input, output, frame, groups); +} } // namespace internal +void fastunpack_with_frame(const uint32_t *__restrict input, uint32_t *__restrict output, uint32_t width, + uint32_t frame, size_t groups) { + internal::UnpackWithFrame(input, output, width, frame, groups, std::make_index_sequence<33>()); +} + +void fastunpack_with_frame(const uint32_t *__restrict input, uint64_t *__restrict output, uint32_t width, + uint64_t frame, size_t groups) { + internal::UnpackWithFrame(input, output, width, frame, groups, std::make_index_sequence<65>()); +} + } // namespace duckdb_fastpforlib diff --git a/src/duckdb/third_party/fastpforlib/bitpacking.h b/src/duckdb/third_party/fastpforlib/bitpacking.h index a7d266baf..2957735de 100644 --- a/src/duckdb/third_party/fastpforlib/bitpacking.h +++ b/src/duckdb/third_party/fastpforlib/bitpacking.h @@ -6,6 +6,7 @@ */ #pragma once #include +#include #include // On macOS, sys/cdefs.h doesn't contain c++: @@ -20,6 +21,12 @@ #endif namespace duckdb_fastpforlib { +// Unpack groups of 32 unsigned residuals and add the frame before storing. +void fastunpack_with_frame(const uint32_t *__restrict input, uint32_t *__restrict output, uint32_t width, + uint32_t frame, std::size_t groups); +void fastunpack_with_frame(const uint32_t *__restrict input, uint64_t *__restrict output, uint32_t width, + uint64_t frame, std::size_t groups); + namespace internal { // Unpacks 8 uint8_t values diff --git a/src/duckdb/third_party/mbedtls/include/mbedtls/build_info.h b/src/duckdb/third_party/mbedtls/include/mbedtls/build_info.h index bca7d3ec5..61c75d142 100644 --- a/src/duckdb/third_party/mbedtls/include/mbedtls/build_info.h +++ b/src/duckdb/third_party/mbedtls/include/mbedtls/build_info.h @@ -26,16 +26,16 @@ */ #define MBEDTLS_VERSION_MAJOR 3 #define MBEDTLS_VERSION_MINOR 6 -#define MBEDTLS_VERSION_PATCH 7 +#define MBEDTLS_VERSION_PATCH 8 /** * The single version number has the following structure: * MMNNPP00 * Major version | Minor version | Patch version */ -#define MBEDTLS_VERSION_NUMBER 0x03060700 -#define MBEDTLS_VERSION_STRING "3.6.7" -#define MBEDTLS_VERSION_STRING_FULL "Mbed TLS 3.6.7" +#define MBEDTLS_VERSION_NUMBER 0x03060800 +#define MBEDTLS_VERSION_STRING "3.6.8" +#define MBEDTLS_VERSION_STRING_FULL "Mbed TLS 3.6.8" /* Macros for build-time platform detection */ diff --git a/src/duckdb/third_party/mbedtls/include/mbedtls/constant_time.h b/src/duckdb/third_party/mbedtls/include/mbedtls/constant_time.h index d31bff677..6ebcfbeb0 100644 --- a/src/duckdb/third_party/mbedtls/include/mbedtls/constant_time.h +++ b/src/duckdb/third_party/mbedtls/include/mbedtls/constant_time.h @@ -11,6 +11,10 @@ #include +#ifdef __cplusplus +extern "C" { +#endif + /** Constant-time buffer comparison without branches. * * This is equivalent to the standard memcmp function, but is likely to be @@ -33,4 +37,8 @@ int mbedtls_ct_memcmp(const void *a, const void *b, size_t n); +#ifdef __cplusplus +} +#endif + #endif /* MBEDTLS_CONSTANT_TIME_H */ diff --git a/src/duckdb/third_party/mbedtls/include/mbedtls/pem.h b/src/duckdb/third_party/mbedtls/include/mbedtls/pem.h index 3c6a28d98..f593f312e 100644 --- a/src/duckdb/third_party/mbedtls/include/mbedtls/pem.h +++ b/src/duckdb/third_party/mbedtls/include/mbedtls/pem.h @@ -67,6 +67,34 @@ void mbedtls_pem_init(mbedtls_pem_context *ctx); * \brief Read a buffer for PEM information and store the resulting * data into the specified context buffers. * + * \warning PEM decryption is inherently prone to oracle attacks. + * If an adversary can submit arbitrary ciphertexts and + * can observe whether they are accepted or rejected, + * the adversary may be able to decrypt ciphertexts without + * knowing the password. Furthermore, this function is + * not constant-time, which improves the adversary's + * efficiency. (Note also that subsequent processing after + * decryption is likely to improve the adversary's efficiency + * as well.) + * Therefore, PEM decryption should only be used in + * environments where the ciphertext comes from a trusted + * source (for example, a storage medium that may be stolen + * but is not at risk of silent modifications by an attacker). + * + * \warning PEM encryption uses an obsolete password protection + * mechanism that makes brute force attack fast. + * Therefore, the password used for encryption should be + * a sufficiently long, randomly generated string. + * + * \note To encrypt private keys, we recommend PKCS8 encryption, which + * is supported by TF-PSA-Crypto's PK module, is a + * significant improvement on the weaknesses of PEM encryption, + * and works equally well with PEM and binary (DER) encoding. + * + * \deprecated Encrypted PEM (with a non-null password) is deprecated, and + * should only be used to access legacy data in environemnts + * where it is safe. + * * \param ctx context to use * \param header header string to seek and expect * \param footer footer string to seek and expect @@ -79,10 +107,6 @@ void mbedtls_pem_init(mbedtls_pem_context *ctx); * MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT, use_len is * the length to skip. * - * \note Attempts to check password correctness by verifying if - * the decrypted text starts with an ASN.1 sequence of - * appropriate length - * * \note \c mbedtls_pem_free must be called on PEM context before * the PEM context can be reused in another call to * \c mbedtls_pem_read_buffer diff --git a/src/duckdb/third_party/mbedtls/library/aes.cpp b/src/duckdb/third_party/mbedtls/library/aes.cpp index 00d64c617..b172e53d0 100644 --- a/src/duckdb/third_party/mbedtls/library/aes.cpp +++ b/src/duckdb/third_party/mbedtls/library/aes.cpp @@ -51,7 +51,7 @@ #if defined(MBEDTLS_AESCE_C) #include "aesce.h" #endif - +#include "constant_time_internal.h" #include "ctr.h" /* @@ -70,6 +70,66 @@ static int aes_padlock_ace = -1; #endif +/* 1 if hardware support is present at runtime, 0 otherwise. + * Undefined macro if no hardware support code is enabled. + * + * This macro is only used for re-checking, so it can directly + * reference a variable, it doesn't need to call the checking code. + */ +#if defined(MBEDTLS_AESNI_HAVE_CODE) +#define MBEDTLS_AES_HAVE_HARDWARE \ + mbedtls_aesni_has_support(MBEDTLS_AESNI_AES) +#endif +#if defined(MBEDTLS_AESCE_HAVE_CODE) +#define MBEDTLS_AES_HAVE_HARDWARE MBEDTLS_AESCE_HAS_SUPPORT_RECHECK +#endif + +#if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) +#if !defined(MBEDTLS_AES_SETKEY_ENC_ALT) || \ + (!defined(MBEDTLS_AES_SETKEY_DEC_ALT) && !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT)) +/* Call this function before executing non-constant-time AES code + * (key schedule or block encryption/decryption). + * + * On platforms with speculative execution, the CPU may start + * executing the non-constant-time software fallback speculatively. + * This would leak part of the key or plaintext to a powerful local + * attacker who can observe precise memory access patterns. + * + * Calling this function sets `*pkey` to `NULL` if hardware AES + * is available. + */ +static void mbedtls_aes_key_block_speculation_of_no_hardware( + const unsigned char **pkey) +{ +#if defined(MBEDTLS_SPECTRE_V1_COUNTERMEASURES) && \ + defined(MBEDTLS_AES_HAVE_HARDWARE) + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(*pkey, MBEDTLS_AES_HAVE_HARDWARE, 0); +#else + (void) pkey; +#endif +} +#endif /* have setkey_enc or setkey_dec */ + +/* Same as mbedtls_aes_key_block_speculation_of_no_hardware(), + * but acts on a pointer to a context, not to a key. + * + * (The two functions are extremeley likely to have exactly the same code, + * but they act on pointers to different types, which are not compatible + * according to C rules, and lying about it could confuse the compiler's + * aliasing detection.) + */ +static void mbedtls_aes_ctx_block_speculation_of_no_hardware( + mbedtls_aes_context **pctx) +{ +#if defined(MBEDTLS_SPECTRE_V1_COUNTERMEASURES) && \ + defined(MBEDTLS_AES_HAVE_HARDWARE) + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(*pctx, MBEDTLS_AES_HAVE_HARDWARE, 0); +#else + (void) pctx; +#endif +} +#endif /* !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) */ + #if defined(MBEDTLS_AES_ROM_TABLES) /* * Forward S-box @@ -609,6 +669,8 @@ int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key, #endif #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) + mbedtls_aes_key_block_speculation_of_no_hardware(&key); + for (unsigned int i = 0; i < (keybits >> 5); i++) { RK[i] = MBEDTLS_GET_UINT32_LE(key, i << 2); } @@ -686,14 +748,10 @@ int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key, int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits) { -#if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) - uint32_t *SK; -#endif int ret; mbedtls_aes_context cty; uint32_t *RK; - mbedtls_aes_init(&cty); ctx->rk_offset = mbedtls_aes_rk_offset(ctx->buf); @@ -725,7 +783,11 @@ int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, #endif #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) - SK = cty.buf + cty.rk_offset + cty.nr * 4; + { + const unsigned char *SK_address = + (const unsigned char *) (cty.buf + cty.rk_offset + cty.nr * 4); + mbedtls_aes_key_block_speculation_of_no_hardware(&SK_address); + const uint32_t *SK = (const uint32_t *) SK_address; *RK++ = *SK++; *RK++ = *SK++; @@ -745,6 +807,7 @@ int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, *RK++ = *SK++; *RK++ = *SK++; *RK++ = *SK++; + } #endif /* !MBEDTLS_AES_USE_HARDWARE_ONLY */ exit: mbedtls_aes_free(&cty); @@ -1052,6 +1115,7 @@ int mbedtls_aes_crypt_ecb(mbedtls_aes_context *ctx, #endif #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) + mbedtls_aes_ctx_block_speculation_of_no_hardware(&ctx); #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) if (mode == MBEDTLS_AES_DECRYPT) { return mbedtls_internal_aes_decrypt(ctx, input, output); diff --git a/src/duckdb/third_party/mbedtls/library/aesce.h b/src/duckdb/third_party/mbedtls/library/aesce.h index a14d085ef..83730b0fb 100644 --- a/src/duckdb/third_party/mbedtls/library/aesce.h +++ b/src/duckdb/third_party/mbedtls/library/aesce.h @@ -47,6 +47,9 @@ int mbedtls_aesce_has_support_impl(void); #define MBEDTLS_AESCE_HAS_SUPPORT() (mbedtls_aesce_has_support_result == -1 ? \ mbedtls_aesce_has_support_impl() : \ mbedtls_aesce_has_support_result) +/* Access the variable directly. This means fewer branches and + * therefore fewer concerns about wrong speculation here. */ +#define MBEDTLS_AESCE_HAS_SUPPORT_RECHECK mbedtls_aesce_has_support_result #else /* defined(__linux__) && !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) */ @@ -57,6 +60,10 @@ int mbedtls_aesce_has_support_impl(void); #endif /* defined(__linux__) && !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) */ +#if !defined(MBEDTLS_AESCE_HAS_SUPPORT_RECHECK) +#define MBEDTLS_AESCE_HAS_SUPPORT_RECHECK MBEDTLS_AESCE_HAS_SUPPORT() +#endif + /** * \brief Internal AES-ECB block encryption and decryption * diff --git a/src/duckdb/third_party/mbedtls/library/alignment.h b/src/duckdb/third_party/mbedtls/library/alignment.h index 456629abf..534385355 100644 --- a/src/duckdb/third_party/mbedtls/library/alignment.h +++ b/src/duckdb/third_party/mbedtls/library/alignment.h @@ -297,7 +297,7 @@ static inline void mbedtls_put_unaligned_uint64(void *p, uint64_t x) /* * Detect GCC built-in byteswap routines */ -#if defined(__GNUC__) +#if defined(MBEDTLS_COMPILER_IS_GCC) #if MBEDTLS_GCC_VERSION >= 40800 #define MBEDTLS_BSWAP16 __builtin_bswap16 #endif @@ -305,7 +305,7 @@ static inline void mbedtls_put_unaligned_uint64(void *p, uint64_t x) #define MBEDTLS_BSWAP32 __builtin_bswap32 #define MBEDTLS_BSWAP64 __builtin_bswap64 #endif -#endif /* defined(__GNUC__) */ +#endif /* defined(MBEDTLS_COMPILER_IS_GCC) */ /* * Detect Clang built-in byteswap routines diff --git a/src/duckdb/third_party/mbedtls/library/bignum.cpp b/src/duckdb/third_party/mbedtls/library/bignum.cpp index 81637afb1..dde901fcf 100644 --- a/src/duckdb/third_party/mbedtls/library/bignum.cpp +++ b/src/duckdb/third_party/mbedtls/library/bignum.cpp @@ -2061,38 +2061,30 @@ int mbedtls_mpi_inv_mod(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi #if defined(MBEDTLS_GENPRIME) -static const mbedtls_mpi_sint small_primes_limit = 997; -/* Product of small primes up to small_primes_limit included */ -static const mbedtls_mpi_uint small_primes_product_limbs[] = { - MBEDTLS_BYTES_TO_T_UINT_8(0x4b, 0x13, 0x6a, 0x97, 0xbb, 0xd0, 0xdf, 0x95), - MBEDTLS_BYTES_TO_T_UINT_8(0xa7, 0x2c, 0x10, 0xa4, 0x20, 0xa4, 0x9f, 0x7b), - MBEDTLS_BYTES_TO_T_UINT_8(0x9d, 0x18, 0xd6, 0xdf, 0xc0, 0xf5, 0x61, 0x65), - MBEDTLS_BYTES_TO_T_UINT_8(0xfc, 0x35, 0x79, 0xfb, 0x30, 0xa8, 0xd5, 0xbf), - MBEDTLS_BYTES_TO_T_UINT_8(0xdb, 0x37, 0xba, 0x2c, 0xfb, 0xbb, 0x89, 0xfb), - MBEDTLS_BYTES_TO_T_UINT_8(0xad, 0xc2, 0x8c, 0x1d, 0x99, 0x18, 0xe8, 0xe5), - MBEDTLS_BYTES_TO_T_UINT_8(0x8d, 0x77, 0xc9, 0x5d, 0x96, 0x8a, 0x61, 0x9d), - MBEDTLS_BYTES_TO_T_UINT_8(0x39, 0x41, 0x3e, 0xf4, 0x34, 0x07, 0x57, 0xe0), - MBEDTLS_BYTES_TO_T_UINT_8(0x4a, 0xf1, 0x54, 0x3a, 0x43, 0x67, 0x46, 0xa2), - MBEDTLS_BYTES_TO_T_UINT_8(0x83, 0x0c, 0xe5, 0x31, 0xa2, 0xfc, 0x05, 0x45), - MBEDTLS_BYTES_TO_T_UINT_8(0xf0, 0x1d, 0x66, 0xfc, 0x7a, 0x85, 0x37, 0xe1), - MBEDTLS_BYTES_TO_T_UINT_8(0x17, 0xe0, 0x80, 0x62, 0x0d, 0xa2, 0xbc, 0x32), - MBEDTLS_BYTES_TO_T_UINT_8(0x6d, 0xce, 0x84, 0x68, 0x00, 0xb5, 0xe3, 0x35), - MBEDTLS_BYTES_TO_T_UINT_8(0x14, 0x19, 0x0d, 0xe4, 0x92, 0xd5, 0xd8, 0xdf), - MBEDTLS_BYTES_TO_T_UINT_8(0x20, 0x1c, 0x7d, 0x38, 0x3b, 0xe8, 0xd9, 0xa8), - MBEDTLS_BYTES_TO_T_UINT_8(0xf6, 0xac, 0x11, 0xe6, 0xb4, 0x03, 0xf7, 0x6c), - MBEDTLS_BYTES_TO_T_UINT_8(0x78, 0x3d, 0xf2, 0x3a, 0x8f, 0xf9, 0x2f, 0x6a), - MBEDTLS_BYTES_TO_T_UINT_8(0x7b, 0x72, 0x66, 0xa9, 0x48, 0xe4, 0x6d, 0x02), - MBEDTLS_BYTES_TO_T_UINT_8(0x69, 0xc7, 0x32, 0xcb, 0xf2, 0xf7, 0xa9, 0x0b), - MBEDTLS_BYTES_TO_T_UINT_8(0xd3, 0x52, 0x72, 0x9d, 0xbf, 0x54, 0xea, 0xc7), - MBEDTLS_BYTES_TO_T_UINT_8(0xf5, 0xf3, 0x8a, 0xc5, 0xf0, 0xe1, 0x21, 0x81), - MBEDTLS_BYTES_TO_T_UINT_8(0x8e, 0x61, 0x78, 0xf0, 0x05, 0x00, 0x00, 0x00), -}; -/* Could make ECP_MPI_INIT_ARRAY() available outside ecp, but not doing it now - * as it would lead to conflicts with other in-flight PRs. */ -static const mbedtls_mpi small_primes_product = { - /* .p = */ (mbedtls_mpi_uint *) small_primes_product_limbs, - /* .s = */ 1, - /* .n = */ sizeof(small_primes_product_limbs) / sizeof(mbedtls_mpi_uint), +/* Gaps between primes, starting at 3. https://oeis.org/A001223 */ +static const unsigned char small_prime_gaps[] = { + 2, 2, 4, 2, 4, 2, 4, 6, + 2, 6, 4, 2, 4, 6, 6, 2, + 6, 4, 2, 6, 4, 6, 8, 4, + 2, 4, 2, 4, 14, 4, 6, 2, + 10, 2, 6, 6, 4, 6, 6, 2, + 10, 2, 4, 2, 12, 12, 4, 2, + 4, 6, 2, 10, 6, 6, 6, 2, + 6, 4, 2, 10, 14, 4, 2, 4, + 14, 6, 10, 2, 4, 6, 8, 6, + 6, 4, 6, 8, 4, 8, 10, 2, + 10, 2, 6, 4, 6, 8, 4, 2, + 4, 12, 8, 4, 8, 4, 6, 12, + 2, 18, 6, 10, 6, 6, 2, 6, + 10, 6, 6, 2, 6, 6, 4, 2, + 12, 10, 2, 4, 6, 6, 2, 12, + 4, 6, 8, 10, 8, 10, 8, 6, + 6, 4, 8, 6, 4, 8, 4, 14, + 10, 12, 2, 10, 2, 4, 2, 10, + 14, 4, 2, 4, 14, 4, 2, 4, + 20, 4, 8, 10, 8, 4, 6, 6, + 14, 4, 6, 6, 8, 6, /*reaches 997*/ + 0 /* the last entry is effectively unused */ }; /* @@ -2107,43 +2099,26 @@ static const mbedtls_mpi small_primes_product = { static int mpi_check_small_factors(const mbedtls_mpi *X) { int ret = 0; - mbedtls_mpi g; - - mbedtls_mpi_init(&g); + size_t i; + mbedtls_mpi_uint r; + unsigned p = 3; /* The first odd prime */ if ((X->p[0] & 1) == 0) { return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE; } - /* The GCD test below only works if X > small_primes_limit. - * Below this limit, use trial division: numbers that small are of no - * interest for cryptography, so we don't care about performance or side - * channels. We're supporting them only for backwards compatibility, so - * let's not waste code size on those. */ - if (mbedtls_mpi_cmp_int(X, small_primes_limit) <= 0) { - mbedtls_mpi_uint x = X->p[0]; - mbedtls_mpi_uint d = 2; - while (x % d != 0) { - ++d; + for (i = 0; i < sizeof(small_prime_gaps); p += small_prime_gaps[i], i++) { + MBEDTLS_MPI_CHK(mbedtls_mpi_mod_int(&r, X, p)); + if (r == 0) { + if (mbedtls_mpi_cmp_int(X, p) == 0) { + return 1; + } else { + return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE; + } } - return x == d ? 1 : MBEDTLS_ERR_MPI_NOT_ACCEPTABLE; - } - - /* We can't directly use mbedtls_mpi_gcd_modinv_odd() because we don't know - * if X is larger than prod or not (prod is 1380 bits). So, use this generic - * wrapper - it does a bit more than what we need (handles even inputs as - * well, while we know our inputs are both odd), but that's OK. */ - MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&g, &small_primes_product, X)); - - if (mbedtls_mpi_cmp_int(&g, 1) == 0) { - /* X is not divisible by a small prime */ - ret = 0; - } else { - ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE; } cleanup: - mbedtls_mpi_free(&g); return ret; } diff --git a/src/duckdb/third_party/mbedtls/library/bignum_core.h b/src/duckdb/third_party/mbedtls/library/bignum_core.h index e612ee928..9402659e6 100644 --- a/src/duckdb/third_party/mbedtls/library/bignum_core.h +++ b/src/duckdb/third_party/mbedtls/library/bignum_core.h @@ -526,6 +526,8 @@ void mbedtls_mpi_core_montmul(mbedtls_mpi_uint *X, * the square of the Montgomery constant: * 2^{2*n*biL} mod N. * \param[in] N Little-endian presentation of the modulus, which must be odd. + * It must not have leading zero limbs, i.e. `N->n` + * must be the number of significant limbs of the modulus. * * \return 0 if successful. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if there is not enough space diff --git a/src/duckdb/third_party/mbedtls/library/cipher.cpp b/src/duckdb/third_party/mbedtls/library/cipher.cpp index e6c4f526d..2a5fe1890 100644 --- a/src/duckdb/third_party/mbedtls/library/cipher.cpp +++ b/src/duckdb/third_party/mbedtls/library/cipher.cpp @@ -319,7 +319,8 @@ int mbedtls_cipher_setkey(mbedtls_cipher_context_t *ctx, #endif #if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_DEPRECATED_REMOVED) - if (ctx->psa_enabled == 1) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(ctx->psa_enabled)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING(ctx, ctx->psa_enabled); mbedtls_cipher_context_psa * const cipher_psa = (mbedtls_cipher_context_psa *) ctx->cipher_ctx; @@ -445,7 +446,11 @@ int mbedtls_cipher_set_iv(mbedtls_cipher_context_t *ctx, } #if defined(MBEDTLS_CHACHA20_C) - if (((mbedtls_cipher_type_t) ctx->cipher_info->type) == MBEDTLS_CIPHER_CHACHA20) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(ctx->cipher_info->type == + MBEDTLS_CIPHER_CHACHA20)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + ctx->cipher_info->type, + MBEDTLS_CIPHER_CHACHA20); /* Even though the actual_iv_size is overwritten with a correct value * of 12 from the cipher info, return an error to indicate that * the input iv_len is wrong. */ @@ -468,7 +473,11 @@ int mbedtls_cipher_set_iv(mbedtls_cipher_context_t *ctx, #endif #if defined(MBEDTLS_GCM_C) - if (MBEDTLS_MODE_GCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(MBEDTLS_MODE_GCM == + ctx->cipher_info->mode)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + MBEDTLS_MODE_GCM, + ctx->cipher_info->mode); return mbedtls_gcm_starts((mbedtls_gcm_context *) ctx->cipher_ctx, ctx->operation, iv, iv_len); @@ -476,7 +485,11 @@ int mbedtls_cipher_set_iv(mbedtls_cipher_context_t *ctx, #endif #if defined(MBEDTLS_CCM_C) - if (MBEDTLS_MODE_CCM_STAR_NO_TAG == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(MBEDTLS_MODE_CCM_STAR_NO_TAG == + ctx->cipher_info->mode)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + MBEDTLS_MODE_CCM_STAR_NO_TAG, + ctx->cipher_info->mode); int set_lengths_result; int ccm_star_mode; @@ -546,14 +559,22 @@ int mbedtls_cipher_update_ad(mbedtls_cipher_context_t *ctx, #endif /* MBEDTLS_USE_PSA_CRYPTO && !MBEDTLS_DEPRECATED_REMOVED */ #if defined(MBEDTLS_GCM_C) - if (MBEDTLS_MODE_GCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(MBEDTLS_MODE_GCM == + ctx->cipher_info->mode)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + MBEDTLS_MODE_GCM, + ctx->cipher_info->mode); return mbedtls_gcm_update_ad((mbedtls_gcm_context *) ctx->cipher_ctx, ad, ad_len); } #endif #if defined(MBEDTLS_CHACHAPOLY_C) - if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ((mbedtls_cipher_type_t) ctx->cipher_info->type)) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(MBEDTLS_CIPHER_CHACHA20_POLY1305 == + ctx->cipher_info->type)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + MBEDTLS_CIPHER_CHACHA20_POLY1305, + ctx->cipher_info->type); int result; mbedtls_chachapoly_mode_t mode; @@ -619,7 +640,11 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in } #if defined(MBEDTLS_GCM_C) - if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_GCM) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(MBEDTLS_MODE_GCM == + ctx->cipher_info->mode)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + MBEDTLS_MODE_GCM, + ctx->cipher_info->mode); return mbedtls_gcm_update((mbedtls_gcm_context *) ctx->cipher_ctx, input, ilen, output, ilen, olen); @@ -627,7 +652,11 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in #endif #if defined(MBEDTLS_CCM_C) - if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_CCM_STAR_NO_TAG) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(MBEDTLS_MODE_CCM_STAR_NO_TAG == + ctx->cipher_info->mode)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + MBEDTLS_MODE_CCM_STAR_NO_TAG, + ctx->cipher_info->mode); return mbedtls_ccm_update((mbedtls_ccm_context *) ctx->cipher_ctx, input, ilen, output, ilen, olen); @@ -635,11 +664,18 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in #endif #if defined(MBEDTLS_CHACHAPOLY_C) - if (((mbedtls_cipher_type_t) ctx->cipher_info->type) == MBEDTLS_CIPHER_CHACHA20_POLY1305) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(MBEDTLS_CIPHER_CHACHA20_POLY1305 == + ctx->cipher_info->type)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + MBEDTLS_CIPHER_CHACHA20_POLY1305, + ctx->cipher_info->type); *olen = ilen; return mbedtls_chachapoly_update((mbedtls_chachapoly_context *) ctx->cipher_ctx, ilen, input, output); } + MBEDTLS_CT_NULLIFY_IF_SPECULATING_NE(ctx, + MBEDTLS_CIPHER_CHACHA20_POLY1305, + ctx->cipher_info->type); #endif if (input == output && @@ -1341,7 +1377,8 @@ int mbedtls_cipher_crypt(mbedtls_cipher_context_t *ctx, size_t finish_olen; #if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_DEPRECATED_REMOVED) - if (ctx->psa_enabled == 1) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(ctx->psa_enabled)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING(ctx, ctx->psa_enabled); /* As in the non-PSA case, we don't check that * a key has been set. If not, the key slot will * still be in its default state of 0, which is @@ -1439,7 +1476,8 @@ static int mbedtls_cipher_aead_encrypt(mbedtls_cipher_context_t *ctx, unsigned char *tag, size_t tag_len) { #if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_DEPRECATED_REMOVED) - if (ctx->psa_enabled == 1) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(ctx->psa_enabled)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING(ctx, ctx->psa_enabled); /* As in the non-PSA case, we don't check that * a key has been set. If not, the key slot will * still be in its default state of 0, which is @@ -1516,7 +1554,8 @@ static int mbedtls_cipher_aead_decrypt(mbedtls_cipher_context_t *ctx, const unsigned char *tag, size_t tag_len) { #if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_DEPRECATED_REMOVED) - if (ctx->psa_enabled == 1) { + if (MBEDTLS_CT_SPEC_RISKY_BOOL(ctx->psa_enabled)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING(ctx, ctx->psa_enabled); /* As in the non-PSA case, we don't check that * a key has been set. If not, the key slot will * still be in its default state of 0, which is @@ -1608,6 +1647,24 @@ static int mbedtls_cipher_aead_decrypt(mbedtls_cipher_context_t *ctx, #endif /* MBEDTLS_CIPHER_MODE_AEAD */ #if defined(MBEDTLS_CIPHER_MODE_AEAD) || defined(MBEDTLS_NIST_KW_C) +#if defined(MBEDTLS_NIST_KW_C) +static int mbedtls_cipher_context_is_kw(const mbedtls_cipher_context_t *ctx) +{ +#if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_DEPRECATED_REMOVED) + if (ctx->psa_enabled) { + return 0; + } +#endif + switch (ctx->cipher_info->mode) { + case MBEDTLS_MODE_KW: + case MBEDTLS_MODE_KWP: + return 1; + default: + return 0; + } +} +#endif /* MBEDTLS_NIST_KW_C */ + /* * Packet-oriented encryption for AEAD/NIST_KW: public function. */ @@ -1619,15 +1676,20 @@ int mbedtls_cipher_auth_encrypt_ext(mbedtls_cipher_context_t *ctx, size_t *olen, size_t tag_len) { #if defined(MBEDTLS_NIST_KW_C) - if ( -#if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_DEPRECATED_REMOVED) - ctx->psa_enabled == 0 && -#endif - (MBEDTLS_MODE_KW == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) || - MBEDTLS_MODE_KWP == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode))) { + if (mbedtls_cipher_context_is_kw(ctx)) { mbedtls_nist_kw_mode_t mode = (MBEDTLS_MODE_KW == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) ? MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP; + if (MBEDTLS_CT_SPEC_RISKY_BOOL(mode == MBEDTLS_KW_MODE_KW)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + ctx->cipher_info->mode, + MBEDTLS_MODE_KW); + } + if (MBEDTLS_CT_SPEC_RISKY_BOOL(mode == MBEDTLS_KW_MODE_KWP)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + ctx->cipher_info->mode, + MBEDTLS_MODE_KWP); + } /* There is no iv, tag or ad associated with KW and KWP, * so these length should be 0 as documented. */ @@ -1670,15 +1732,20 @@ int mbedtls_cipher_auth_decrypt_ext(mbedtls_cipher_context_t *ctx, size_t *olen, size_t tag_len) { #if defined(MBEDTLS_NIST_KW_C) - if ( -#if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_DEPRECATED_REMOVED) - ctx->psa_enabled == 0 && -#endif - (MBEDTLS_MODE_KW == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) || - MBEDTLS_MODE_KWP == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode))) { + if (mbedtls_cipher_context_is_kw(ctx)) { mbedtls_nist_kw_mode_t mode = (MBEDTLS_MODE_KW == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) ? MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP; + if (MBEDTLS_CT_SPEC_RISKY_BOOL(mode == MBEDTLS_KW_MODE_KW)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + ctx->cipher_info->mode, + MBEDTLS_MODE_KW); + } + if (MBEDTLS_CT_SPEC_RISKY_BOOL(mode == MBEDTLS_KW_MODE_KWP)) { + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ctx, + ctx->cipher_info->mode, + MBEDTLS_MODE_KWP); + } /* There is no iv, tag or ad associated with KW and KWP, * so these length should be 0 as documented. */ diff --git a/src/duckdb/third_party/mbedtls/library/constant_time_impl.h b/src/duckdb/third_party/mbedtls/library/constant_time_impl.h index aeaeecb7d..afe6bec19 100644 --- a/src/duckdb/third_party/mbedtls/library/constant_time_impl.h +++ b/src/duckdb/third_party/mbedtls/library/constant_time_impl.h @@ -538,4 +538,14 @@ static inline mbedtls_ct_condition_t mbedtls_ct_bool_not(mbedtls_ct_condition_t #pragma GCC diagnostic pop #endif +#if defined(MBEDTLS_SPECTRE_V1_COUNTERMEASURES) +static inline uintptr_t mbedtls_ct_nullify_if_speculating(uintptr_t value, + mbedtls_ct_uint_t cond) +{ + MBEDTLS_STATIC_ASSERT(sizeof(uintptr_t) <= sizeof(mbedtls_ct_condition_t), + "mbedtls_ct_condition_t smaller than uintptr_t is not supported"); + return value & mbedtls_ct_bool(cond); +} +#endif /* MBEDTLS_SPECTRE_V1_COUNTERMEASURES */ + #endif /* MBEDTLS_CONSTANT_TIME_IMPL_H */ diff --git a/src/duckdb/third_party/mbedtls/library/constant_time_internal.h b/src/duckdb/third_party/mbedtls/library/constant_time_internal.h index 61a5c6d4e..5bef2e319 100644 --- a/src/duckdb/third_party/mbedtls/library/constant_time_internal.h +++ b/src/duckdb/third_party/mbedtls/library/constant_time_internal.h @@ -573,6 +573,139 @@ int mbedtls_ct_memcmp_partial(const void *a, #endif +/* The code below provides countermeasures for Spectre v1 countermeasures, + * i.e. defenses against timing-based side channels in speculatively + * executed code. It is currently possible to disable these countermeasures + * by configuring the library with -DMBEDTLS_SPECTRE_V1_COUNTERMEASURES=0, + * however this is not officially supported and may be removed without + * notice. + * */ +#if defined(MBEDTLS_SPECTRE_V1_COUNTERMEASURES) +# if !(MBEDTLS_SPECTRE_V1_COUNTERMEASURES) +# undef MBEDTLS_SPECTRE_V1_COUNTERMEASURES +# endif +#else +# define MBEDTLS_SPECTRE_V1_COUNTERMEASURES +#endif + +#if defined(MBEDTLS_SPECTRE_V1_COUNTERMEASURES) + +/** Use this macro on the condition of if statements where wrongly executing + * one of the branches speculatively may leak sensitive data. + * + * \note This macro alone has no useful effect. It is a + * complement for e.g. #MBEDTLS_CT_NULLIFY_IF_SPECULATING. + * + * This is part of a countermeasure against Spectre v1 attacks. + * + * \param value An integral-valued expression. + * It will be executed exactly once. + * \return The value of \p value. + */ +#define MBEDTLS_CT_SPEC_RISKY_BOOL(value) \ + mbedtls_ct_compiler_opaque(value) + +static inline uintptr_t mbedtls_ct_nullify_if_speculating(uintptr_t value, + mbedtls_ct_uint_t cond); + +/** Mask under speculative execution. + * + * Use this macro in a branch whose condition is \p cond. + * If the branch is being executed speculatively, set \p ptr to \c NULL. + * (Note: this sets the pointer variable. The pointer is not dereferenced.) + * If the branch is being executed normally, leave \p ptr unchanged. + * + * On processors that do not perform speculative execution, this is always + * a no-op (except for possible side effects of the given expressions). + * + * The behavior is unspecified when not in a branch whose condition is \p cond. + * + * This macro is intended to prevent potential Spectre v1 (Spectre-PHT) + * side channels, where the speculative execution of a branch can leak + * sensitive data through the address of a memory access. + * + * \note Compilers may optimize \p cond in a way that makes + * this countermeasure ineffective on its own. To prevent + * this, use #MBEDTLS_CT_SPEC_RISKY_BOOL on the if condition. + * + * Usage example: + * ``` + * if (MBEDTLS_CT_SPEC_RISKY_BOOL(key.is_public)) { + * MBEDTLS_CT_NULLIFY_IF_SPECULATING(key_buffer, key.is_public); + * parse_public_key_in_variable_time(key_buffer, key_buffer_length); + * } else { + * parse_private_key_in_constant_time(key_buffer, key_buffer_length); + * } + * ``` + * + * \param ptr A pointer lvalue. + * It may be evaluated zero, one or multiple times, hence + * this expression should not have any side effects. + * \param cond An expression with integral value. + * It may be evaluated zero, one or multiple times, hence + * this expression should not have any side effects. + * This expression should be compiled to code that does + * not use branches or other conditional instructions, + * otherwise the calculation of \p cond here may + * reintroduce a Spectre v1 gadget. To avoid this, + * use another macro such as + * #MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ or + * #MBEDTLS_CT_NULLIFY_IF_SPECULATING_NE if applicable. + */ +#define MBEDTLS_CT_NULLIFY_IF_SPECULATING(ptr, cond) \ + ((ptr) = (decltype(+(ptr))) mbedtls_ct_nullify_if_speculating((uintptr_t) (ptr), cond)) + +#else /* MBEDTLS_SPECTRE_V1_COUNTERMEASURES */ + +#define MBEDTLS_CT_SPEC_RISKY_BOOL(value) (value) + +#define MBEDTLS_CT_NULLIFY_IF_SPECULATING(ptr, cond) \ + (void) (ptr) + +#endif /* MBEDTLS_SPECTRE_V1_COUNTERMEASURES */ + +/** Mask under speculative execution of an equality condition. + * + * This is functionally equivalent to + * #MBEDTLS_CT_NULLIFY_IF_SPECULATING(\p ptr, (\p lhs) == (\p rhs)) + * but it protects against the equality being compiled to code using + * a conditional instruction that may introduce a further Spectre v1 + * gadget. + * + * \param ptr A pointer lvalue. + * It may be evaluated zero, one or multiple times, hence + * this expression should not have any side effects. + * \param lhs An expression with an integral value. + * It may be evaluated zero, one or multiple times, hence + * this expression should not have any side effects. + * \param rhs An expression with an integral value. + * It may be evaluated zero, one or multiple times, hence + * this expression should not have any side effects. + */ +#define MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(ptr, lhs, rhs) \ + MBEDTLS_CT_NULLIFY_IF_SPECULATING(ptr, mbedtls_ct_uint_eq(lhs, rhs)) + +/** Mask under speculative execution of a negated equality condition. + * + * This is functionally equivalent to + * #MBEDTLS_CT_NULLIFY_IF_SPECULATING(\p ptr, (\p lhs) != (\p rhs)) + * but it protects against the equality being compiled to code using + * a conditional instruction that may introduce a further Spectre v1 + * gadget. + * + * \param ptr A pointer lvalue. + * It may be evaluated zero, one or multiple times, hence + * this expression should not have any side effects. + * \param lhs An expression with an integral value. + * It may be evaluated zero, one or multiple times, hence + * this expression should not have any side effects. + * \param rhs An expression with an integral value. + * It may be evaluated zero, one or multiple times, hence + * this expression should not have any side effects. + */ +#define MBEDTLS_CT_NULLIFY_IF_SPECULATING_NE(ptr, lhs, rhs) \ + MBEDTLS_CT_NULLIFY_IF_SPECULATING(ptr, mbedtls_ct_uint_ne(lhs, rhs)) + /* Include the implementation of static inline functions above. */ #include "constant_time_impl.h" diff --git a/src/duckdb/third_party/mbedtls/library/gcm.cpp b/src/duckdb/third_party/mbedtls/library/gcm.cpp index 5dfac2349..d3e458468 100644 --- a/src/duckdb/third_party/mbedtls/library/gcm.cpp +++ b/src/duckdb/third_party/mbedtls/library/gcm.cpp @@ -34,10 +34,10 @@ #if defined(MBEDTLS_AESNI_C) #include "aesni.h" #endif - #if defined(MBEDTLS_AESCE_C) #include "aesce.h" #endif +#include "constant_time_internal.h" #if !defined(MBEDTLS_GCM_ALT) @@ -47,6 +47,34 @@ #define MBEDTLS_GCM_ACC_AESNI 2 #define MBEDTLS_GCM_ACC_AESCE 3 +/* 1 if hardware support is present at runtime, 0 otherwise. + * Undefined macro if no hardware support code is enabled. + * + * This macro is only used for re-checking, so it can directly + * reference a variable, it doesn't need to call the checking code. + */ +#if defined(MBEDTLS_AESNI_HAVE_CODE) +#define MBEDTLS_GCM_HAVE_HARDWARE \ + mbedtls_aesni_has_support(MBEDTLS_AESNI_CLMUL) +#endif +#if defined(MBEDTLS_AESCE_HAVE_CODE) +#define MBEDTLS_GCM_HAVE_HARDWARE MBEDTLS_AESCE_HAS_SUPPORT_RECHECK +#endif + +/* Similar to mbedtls_aes_block_speculation_of_no_hardware() in aes.c. + * See the documentation of that function. */ +static void mbedtls_gcm_block_speculation_of_no_hardware( + mbedtls_gcm_context **pctx) +{ +#if defined(MBEDTLS_SPECTRE_V1_COUNTERMEASURES) && \ + defined(MBEDTLS_GCM_HAVE_HARDWARE) + MBEDTLS_CT_NULLIFY_IF_SPECULATING_EQ(*pctx, MBEDTLS_GCM_HAVE_HARDWARE, 0); +#else + (void) pctx; +#endif + +} + /* * Initialize a context */ @@ -130,6 +158,8 @@ static int gcm_gen_table(mbedtls_gcm_context *ctx) #endif default: + mbedtls_gcm_block_speculation_of_no_hardware(&ctx); + /* 0 corresponds to 0 in GF(2^128) */ ctx->H[0][0] = 0; ctx->H[0][1] = 0; @@ -362,10 +392,12 @@ static void gcm_mult(mbedtls_gcm_context *ctx, const unsigned char x[16], #if defined(MBEDTLS_GCM_LARGE_TABLE) case MBEDTLS_GCM_ACC_LARGETABLE: + mbedtls_gcm_block_speculation_of_no_hardware(&ctx); gcm_mult_largetable(output, x, ctx->H); break; #else case MBEDTLS_GCM_ACC_SMALLTABLE: + mbedtls_gcm_block_speculation_of_no_hardware(&ctx); gcm_mult_smalltable(output, x, ctx->H); break; #endif diff --git a/src/duckdb/third_party/mbedtls/library/oid.cpp b/src/duckdb/third_party/mbedtls/library/oid.cpp index fdaa52dee..b7a56b53a 100644 --- a/src/duckdb/third_party/mbedtls/library/oid.cpp +++ b/src/duckdb/third_party/mbedtls/library/oid.cpp @@ -995,7 +995,7 @@ static int oid_parse_number(unsigned int *num, const char **p, const char *bound while (*p < bound && **p >= '0' && **p <= '9') { ret = 0; - if (*num > (UINT_MAX / 10)) { + if (*num > (UINT_MAX - (unsigned int) (**p - '0')) / 10) { return MBEDTLS_ERR_ASN1_INVALID_DATA; } *num *= 10; diff --git a/src/duckdb/third_party/mbedtls/library/pk_internal.h b/src/duckdb/third_party/mbedtls/library/pk_internal.h index d1c26421d..a57b5545b 100644 --- a/src/duckdb/third_party/mbedtls/library/pk_internal.h +++ b/src/duckdb/third_party/mbedtls/library/pk_internal.h @@ -153,7 +153,7 @@ static inline mbedtls_ecp_group_id mbedtls_pk_get_ec_group_id(const mbedtls_pk_c #endif /* MBEDTLS_ECP_HAVE_CURVE25519 || MBEDTLS_ECP_DP_CURVE448 */ #define MBEDTLS_PK_IS_RFC8410_GROUP_ID(id) \ - ((id == MBEDTLS_ECP_DP_CURVE25519) || (id == MBEDTLS_ECP_DP_CURVE448)) + (((id) == MBEDTLS_ECP_DP_CURVE25519) || ((id) == MBEDTLS_ECP_DP_CURVE448)) static inline int mbedtls_pk_is_rfc8410(const mbedtls_pk_context *pk) { diff --git a/src/duckdb/third_party/mbedtls/library/sha1.cpp b/src/duckdb/third_party/mbedtls/library/sha1.cpp index dacfe263f..72aa2f898 100644 --- a/src/duckdb/third_party/mbedtls/library/sha1.cpp +++ b/src/duckdb/third_party/mbedtls/library/sha1.cpp @@ -257,6 +257,10 @@ int mbedtls_sha1_update(mbedtls_sha1_context *ctx, ctx->total[1]++; } +#if SIZE_MAX > 0xFFFFFFFF + ctx->total[1] += (uint32_t) (ilen >> 32); +#endif + if (left && ilen >= fill) { memcpy((void *) (ctx->buffer + left), input, fill); diff --git a/src/duckdb/third_party/mbedtls/library/sha256.cpp b/src/duckdb/third_party/mbedtls/library/sha256.cpp index 4f1ac3e0f..06d2f53bc 100644 --- a/src/duckdb/third_party/mbedtls/library/sha256.cpp +++ b/src/duckdb/third_party/mbedtls/library/sha256.cpp @@ -667,6 +667,10 @@ int mbedtls_sha256_update(mbedtls_sha256_context *ctx, ctx->total[1]++; } +#if SIZE_MAX > 0xFFFFFFFF + ctx->total[1] += (uint32_t) (ilen >> 32); +#endif + if (left && ilen >= fill) { memcpy((void *) (ctx->buffer + left), input, fill); diff --git a/src/duckdb/ub_src_common_enums.cpp b/src/duckdb/ub_src_common_enums.cpp index c90e668fb..e84951fa7 100644 --- a/src/duckdb/ub_src_common_enums.cpp +++ b/src/duckdb/ub_src_common_enums.cpp @@ -20,7 +20,5 @@ #include "src/common/enums/physical_operator_type.cpp" -#include "src/common/enums/relation_type.cpp" - #include "src/common/enums/statement_type.cpp" diff --git a/src/duckdb/ub_src_execution_operator_join.cpp b/src/duckdb/ub_src_execution_operator_join.cpp index f971faf76..7b6ae0b97 100644 --- a/src/duckdb/ub_src_execution_operator_join.cpp +++ b/src/duckdb/ub_src_execution_operator_join.cpp @@ -1,3 +1,5 @@ +#include "src/execution/operator/join/join_filter_pushdown.cpp" + #include "src/execution/operator/join/outer_join_marker.cpp" #include "src/execution/operator/join/physical_asof_join.cpp" diff --git a/src/duckdb/ub_src_function.cpp b/src/duckdb/ub_src_function.cpp index 41f820603..a0de8267b 100644 --- a/src/duckdb/ub_src_function.cpp +++ b/src/duckdb/ub_src_function.cpp @@ -4,6 +4,8 @@ #include "src/function/built_in_functions.cpp" +#include "src/function/builtin_encodings.cpp" + #include "src/function/builtin_function_lookup.cpp" #include "src/function/cast_rules.cpp" diff --git a/src/duckdb/ub_src_main.cpp b/src/duckdb/ub_src_main.cpp index cf519f2f7..df179ab8d 100644 --- a/src/duckdb/ub_src_main.cpp +++ b/src/duckdb/ub_src_main.cpp @@ -10,8 +10,6 @@ #include "src/main/client_context_file_opener.cpp" -#include "src/main/client_context_wrapper.cpp" - #include "src/main/client_data.cpp" #include "src/main/client_verify.cpp" @@ -64,8 +62,6 @@ #include "src/main/query_result_stream.cpp" -#include "src/main/relation.cpp" - #include "src/main/result_format.cpp" #include "src/main/result_set_manager.cpp" diff --git a/src/duckdb/ub_src_main_capi_v2.cpp b/src/duckdb/ub_src_main_capi_v2.cpp index 8151035b6..84ce08ce6 100644 --- a/src/duckdb/ub_src_main_capi_v2.cpp +++ b/src/duckdb/ub_src_main_capi_v2.cpp @@ -62,6 +62,8 @@ #include "src/main/capi/v2/capi_v2_logical_type.cpp" +#include "src/main/capi/v2/capi_v2_object_cache.cpp" + #include "src/main/capi/v2/capi_v2_option.cpp" #include "src/main/capi/v2/capi_v2_prepared_statement.cpp" diff --git a/src/duckdb/ub_src_main_relation.cpp b/src/duckdb/ub_src_main_relation.cpp deleted file mode 100644 index 4087d6f10..000000000 --- a/src/duckdb/ub_src_main_relation.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "src/main/relation/aggregate_relation.cpp" - -#include "src/main/relation/create_table_relation.cpp" - -#include "src/main/relation/create_view_relation.cpp" - -#include "src/main/relation/cross_product_relation.cpp" - -#include "src/main/relation/delete_relation.cpp" - -#include "src/main/relation/delim_get_relation.cpp" - -#include "src/main/relation/distinct_relation.cpp" - -#include "src/main/relation/explain_relation.cpp" - -#include "src/main/relation/filter_relation.cpp" - -#include "src/main/relation/insert_relation.cpp" - -#include "src/main/relation/join_relation.cpp" - -#include "src/main/relation/limit_relation.cpp" - -#include "src/main/relation/materialized_relation.cpp" - -#include "src/main/relation/order_relation.cpp" - -#include "src/main/relation/projection_relation.cpp" - -#include "src/main/relation/query_relation.cpp" - -#include "src/main/relation/read_csv_relation.cpp" - -#include "src/main/relation/read_json_relation.cpp" - -#include "src/main/relation/setop_relation.cpp" - -#include "src/main/relation/subquery_relation.cpp" - -#include "src/main/relation/table_function_relation.cpp" - -#include "src/main/relation/table_relation.cpp" - -#include "src/main/relation/update_relation.cpp" - -#include "src/main/relation/value_relation.cpp" - -#include "src/main/relation/view_relation.cpp" - -#include "src/main/relation/write_csv_relation.cpp" - -#include "src/main/relation/write_parquet_relation.cpp" - diff --git a/src/duckdb/ub_src_optimizer.cpp b/src/duckdb/ub_src_optimizer.cpp index 68664b8eb..5a1d9f656 100644 --- a/src/duckdb/ub_src_optimizer.cpp +++ b/src/duckdb/ub_src_optimizer.cpp @@ -34,10 +34,14 @@ #include "src/optimizer/cte_runtime_filter_pushdown.cpp" +#include "src/optimizer/cte_semi_join_filter_transfer.cpp" + #include "src/optimizer/deliminator.cpp" #include "src/optimizer/disjunctive_join_rewriter.cpp" +#include "src/optimizer/distinctness.cpp" + #include "src/optimizer/duplicate_eliminated_domain_optimizer.cpp" #include "src/optimizer/empty_result_pullup.cpp" @@ -64,20 +68,24 @@ #include "src/optimizer/join_filter_pushdown_optimizer.cpp" +#include "src/optimizer/join_simplification.cpp" + +#include "src/optimizer/join_to_semi_join.cpp" + #include "src/optimizer/late_materialization.cpp" #include "src/optimizer/late_materialization_helper.cpp" #include "src/optimizer/limit_pushdown.cpp" +#include "src/optimizer/mark_join_simplifier.cpp" + #include "src/optimizer/materialized_aggregate_reuse.cpp" #include "src/optimizer/multi_stage_aggregate_rewriter.cpp" #include "src/optimizer/optimizer.cpp" -#include "src/optimizer/outer_join_simplification.cpp" - #include "src/optimizer/partial_aggregate_pushdown.cpp" #include "src/optimizer/partitioned_execution.cpp" @@ -94,6 +102,8 @@ #include "src/optimizer/remove_duplicate_groups.cpp" +#include "src/optimizer/remove_redundant_distinct.cpp" + #include "src/optimizer/remove_redundant_order.cpp" #include "src/optimizer/remove_redundant_order_keys.cpp" @@ -114,6 +124,8 @@ #include "src/optimizer/self_join_aggregate.cpp" +#include "src/optimizer/set_operation_aggregate.cpp" + #include "src/optimizer/statistics_propagator.cpp" #include "src/optimizer/topn_optimizer.cpp" @@ -124,6 +136,8 @@ #include "src/optimizer/unnest_rewriter.cpp" +#include "src/optimizer/window_fusion.cpp" + #include "src/optimizer/window_join_pushdown.cpp" #include "src/optimizer/window_self_join.cpp" diff --git a/src/duckdb/ub_src_parallel.cpp b/src/duckdb/ub_src_parallel.cpp index 1b7650140..9542838a8 100644 --- a/src/duckdb/ub_src_parallel.cpp +++ b/src/duckdb/ub_src_parallel.cpp @@ -34,8 +34,12 @@ #include "src/parallel/runtime_filter_schedule.cpp" +#include "src/parallel/scan_affinity_queue.cpp" + #include "src/parallel/scan_read_ahead.cpp" +#include "src/parallel/sharded_counter.cpp" + #include "src/parallel/task_executor.cpp" #include "src/parallel/task_notifier.cpp" diff --git a/src/duckdb/ub_src_parser_parsed_data.cpp b/src/duckdb/ub_src_parser_parsed_data.cpp index dc2fca713..20e161f76 100644 --- a/src/duckdb/ub_src_parser_parsed_data.cpp +++ b/src/duckdb/ub_src_parser_parsed_data.cpp @@ -22,8 +22,6 @@ #include "src/parser/parsed_data/create_aggregate_function_info.cpp" -#include "src/parser/parsed_data/create_collation_info.cpp" - #include "src/parser/parsed_data/create_coordinate_system_info.cpp" #include "src/parser/parsed_data/create_copy_function_info.cpp" diff --git a/src/duckdb/ub_src_parser_statement.cpp b/src/duckdb/ub_src_parser_statement.cpp index 7e5862f60..a82fb2102 100644 --- a/src/duckdb/ub_src_parser_statement.cpp +++ b/src/duckdb/ub_src_parser_statement.cpp @@ -44,8 +44,6 @@ #include "src/parser/statement/prepare_statement.cpp" -#include "src/parser/statement/relation_statement.cpp" - #include "src/parser/statement/select_statement.cpp" #include "src/parser/statement/set_statement.cpp" diff --git a/src/duckdb/ub_src_parser_tableref.cpp b/src/duckdb/ub_src_parser_tableref.cpp index bdaaa9042..2015276a1 100644 --- a/src/duckdb/ub_src_parser_tableref.cpp +++ b/src/duckdb/ub_src_parser_tableref.cpp @@ -6,8 +6,6 @@ #include "src/parser/tableref/column_data_ref.cpp" -#include "src/parser/tableref/delimgetref.cpp" - #include "src/parser/tableref/emptytableref.cpp" #include "src/parser/tableref/expressionlistref.cpp" diff --git a/src/duckdb/ub_src_planner_binder_statement.cpp b/src/duckdb/ub_src_planner_binder_statement.cpp index 3604a144f..56ce0ed02 100644 --- a/src/duckdb/ub_src_planner_binder_statement.cpp +++ b/src/duckdb/ub_src_planner_binder_statement.cpp @@ -42,8 +42,6 @@ #include "src/planner/binder/statement/bind_prepare.cpp" -#include "src/planner/binder/statement/bind_relation.cpp" - #include "src/planner/binder/statement/bind_select.cpp" #include "src/planner/binder/statement/bind_set.cpp" diff --git a/src/duckdb/ub_src_planner_binder_tableref.cpp b/src/duckdb/ub_src_planner_binder_tableref.cpp index 8973efb30..64e86b521 100644 --- a/src/duckdb/ub_src_planner_binder_tableref.cpp +++ b/src/duckdb/ub_src_planner_binder_tableref.cpp @@ -4,8 +4,6 @@ #include "src/planner/binder/tableref/bind_column_data_ref.cpp" -#include "src/planner/binder/tableref/bind_delimgetref.cpp" - #include "src/planner/binder/tableref/bind_emptytableref.cpp" #include "src/planner/binder/tableref/bind_expressionlistref.cpp" diff --git a/src/duckdb/ub_src_planner_subquery.cpp b/src/duckdb/ub_src_planner_subquery.cpp index 179302655..14f5739f9 100644 --- a/src/duckdb/ub_src_planner_subquery.cpp +++ b/src/duckdb/ub_src_planner_subquery.cpp @@ -2,6 +2,8 @@ #include "src/planner/subquery/flatten_dependent_join.cpp" +#include "src/planner/subquery/has_volatile_expressions.cpp" + #include "src/planner/subquery/pair_dependent_full_outer_join.cpp" #include "src/planner/subquery/pair_dependent_join.cpp" diff --git a/src/test/java/org/duckdb/TestDuckDBJDBC.java b/src/test/java/org/duckdb/TestDuckDBJDBC.java index d418d0a38..485c4fb5c 100644 --- a/src/test/java/org/duckdb/TestDuckDBJDBC.java +++ b/src/test/java/org/duckdb/TestDuckDBJDBC.java @@ -1883,7 +1883,7 @@ public static void test_all_types() throws Exception { try { String sql = // TODO: remove excludes - "select * EXCLUDE(time, time_ns, time_tz, timestamp_tz_ns, empty_struct, tuple)" + "select * EXCLUDE(time, time_ns, time_tz, timestamp_tz_ns, empty_struct, tuple, geography)" + "\n , CASE WHEN time = '24:00:00'::TIME THEN '23:59:59.999999'::TIME ELSE time END AS time" + "\n , CASE WHEN time_ns = '24:00:00'::TIME_NS THEN '23:59:59.999999'::TIME_NS ELSE time_ns END " + "AS time_ns"